问:
Android Studio/Kotlin - findViewById crash my app
The program stop when it reach the findViewById and I can't figure out why :

```<code>    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.splash_screen)

    handler.postDelayed({ setContentView(R.layout.activity_main) }, 500) // 5 seconds
    val imageView: ImageView = findViewById(R.id.splashScreenIMG)
    Glide.with(this).load(R.drawable.sligames_waiting).into(imageView)
}

    fun showButtons()
{
    val view: View = findViewById(R.id.boutonOui)
    val cx = view.width / 2
    val cy = view.height / 2
    val finalRadius = hypot(cx.toDouble(), cy.toDouble()).toFloat()
    val anim = ViewAnimationUtils.createCircularReveal(view, cx, cy, 0f, finalRadius)
    // make the view visible and start the animation
    view.visibility = View.VISIBLE
    anim.duration = 1500
    anim.start()
}
</code>```

I execute this function from another file with this line :

```<code>MainActivity().showButtons()
</code>```

Here's the stack trace :

```<code>2020-06-01 12:55:02.783 22557-22557/com.example.yourmajesty E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.yourmajesty, PID: 22557
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
    at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:163)
    at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:174)
    at android.content.Context.obtainStyledAttributes(Context.java:738)
    at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
    at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
    at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
    at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
    at com.example.yourmajesty.MainActivity.showButtons(MainActivity.kt:122)
    at com.example.yourmajesty.Dialog.dialogChanger(Dialog.kt:26)
    at com.example.yourmajesty.MainActivity$dialogBoxDiseappear$2.run(MainActivity.kt:190)
    at android.os.Handler.handleCallback(Handler.java:883)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7695)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
</code>```

Thanks in advance

答:
For creating a reference to a class's objects in Kotlin, you can use

(activity as MainActivity!!)?.showButtons()

What this will do is it will create a reference of already running class instead of creating one more instance which will always give NPE for Views as it's not instantiated.

Also, remember referencing views of other Class or Fragment only works when that class has a running instance, you can reference functions which don't actually need to create views and only need the Context, but referencing Views or any objects which need to be initialized first give the NPE.

Body:
The program stop when it reach the findViewById and I can't figure out why :

    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.splash_screen)

    handler.postDelayed({ setContentView(R.layout.activity_main) }, 500) // 5 seconds
    val imageView: ImageView = findViewById(R.id.splashScreenIMG)
    Glide.with(this).load(R.drawable.sligames_waiting).into(imageView)
}

    fun showButtons()
{
    val view: View = findViewById(R.id.boutonOui)
    val cx = view.width / 2
    val cy = view.height / 2
    val finalRadius = hypot(cx.toDouble(), cy.toDouble()).toFloat()
    val anim = ViewAnimationUtils.createCircularReveal(view, cx, cy, 0f, finalRadius)
    // make the view visible and start the animation
    view.visibility = View.VISIBLE
    anim.duration = 1500
    anim.start()
}

I execute this function from another file with this line :

MainActivity().showButtons()

Here's the stack trace :

2020-06-01 12:55:02.783 22557-22557/com.example.yourmajesty E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.yourmajesty, PID: 22557
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
    at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:163)
    at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:174)
    at android.content.Context.obtainStyledAttributes(Context.java:738)
    at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
    at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
    at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
    at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
    at com.example.yourmajesty.MainActivity.showButtons(MainActivity.kt:122)
    at com.example.yourmajesty.Dialog.dialogChanger(Dialog.kt:26)
    at com.example.yourmajesty.MainActivity$dialogBoxDiseappear$2.run(MainActivity.kt:190)
    at android.os.Handler.handleCallback(Handler.java:883)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7695)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)

Thanks in advance


来源: stackexchange

问:
toODataString Method Throwing error filterOperators(...) is not a function Kendo Angular
I am using Filter widget of Kendo UI for Angular. For converting the filter Expression to oData Query I am using toODataQuery method and passing state to it.

While adding Groups I am getting

```<code> filterOperators(...) is not a function
    at odata-filtering.operators.js:69
    at funcs.js:4
    at odata-filtering.operators.js:70
    at Array.map (<anonymous>)
</code>```

I  have created stackblitz for the same: https://stackblitz.com/edit/angular-ivy-gny5pv?file=src%2Fapp%2Fapp.component.ts

I am able to reproduce the error but error is different.
What I am doing wrong...??

app.component.ts:

```<code>import { Component, OnInit, ElementRef, ViewChild, Output, Input, EventEmitter } from '@angular/core';
import { CompositeFilterDescriptor, FilterDescriptor, State, toODataString, normalizeFilters } from '@progress/kendo-data-query';

declare var kendo: any;

@Component({
    selector: 'my-app',
    template: `
        <div #positionFilter></div>
    `
})
export class AppComponent implements OnInit {
    @ViewChild('positionFilter',{static: true}) positionFilter: ElementRef;
    public filterExpression: CompositeFilterDescriptor;
 public state: State = {
    skip: 0,
    take: 5,
    // Initial filter descriptor
    filter: null
  };

   ngOnInit() {
         this.loadFilter(this.positionFilter.nativeElement,  this.filterExpression);

   }

   public loadFilter(filterContainer,  expressionVal) {
    kendo.jQuery(filterContainer).kendoFilter({
      dataSource: [],
      //applyButton: false,
      expressionPreview: true,
      expression: expressionVal,
      change: this.onChangeFieldDropDownEvent.bind(this),
      fields: [
          { name: "ProductName",type: "string", label: "String" },
          { name: "CategoryID", type: "number", label: "Number"},
          { name: "UnitPrice", type: "boolean", label: "boolean"},
          { name: "UnitsInStock", type: "date", label: "Date" }
      ]
    });
  }

  onChangeFieldDropDownEvent(e) {
    console.log('Filter Expression--', e.expression);
    this.addSearch();
    this.filterExpression = e.expression;//.filters;
    this.updateState(this.filterExpression);
    let serializedFilterValue = this.serializeFilter(this.state);
    console.log('serializedFilterValue----', serializedFilterValue)

  }

  public updateState(filter) {
    this.state.filter = filter;
  }
  private serializeFilter(state: State): string {
    return toODataString(state);
  }

   public addSearch() {
    let container = this.positionFilter.nativeElement;
    kendo.jQuery(container).find(".k-filter-field select.k-filter-dropdown").each(function (i, x) {
      kendo.jQuery(x).data("kendoDropDownList").setOptions({ filter: "contains" });
    });
  }
}
</code>```

答:
I had raised this with Kendo Team.

This is what they suggested:

The issue occurs since the toODataString fails to serialize empty filter objects. A possible solution would be to remove all empty filters before serializing the parameters.
e.g.

```<code>  private serializeFilter(state: State): string {
    removeEmptyFilters(state.filter)
    return toODataString(state);
  }

  function removeEmptyFilters(expression){
    var that = this;
            if (expression.filters) {
            expression.filters =  kendo.jQuery.grep(expression.filters, function(filter) {
                removeEmptyFilters(filter);
                if (filter.filters) {
                    return filter.filters.length;
                } else {
                    return filter.value;
                }
            });
        }
  }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using Filter widget of Kendo UI for Angular. For converting the filter Expression to oData Query I am using toODataQuery method and passing state to it.

While adding Groups I am getting

 filterOperators(...) is not a function
    at odata-filtering.operators.js:69
    at funcs.js:4
    at odata-filtering.operators.js:70
    at Array.map (<anonymous>)

I  have created stackblitz for the same: https://stackblitz.com/edit/angular-ivy-gny5pv?file=src%2Fapp%2Fapp.component.ts

I am able to reproduce the error but error is different.
What I am doing wrong...??

app.component.ts:

import { Component, OnInit, ElementRef, ViewChild, Output, Input, EventEmitter } from '@angular/core';
import { CompositeFilterDescriptor, FilterDescriptor, State, toODataString, normalizeFilters } from '@progress/kendo-data-query';

declare var kendo: any;

@Component({
    selector: 'my-app',
    template: `

    `
})
export class AppComponent implements OnInit {
    @ViewChild('positionFilter',{static: true}) positionFilter: ElementRef;
    public filterExpression: CompositeFilterDescriptor;
 public state: State = {
    skip: 0,
    take: 5,
    // Initial filter descriptor
    filter: null
  };

   ngOnInit() {
         this.loadFilter(this.positionFilter.nativeElement,  this.filterExpression);

   }

   public loadFilter(filterContainer,  expressionVal) {
    kendo.jQuery(filterContainer).kendoFilter({
      dataSource: [],
      //applyButton: false,
      expressionPreview: true,
      expression: expressionVal,
      change: this.onChangeFieldDropDownEvent.bind(this),
      fields: [
          { name: "ProductName",type: "string", label: "String" },
          { name: "CategoryID", type: "number", label: "Number"},
          { name: "UnitPrice", type: "boolean", label: "boolean"},
          { name: "UnitsInStock", type: "date", label: "Date" }
      ]
    });
  }

  onChangeFieldDropDownEvent(e) {
    console.log('Filter Expression--', e.expression);
    this.addSearch();
    this.filterExpression = e.expression;//.filters;
    this.updateState(this.filterExpression);
    let serializedFilterValue = this.serializeFilter(this.state);
    console.log('serializedFilterValue----', serializedFilterValue)

  }

  public updateState(filter) {
    this.state.filter = filter;
  }
  private serializeFilter(state: State): string {
    return toODataString(state);
  }

   public addSearch() {
    let container = this.positionFilter.nativeElement;
    kendo.jQuery(container).find(".k-filter-field select.k-filter-dropdown").each(function (i, x) {
      kendo.jQuery(x).data("kendoDropDownList").setOptions({ filter: "contains" });
    });
  }
}

Body:
I had raised this with Kendo Team.

This is what they suggested:

The issue occurs since the toODataString fails to serialize empty filter objects. A possible solution would be to remove all empty filters before serializing the parameters.
e.g.

  private serializeFilter(state: State): string {
    removeEmptyFilters(state.filter)
    return toODataString(state);
  }

  function removeEmptyFilters(expression){
    var that = this;
            if (expression.filters) {
            expression.filters =  kendo.jQuery.grep(expression.filters, function(filter) {
                removeEmptyFilters(filter);
                if (filter.filters) {
                    return filter.filters.length;
                } else {
                    return filter.value;
                }
            });
        }
  }


问:
Selenium Python find button with <button type="button" class="size-grid-dropdown size-grid-button" data-qa="size-dropdown">AB 12</button>
i'm trying to find with selenium in python a button in a website and the button identify is:
AB 12

I'm trying with this code but all can't find the button...

```<code>driver.find_element_by_xpath("//button[contains(@class, '.size-grid-dropdown .size-grid-button') and contains(.,'AB 12)]")

driver.find_element_by_xpath('//button[span[text()="AB 12"]')

driver.find_element_by_link_text("AB 12")
</code>```

the problem is: i have a lot of button with same class but different AB 12 / AB 23 / AB 34...

How can i find a precisely button?

Thanks!

答:
Presuming the id of the button is AB 12, the code you want is:

driver.find_element_by_id('AB 12')

you can see this answer for a similar query: >How to use find_element_by_id() in python
  or read the docs for the same here:
  https://selenium-python.readthedocs.io/api.html#locate-elements-by

In hindsight i see you want to find a button element with the text "AB 12"
the correct code for that would be:

```<code>driver.find_element_by_xpath('//button[text()="AB 12"]')
</code>```

You can check this similar query for more variations:
How to find button with Selenium by its text inside (Python)?

Body:
i'm trying to find with selenium in python a button in a website and the button identify is:
AB 12

I'm trying with this code but all can't find the button...

driver.find_element_by_xpath("//button[contains(@class, '.size-grid-dropdown .size-grid-button') and contains(.,'AB 12)]")

driver.find_element_by_xpath('//button[span[text()="AB 12"]')

driver.find_element_by_link_text("AB 12")

the problem is: i have a lot of button with same class but different AB 12 / AB 23 / AB 34...

How can i find a precisely button?

Thanks!

Body:
Presuming the id of the button is AB 12, the code you want is:

driver.find_element_by_id('AB 12')

you can see this answer for a similar query: >How to use find_element_by_id() in python
  or read the docs for the same here:
  https://selenium-python.readthedocs.io/api.html#locate-elements-by

In hindsight i see you want to find a button element with the text "AB 12"
the correct code for that would be:

driver.find_element_by_xpath('//button[text()="AB 12"]')

You can check this similar query for more variations:
How to find button with Selenium by its text inside (Python)?


问:
Angular - Run ngAfterViewInit() code only after Inputs() are initialized
I Have some code in ngAfterViewInit() in a component:

```<code>  @Input
  public stringArray: string[];
  public newArray: string[];

  ngAfterViewInit() {
    this.newArray = this.stringArray.filter(x => x.includes('a'));
  }
</code>```

I put the code in ngAfterViewInit() to wait for @Input properties to initialize.

However, it looks like the code in ngAfterViewInit() is 'undefined' when execution gets to it.

How do I get all the @Input properties to initialize before running the filter() operation?

EDIT: The @Input property does have data later. It just happens after ngAfterViewInit(). How do I make sure my code runs only after all @Input() properties are initialized?

答:
Move your code to ng on changes.

```<code>ngOnChanges(changes: SimpleChanges) {
    if(changes && changes.stringArray.currentValue && !this.newArray) {
       this.newArray = this.stringArray.filter(x => x.includes('a'));
    }
  }
</code>```

because your property was changing parent even after initialization of your child component.

Body:
I Have some code in ngAfterViewInit() in a component:

  @Input
  public stringArray: string[];
  public newArray: string[];

  ngAfterViewInit() {
    this.newArray = this.stringArray.filter(x => x.includes('a'));
  }

I put the code in ngAfterViewInit() to wait for @Input properties to initialize.

However, it looks like the code in ngAfterViewInit() is 'undefined' when execution gets to it.

How do I get all the @Input properties to initialize before running the filter() operation?

EDIT: The @Input property does have data later. It just happens after ngAfterViewInit(). How do I make sure my code runs only after all @Input() properties are initialized?

Body:
Move your code to ng on changes.

ngOnChanges(changes: SimpleChanges) {
    if(changes && changes.stringArray.currentValue && !this.newArray) {
       this.newArray = this.stringArray.filter(x => x.includes('a'));
    }
  }

because your property was changing parent even after initialization of your child component.


问:
function name in json response - not working
I am trying to send a function in JSON response and tried to alert that function in js. Below is the code.

JS:

```<code>$('input').keyup(function(){
    $.ajax({
        type: "POST",
        url: "sample.php",
        dataType : 'json',
        data: 'val='+$('input').val(),
        success: function(response){

         var json = transport.responseText.evalJSON();
         alert(json.function()); // => **should alert 'foo bar' - but not**
        }
    });
});
</code>```

PHP:

```<code><?php
// Our sample array
$foo = array(
  'string'  => 'bar',
  'function'=> 'function(){return "foo bar";}'
);
$value_arr = array();
$replace_keys = array();
foreach($foo as $key => &$value){
  // Look for values starting with 'function('
  if(strpos($value, 'function(')===0){
    // Store function string.
    $value_arr[] = $value;
    // Replace function string in $foo with a 'unique' special key.
    $value = '%' . $key . '%';
    // Later on, we'll look for the value, and replace it.
    $replace_keys[] = '"' . $value . '"';
  }
}

// Now encode the array to json format
$json = json_encode($foo);

/* $json looks like:
{
  "number":1,
  "float":1.5,
  "array":[1,2],
  "string":"bar",
  "function":"%function%"
}
*/
// Replace the special keys with the original string.
$json = str_replace($replace_keys, $value_arr, $json);

// Send to to the client
echo $json;

/* This echoes the following string:
{
  "string":"bar",
  "function":function(){return "foo bar";}
}
*/
?>
</code>```

what am I doing wrong in the above? Any help is appreciated.

答:
You are obviously using code from http://solutoire.com/2008/06/12/sending-javascript-functions-over-json/

But they are using prototype and not jQuery ..

The line transport.responseText.evalJSON(); means nothing in jQuery ..

Also have a look at http://json.org/ and you will see that functions is not supposed to go in JSON .. For more explanation read Is it valid to define functions in JSON results?

ContentLicense: CC BY-SA 3.0

Body:
I am trying to send a function in JSON response and tried to alert that function in js. Below is the code.

JS:

$('input').keyup(function(){
    $.ajax({
        type: "POST",
        url: "sample.php",
        dataType : 'json',
        data: 'val='+$('input').val(),
        success: function(response){

         var json = transport.responseText.evalJSON();
         alert(json.function()); // => **should alert 'foo bar' - but not**
        }
    });
});

PHP:

<?php
// Our sample array
$foo = array(
  'string'  => 'bar',
  'function'=> 'function(){return "foo bar";}'
);
$value_arr = array();
$replace_keys = array();
foreach($foo as $key => &$value){
  // Look for values starting with 'function('
  if(strpos($value, 'function(')===0){
    // Store function string.
    $value_arr[] = $value;
    // Replace function string in $foo with a 'unique' special key.
    $value = '%' . $key . '%';
    // Later on, we'll look for the value, and replace it.
    $replace_keys[] = '"' . $value . '"';
  }
}

// Now encode the array to json format
$json = json_encode($foo);

/* $json looks like:
{
  "number":1,
  "float":1.5,
  "array":[1,2],
  "string":"bar",
  "function":"%function%"
}
*/
// Replace the special keys with the original string.
$json = str_replace($replace_keys, $value_arr, $json);

// Send to to the client
echo $json;

/* This echoes the following string:
{
  "string":"bar",
  "function":function(){return "foo bar";}
}
*/
?>

what am I doing wrong in the above? Any help is appreciated.


问:
How to run the mule job based on an event
i want to run my mule flow only when the file arrives at a particular path.How to do that.
since event wait is not there in mulesoft, i thought of running the job every 30 minutes .So that it check the file and run.
But the problem here is, it is not necessary , that the file will be available at every 30 min. when the file is not available , it should not throw any error also.
Note: Job will be running once a month.
Suggestions needed.</p>

答: What you are asking for is exactly On New Or Updated File Connector with schedule based on the cron expression to run every month.


答:
in parent component use

```<code><div *ngIf='stringArray.length >0'>
<child-component [stringArray]='stringArray' ></child-component>
</div>
</code>```

i.e your child component is initializes only if there is data in your input properties

Title: Angular - Run ngAfterViewInit() code only after Inputs() are initialized

Body:
in parent component use

<div *ngIf='stringArray.length >0'>
<child-component [stringArray]='stringArray' ></child-component>
</div>

i.e your child component is initializes only if there is data in your input properties


问:
Kubernetes Jupyter Server with Example Notebook and Persistent Storage
I am trying to run a jupyter lab server Kubernetes deployment with a docker container that is set up to be a Jupiter server and that contains an example notebook (and Jupyter config) in the jupyter working directory. I would like to link this working directory to persistent storage, but when mounting the (Azure fileshare) volume to the container (as specified in the deployement.yaml file), the example notebook gets deleted (due to the empty storage being mounted). Is there any way to mount the container and keep the notebook and config?

The deployment file looks more or less (with some unimportant sections replaced by '...')as follows:

apiVersion: apps/v1beta2
kind: Deployment
metadata:
  name: {{ include "api-chart.fullname" . }}
  labels:
  ...
spec:
  replicas: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: {{ include "api-chart.name" . }}
      app.kubernetes.io/instance: {{ .Release.Name }}
  template:
    metadata:
      labels:
      ...
      volumes:
        - name: personal-volume
          azureFile:
            secretName: {{ .Values.sharedVolumes.personalSecretName }}
            shareName: personal
            readOnly: false
      containers:
        - name: {{ .Chart.Name }}
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          ports:
            - name: http
              containerPort: {{ .Values.service.targetPort }}
              protocol: TCP
          volumeMounts:
            - name: personal-volume
              mountPath: "/workspace"
              subPath: {{ .Values.username }}
          resources:
            ...

答:
You did not provide much information on how you're mounting the storage service.  The first thing I would look is to make sure to use a StorageClass with the reclaim policy set to Retain.

```<code>kind: StorageClass
apiVersion: storage.k8s.io/v1
metadata:
  name: azurefile
provisioner: kubernetes.io/azure-file
mountOptions:
  - dir_mode=0777
  - file_mode=0777
  - uid=0
  - gid=0
  - mfsymlinks
  - cache=strict
parameters:
  skuName: Standard_LRS
reclaimPolicy: Retain
</code>```

Body:
You did not provide much information on how you're mounting the storage service.  The first thing I would look is to make sure to use a StorageClass with the reclaim policy set to Retain.

kind: StorageClass
apiVersion: storage.k8s.io/v1
metadata:
  name: azurefile
provisioner: kubernetes.io/azure-file
mountOptions:
  - dir_mode=0777
  - file_mode=0777
  - uid=0
  - gid=0
  - mfsymlinks
  - cache=strict
parameters:
  skuName: Standard_LRS
reclaimPolicy: Retain


问:
Dynamic templates support default types?

Dynamic templates allow you to define custom mappings that can be applied to dynamically added fields based on:

the datatype detected by Elasticsearch, with match_mapping_type.

the name of the field, with match and unmatch or match_pattern.

the full dotted path to the field, with path_match and path_unmatch.

I was trying to have a default type keyword for all fields while some special fields with specific *Suffix or prefix* could have specified types as follows, but it turned out all fields will be keyword in the end unexpectedly.

```<code>{
  "order": 99,
  "index_patterns": [
    "xxxx_stats_*"
  ],
  "settings": {
    "index": {
      "number_of_shards": "6",
      "number_of_replicas": "1"
    }
  },
  "mappings": {
    "_doc": {
      "dynamic": true,
      "_source": {
        "enabled": true
      },
      "dynamic_templates": [
        {
          "strings": {
            "match_mapping_type": "*",
            "unmatch": [
              "*Time",
              "*At",
              "is*"
            ],
            "mapping": {
              "ignore_above": 256,
              "null_value": "NULL",
              "type": "keyword"
            }
          }
        },
        {
          "timeSuffix": {
            "match_mapping_type": "*",
            "match": [
              "*Time",
              "*At"
            ],
            "mapping": {
              "type": "long"
            }
          }
        },
        {
          "isPrefix": {
            "match_mapping_type": "*",
            "match": "is*",
            "mapping": {
              "type": "boolean"
            }
          }
        }
      ],
      "date_detection": false,
      "numeric_detection": true
    }
  },
  "aliases": {
    "{index}-alias": {

    }
  }
}
</code>```

答:
AFAIK match and unmatch cannot be arrays, only strings or regexes. So try this:

```<code>{
  "dynamic_templates":[
    {
      "timeSuffix":{
        "match_mapping_type":"*",
        "match_pattern":"regex",
        "match":"^(.*Time)|(.*At)$",
        "mapping":{
          "type":"long"
        }
      }
    },
    {
      "isPrefix":{
        "match_mapping_type":"*",
        "match":"is*",
        "mapping":{
          "type":"boolean"
        }
      }
    },
    {
      "strings":{
        "match_mapping_type":"*",
        "mapping":{
          "ignore_above":256,
          "null_value":"NULL",
          "type":"keyword"
        }
      }
    }
  ]
}
</code>```

I also find that when you move strings to the bottom, the 2 mappings above will be resolved first. Otherwise, since every segment includes match_mapping_type":"*", the first matching segment will apply. This issue may be related.

Body:
Dynamic templates allow you to define custom mappings that can be applied to dynamically added fields based on:

the datatype detected by Elasticsearch, with match_mapping_type.

the name of the field, with match and unmatch or match_pattern.

the full dotted path to the field, with path_match and path_unmatch.

I was trying to have a default type keyword for all fields while some special fields with specific *Suffix or prefix* could have specified types as follows, but it turned out all fields will be keyword in the end unexpectedly.

{
  "order": 99,
  "index_patterns": [
    "xxxx_stats_*"
  ],
  "settings": {
    "index": {
      "number_of_shards": "6",
      "number_of_replicas": "1"
    }
  },
  "mappings": {
    "_doc": {
      "dynamic": true,
      "_source": {
        "enabled": true
      },
      "dynamic_templates": [
        {
          "strings": {
            "match_mapping_type": "*",
            "unmatch": [
              "*Time",
              "*At",
              "is*"
            ],
            "mapping": {
              "ignore_above": 256,
              "null_value": "NULL",
              "type": "keyword"
            }
          }
        },
        {
          "timeSuffix": {
            "match_mapping_type": "*",
            "match": [
              "*Time",
              "*At"
            ],
            "mapping": {
              "type": "long"
            }
          }
        },
        {
          "isPrefix": {
            "match_mapping_type": "*",
            "match": "is*",
            "mapping": {
              "type": "boolean"
            }
          }
        }
      ],
      "date_detection": false,
      "numeric_detection": true
    }
  },
  "aliases": {
    "{index}-alias": {

    }
  }
}

Body:
AFAIK match and unmatch cannot be arrays, only strings or regexes. So try this:

{
  "dynamic_templates":[
    {
      "timeSuffix":{
        "match_mapping_type":"*",
        "match_pattern":"regex",
        "match":"^(.*Time)|(.*At)$",
        "mapping":{
          "type":"long"
        }
      }
    },
    {
      "isPrefix":{
        "match_mapping_type":"*",
        "match":"is*",
        "mapping":{
          "type":"boolean"
        }
      }
    },
    {
      "strings":{
        "match_mapping_type":"*",
        "mapping":{
          "ignore_above":256,
          "null_value":"NULL",
          "type":"keyword"
        }
      }
    }
  ]
}

I also find that when you move strings to the bottom, the 2 mappings above will be resolved first. Otherwise, since every segment includes match_mapping_type":"*", the first matching segment will apply. This issue may be related.


问:
How can I enter number digit by digit in field /selenium
So I have verification code that contains 7 fields and I have verification code itself. How can I enter this code by number in every field? I tried to do List, but my skills are not that good. </p>

答:
It is totally dependent on how you application looks and what the DOM structure is. I could help you with the following piece of code that shows how you can automate the verification code field. Execute the below code and see how it works.</p>

```<code>            driver.get("https://codepen.io/DaniRC/pen/PowwwjZ");
            List<String> data = new ArrayList<String>();

            data.add("5");
            data.add("4");
            data.add("3");
            data.add("5");
            int counter = 0;

            driver.switchTo().frame("result");

            List<WebElement> elements = driver.findElement(By.id("form")).findElements(By.xpath("input[@type='text']"));

            for(WebElement element : elements)
            {
                element.sendKeys(data.get(counter));
                counter++;
            }
            Thread.sleep(10000);
            driver.close();
</code>```

Body:
It is totally dependent on how you application looks and what the DOM structure is. I could help you with the following piece of code that shows how you can automate the verification code field. Execute the below code and see how it works.

            driver.get("https://codepen.io/DaniRC/pen/PowwwjZ");
            List<String> data = new ArrayList<String>();

            data.add("5");
            data.add("4");
            data.add("3");
            data.add("5");
            int counter = 0;

            driver.switchTo().frame("result");

            List<WebElement> elements = driver.findElement(By.id("form")).findElements(By.xpath("input[@type='text']"));

            for(WebElement element : elements)
            {
                element.sendKeys(data.get(counter));
                counter++;
            }
            Thread.sleep(10000);
            driver.close();


问:
Spring boot how to edit entity
I am using spring boot with spring data jpa and postgre. I have "item" entity that has price, quantity, auto generated int id and order that it belongs to.
I've searched how to edit that entity changing its price and quantity only,  without making new entity and the only answer I got is to get the entity from the db and set each property to the new one then save it. But if i have 6 other properties except price and quantity that means in the update method i will set a property 8 times and this seems to me like way too much boilerplate code for spring. My question is: Is there better/default way to do that? </p>

答:
Just use this @DynamicUpdate in your Entity class</p>

```<code>@DynamicUpdate
public class Item{
}
</code>```

Title: Spring boot how to edit entity

Body:
Just use this @DynamicUpdate in your Entity class

@DynamicUpdate
public class Item{
}


问:
How to set value dynamically in JHTMLarea
I have been struggling to set the value of JHTML Area. But no luck. Can anyone please help me out. I have read so many articles but i didn't find anything regarding it. I have also searched here and found one problem but have no solution with it.

Any help would be appreciated.

Thanks and regards,

Zeeshan

答:
There's a  proper call to do this. Use this.pasteHTML("Text to enter");
This will programmatically insert text into the editor.

e.g.

```<code>loaded:function(){
        this.pasteHTML("Hello World");
    }
</code>```

Body:
There's a  proper call to do this. Use this.pasteHTML("Text to enter");
This will programmatically insert text into the editor.

e.g.

loaded:function(){
        this.pasteHTML("Hello World");
    }


问:
Scheduling spark job via marathon
I want to schedule spark job to run on daily basis via marathon. I am using mesos as cluster manager.

How to schedule a job to run only once a day via marathon. Right now the job keeps on running again and again once it's finished.

答:
There is no way to schedule periodic job on Marathon. You need to use another framework

Metronome

Chronos

Singularity

Aurora

Title: Scheduling spark job via marathon


问:
CSS grid different number of columns

I want to make a grid with different column sizes ('ITEM = V' covers all width 'ITEM A' or 'P' or 'T' cover each 50 percent of the grid width), as shown in the image. Any help?

i ve been tryin to solve this for a week now. Really what's wrong with this. (video should take two columns)

```<code><div  class="grid-container">
    <div *ngFor="let media of allMedia">
      <div *ngIf="media.type==='V'" class="item1">
        {{media.title}}
      </div>
      <div *ngIf="media.type==='A'" >
         {{media.title}}
      </div>
      <div *ngIf="media.type==='P'" >**Bold Text Here**
        {{media.title}}
      </div>
      <div *ngIf="media.type==='T'">
        {{media.title}}
      </div>
    </div>
  </div>
</code>```

CSS

```<code>   .grid-container {
     display: grid;
     background-color: #2196F3;
     grid-template-columns: 50% 50%;
  }

  .item1 {
     grid-area:  2 / 1 /  span  2 / span 2 !important;
    border-style:solid;
    text-align:center
   }
</code>```

答:
It'd be best to use display: grid; for something like this.

You'd have to add unique classes/id's for the children elements and then set the grid-area property on each of them.

The layout of grid-area is:

```<code>grid-area: row-start / column-start / row-end / column end;
</code>```

You can also use shorthand if two properties have the same value:

```<code>grid-area: 2 / 1
/* Equates to: */
grid-area: 2 / 1 / 2 / 1
</code>```

Example:

.outer-grid {
  display: grid;
  height: 100vh;
}

.newspaper1 {
  grid-area: 1 / 3 / 2 / 1;
  border-style: solid;
}

.newspaper2 {
  grid-area: 2 / 1;
  border-style: solid;
}

.newspaper3 {
  grid-area: 2;
  border-style: solid;
}

.newspaper4 {
  grid-area: 3 / 1;
  border-style: solid;
}

.newspaper5 {
  grid-area: 3 / 2;
  border-style: solid;
}

.newspaper6 {
  grid-area: 4 / 3 / 4 / 1;
  border-style: solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outer-grid">
  <div *ngIf="item==='V'" class="newspaper1">
    some content
  </div>
  <div *ngIf="item==='A'" class="newspaper2">
    some content
  </div>
  <div *ngIf="item==='P'" class="newspaper3">
    some content
  </div>
  <div *ngIf="item==='T'" class="newspaper4">
    some content
  </div>
  <div *ngIf="item==='A'" class="newspaper5">
    some content
  </div>
    <div *ngIf="item==='V'" class="newspaper6">
    some content
  </div>
</div></code>```

Here's a good interface for learning CSS Grid if you want to learn more: https://alialaa.github.io/css-grid-cheat-sheet/

Title: CSS grid different number of columns

Body:
I want to make a grid with different column sizes ('ITEM = V' covers all width 'ITEM A' or 'P' or 'T' cover each 50 percent of the grid width), as shown in the image. Any help?

i ve been tryin to solve this for a week now. Really what's wrong with this. (video should take two columns)

        {{media.title}}

         {{media.title}}

**Bold Text Here**
        {{media.title}}

        {{media.title}}

CSS

   .grid-container {
     display: grid;
     background-color: #2196F3;
     grid-template-columns: 50% 50%;
  }

  .item1 {
     grid-area:  2 / 1 /  span  2 / span 2 !important;
    border-style:solid;
    text-align:center
   }

Body:
It'd be best to use display: grid; for something like this.

You'd have to add unique classes/id's for the children elements and then set the grid-area property on each of them.

The layout of grid-area is:

grid-area: row-start / column-start / row-end / column end;

You can also use shorthand if two properties have the same value:

grid-area: 2 / 1
/* Equates to: */
grid-area: 2 / 1 / 2 / 1

Example:

.outer-grid {
  display: grid;
  height: 100vh;
}

.newspaper1 {
  grid-area: 1 / 3 / 2 / 1;
  border-style: solid;
}

.newspaper2 {
  grid-area: 2 / 1;
  border-style: solid;
}

.newspaper3 {
  grid-area: 2;
  border-style: solid;
}

.newspaper4 {
  grid-area: 3 / 1;
  border-style: solid;
}

.newspaper5 {
  grid-area: 3 / 2;
  border-style: solid;
}

.newspaper6 {
  grid-area: 4 / 3 / 4 / 1;
  border-style: solid;
}

<div class="outer-grid">
  <div *ngIf="item==='V'" class="newspaper1">
    some content
  </div>
  <div *ngIf="item==='A'" class="newspaper2">
    some content
  </div>
  <div *ngIf="item==='P'" class="newspaper3">
    some content
  </div>
  <div *ngIf="item==='T'" class="newspaper4">
    some content
  </div>
  <div *ngIf="item==='A'" class="newspaper5">
    some content
  </div>
    <div *ngIf="item==='V'" class="newspaper6">
    some content
  </div>
</div>

Here's a good interface for learning CSS Grid if you want to learn more: https://alialaa.github.io/css-grid-cheat-sheet/


答:
You could try to use setter and ignore the ngAfterViewInit().

public newArray: string[];

@Input
set stringArray(value: any) {
  this.newArray = value.filter(x => x.includes('a'));
}
```


问:
Is it possible to run 2 threads in the same time continuously in python?
I try to run a thread that is calculating different data and when the server call is made to serve data.

What i do not understand is why the program not pass to call sending and receiving after thread start

```<code>class FuncThread(threading.Thread):
  def __init__(self, image_model):
    self.image_model = image_model
    threading.Thread.__init__(self)

  def run(self):
    image_model = self.image_model
    while True:

def sending_ receiving():
  while true:

image_model = init()
thread1 = FuncThread(image_model)
thread1.setDaemon(True)
thread1.start() # this should not affect the course of executing order
sending_and_reciveing()   - this is contiuously listening client request
</code>```

thread.start is calling run method that is a while true loop that run continuously .

答:
if I correct the typos in your code, it works well on my machine.</p>

```<code>import time
import threading

class FuncThread(threading.Thread):
  def __init__(self, image_model):
    self.image_model = image_model
    threading.Thread.__init__(self)

  def run(self):
    image_model = self.image_model
    while True:
        print('run')
        time.sleep(1)

def sending_and_receiving():
  while True:
      print('sending_and_receiving')
      time.sleep(1)

image_model = 'test'
thread1 = FuncThread(image_model)
thread1.setDaemon(True)
thread1.start()
sending_and_receiving()
</code>```

Body:
I try to run a thread that is calculating different data and when the server call is made to serve data.

What i do not understand is why the program not pass to call sending and receiving after thread start

class FuncThread(threading.Thread):
  def __init__(self, image_model):
    self.image_model = image_model
    threading.Thread.__init__(self)

  def run(self):
    image_model = self.image_model
    while True:

def sending_ receiving():
  while true:

image_model = init()
thread1 = FuncThread(image_model)
thread1.setDaemon(True)
thread1.start() # this should not affect the course of executing order
sending_and_reciveing()   - this is contiuously listening client request

thread.start is calling run method that is a while true loop that run continuously .

Body:
if I correct the typos in your code, it works well on my machine.

import time
import threading

class FuncThread(threading.Thread):
  def __init__(self, image_model):
    self.image_model = image_model
    threading.Thread.__init__(self)

  def run(self):
    image_model = self.image_model
    while True:
        print('run')
        time.sleep(1)

def sending_and_receiving():
  while True:
      print('sending_and_receiving')
      time.sleep(1)

image_model = 'test'
thread1 = FuncThread(image_model)
thread1.setDaemon(True)
thread1.start()
sending_and_receiving()


问:
Dynamo DB leader board within an Alexa Skill
I am attempting to create a leader board using dynamo db for an quiz style Alexa skill. I have set up the table and users are added to the table with their appropriate data e.g.:

```<code>Item: {
    "PlatformId": 2,
    "UserId": 12345,
    "Score": 100,
    "NickName": "scott",
    "Sport": "football",
}
</code>```

In my table the Primary key is their UserId, the sort key is the PlatformId (this is the same for all users). I have a secondary global index which sets the platformId as the primary key, and the score as the sort key.

In this leader board i want users to be ranked, the highest scorer being number 1, my first attempt at this was to scan the table using the secondary index, this nicely returned all the users sorted by score, however with the potential to have thousands of users on this leader board, i discovered that the time to scan a table with 10000+ users exceeds the 8 second response time that Alexa skills have. This causes the skill to error and close.

Before the response time exceeded, i was using the LastEvaluatedKey to perform an extra scan if the first one didn't cover the entire table, but on this second scan is when the response time limit was exceeded. Annoyingly it's just taking too long to scan the table.

```<code>dbHelper.prototype.scanGetUsers = (ad, newParams = null) => {
return new Promise((resolve, reject) => {
    let params = {};
    if (newParams != null) {
        params = newParams
    } else {
        params = {
            TableName: tableName,
            IndexName: 'PlatformId-Score-index',
            FilterExpression: "Score >= :s AND PlatformId = :p",
            ProjectionExpression: `NickName, Sport, Score`,
            // Limit: 10,
            ExpressionAttributeValues: {
                ":p": User.PlatformId,
                ":s": User.Score,
            },
        }
    }

    docClient.scan(params, function (err, data) {
        if (err || !data) {
            console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
            return reject(JSON.stringify(err, null, 2))
        } else {
            console.log("scan users data succeeded:", JSON.stringify(data, null, 2));
            if(data.LastEvaluatedKey) {
                console.log("found a LastEvalutedKey, Continuing scan");
                params.ExclusiveStartKey = data.LastEvaluatedKey;
                data = data.concat(this.scanGetUsers(ad, params));
            }
            resolve(data);
        }
    });
});
</code>```

}

Is there a way to work around these issues that i haven't explored yet? Or a way to create a leader board with dynamo db that can be structured in an easier way?

答:
You can try Sort Key:

When you combine a partition key and sort key, they create a composite key, and that composite key is the primary key for individual items in a table. With a composite key, you gain the ability to use queries with a KeyConditionExpression against the sort key. In a query, you can use KeyConditionExpression to write conditional statements by using comparison operators that evaluate against a key and limit the items returned. In other words, you can use special operators to include, exclude, and match items by their sort key values.

The article contains all information how to setup and use it.

Body:
I am attempting to create a leader board using dynamo db for an quiz style Alexa skill. I have set up the table and users are added to the table with their appropriate data e.g.:

Item: {
    "PlatformId": 2,
    "UserId": 12345,
    "Score": 100,
    "NickName": "scott",
    "Sport": "football",
}

In my table the Primary key is their UserId, the sort key is the PlatformId (this is the same for all users). I have a secondary global index which sets the platformId as the primary key, and the score as the sort key.

In this leader board i want users to be ranked, the highest scorer being number 1, my first attempt at this was to scan the table using the secondary index, this nicely returned all the users sorted by score, however with the potential to have thousands of users on this leader board, i discovered that the time to scan a table with 10000+ users exceeds the 8 second response time that Alexa skills have. This causes the skill to error and close.

Before the response time exceeded, i was using the LastEvaluatedKey to perform an extra scan if the first one didn't cover the entire table, but on this second scan is when the response time limit was exceeded. Annoyingly it's just taking too long to scan the table.

dbHelper.prototype.scanGetUsers = (ad, newParams = null) => {
return new Promise((resolve, reject) => {
    let params = {};
    if (newParams != null) {
        params = newParams
    } else {
        params = {
            TableName: tableName,
            IndexName: 'PlatformId-Score-index',
            FilterExpression: "Score >= :s AND PlatformId = :p",
            ProjectionExpression: `NickName, Sport, Score`,
            // Limit: 10,
            ExpressionAttributeValues: {
                ":p": User.PlatformId,
                ":s": User.Score,
            },
        }
    }

    docClient.scan(params, function (err, data) {
        if (err || !data) {
            console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
            return reject(JSON.stringify(err, null, 2))
        } else {
            console.log("scan users data succeeded:", JSON.stringify(data, null, 2));
            if(data.LastEvaluatedKey) {
                console.log("found a LastEvalutedKey, Continuing scan");
                params.ExclusiveStartKey = data.LastEvaluatedKey;
                data = data.concat(this.scanGetUsers(ad, params));
            }
            resolve(data);
        }
    });
});

}

Is there a way to work around these issues that i haven't explored yet? Or a way to create a leader board with dynamo db that can be structured in an easier way?


问:
Creating multiple query parameters on the endpoint- REST API WordPress
I'm creating a custom endpoint, that's basically this:

register_rest_route( 'wc/v3', '/custom-product-list(?:/(&P<custom_page>\d+))?(?:/(?P<custom_colors>\d+))?', array(
            'method' => 'GET',
            'callback' => 'custom_product_list',
            'args' => [
                'custom_page',
                'custom_colors'
            ],
        ));
```

<p>What am trying to achieve is this: website.com/shop?page=2&colors=red,green,blue
You know, like a normal URL that you can add stuff to it, and also have these things optional.</p>

<p>This however, doesn't work. </p>

<p>I decode it like this:</p>

<pre class="lang-php prettyprint-override"><code>function custom_product_list( $args ) {
        global $product;

        $offset = 0;
        $limit = 9;

        $page = $args['custom_page'];
        $colors = $args['custom_colors'];
</code>```

How should I go about doing this?

答:
try add another parametr for args, like</p>

```<code>'args' => array(
            'custom_page' => array(
                'required'          => true,

            ),
            'custom_colors' => array(
                'required'          => true,
            )
        ),
</code>```

Body:
I'm creating a custom endpoint, that's basically this:

register_rest_route( 'wc/v3', '/custom-product-list(?:/(&P<custom_page>\d+))?(?:/(?P<custom_colors>\d+))?', array(
            'method' => 'GET',
            'callback' => 'custom_product_list',
            'args' => [
                'custom_page',
                'custom_colors'
            ],
        ));

What am trying to achieve is this: website.com/shop?page=2&colors=red,green,blue
You know, like a normal URL that you can add stuff to it, and also have these things optional.

This however, doesn't work.

I decode it like this:

function custom_product_list( $args ) {
        global $product;

        $offset = 0;
        $limit = 9;

        $page = $args['custom_page'];
        $colors = $args['custom_colors'];

How should I go about doing this?

Body:
try add another parametr for args, like

'args' => array(
            'custom_page' => array(
                'required'          => true,

            ),
            'custom_colors' => array(
                'required'          => true,
            )
        ),


问:
Singleton pattern in flutter
I have the following singleton

```<code>class WebSocketSingleton {

   IOWebSocketChannel _channel;

   WebSocketSingleton._privateConstructor();

   static final WebSocketSingleton _instance = WebSocketSingleton._privateConstructor();

   static WebSocketSingleton get instance => _instance;

   IOWebSocketChannel get channel{
   if(_channel == null){
      debugPrint("Creating new channel");
      _channel =  IOWebSocketChannel.connect(
         "wss://42zn68xb57.execute-api.us-east-1.amazonaws.com/Test");
    }

    return _channel;
   }
}
</code>```

Every time I call WebSocketSingleton.instance it created a new instance of IOWebSocketChannel.

Questions:

Shouldn't the WebSocketSingleton return a previously created instance of the IOWebSocketChannel instead of creating a new one every time I call WebSocketSingleton.instance?

答:
I think there is some issue with a connecting method which I guess it's static, I am calling connect by creating object of the class, and it's working as the only a single instance is created. </p>

```<code>void main() {
  WebSocketSingleton.instance.channel;
  WebSocketSingleton.instance.channel;
  WebSocketSingleton.instance.channel;
}

class WebSocketSingleton {

  IOWebSocketChannel _channel;

  WebSocketSingleton._privateConstructor();

  static final WebSocketSingleton _instance = WebSocketSingleton._privateConstructor();

  static WebSocketSingleton get instance => _instance;

  IOWebSocketChannel get channel{
    if(_channel == null){
      debugPrint("Creating new channel");
      _channel =  IOWebSocketChannel().connect(
          "wss://42zn68xb57.execute-api.us-east-1.amazonaws.com/Test");
    }

    return _channel;
  }
}

class IOWebSocketChannel {
  IOWebSocketChannel connect(String url) {
    return this;
  }
}
</code>```

Title: Singleton pattern in flutter

Body:
I have the following singleton

class WebSocketSingleton {

   IOWebSocketChannel _channel;

   WebSocketSingleton._privateConstructor();

   static final WebSocketSingleton _instance = WebSocketSingleton._privateConstructor();

   static WebSocketSingleton get instance => _instance;

   IOWebSocketChannel get channel{
   if(_channel == null){
      debugPrint("Creating new channel");
      _channel =  IOWebSocketChannel.connect(
         "wss://42zn68xb57.execute-api.us-east-1.amazonaws.com/Test");
    }

    return _channel;
   }
}

Every time I call WebSocketSingleton.instance it created a new instance of IOWebSocketChannel.

Questions:

Shouldn't the WebSocketSingleton return a previously created instance of the IOWebSocketChannel instead of creating a new one every time I call WebSocketSingleton.instance?

Body:
I think there is some issue with a connecting method which I guess it's static, I am calling connect by creating object of the class, and it's working as the only a single instance is created.

void main() {
  WebSocketSingleton.instance.channel;
  WebSocketSingleton.instance.channel;
  WebSocketSingleton.instance.channel;
}

class WebSocketSingleton {

  IOWebSocketChannel _channel;

  WebSocketSingleton._privateConstructor();

  static final WebSocketSingleton _instance = WebSocketSingleton._privateConstructor();

  static WebSocketSingleton get instance => _instance;

  IOWebSocketChannel get channel{
    if(_channel == null){
      debugPrint("Creating new channel");
      _channel =  IOWebSocketChannel().connect(
          "wss://42zn68xb57.execute-api.us-east-1.amazonaws.com/Test");
    }

    return _channel;
  }
}

class IOWebSocketChannel {
  IOWebSocketChannel connect(String url) {
    return this;
  }
}


问:
Most Efficient Way Of Clearing Cache Using ASP.NET
I am building an ASP.NET/Umbraco powered website which is very custom data driven via  entity framework, we are having to cache quite a lot of the data queries (For example searches by keyword) as it's a busy site.

But when a user creates a new data entry, I need to clear all the cached queries (Searches etc..) so the new entry is available in the results.

So in my create, delete and update methods I am calling the following method:

```<code>public static void ClearCacheItems()
{
    var enumerator = HttpContext.Current.Cache.GetEnumerator();

    while (enumerator.MoveNext())
    {
        HttpContext.Current.Cache.Remove(enumerator.Key.ToString());
    }
}
</code>```

Is this really bad? I can't see how else I am supposed to clear the cached items?

答:
Clearing the whole ASP.NET cache for just one specific functional domain seems a bit overkill.

You could create an intermediate object, and store all your cached queries in there. This object could be just a wrapper on a dictionary object. All queries should use this object instead of playing with the ASP.NET cache directly.

Then you add this object to the ASP.NET Cache when you need it. When you need to clear the queries, just get to this object and clear the underlying dictionary. Here is a sample implentation:

```<code>    public sealed class IntermediateCache<T>
    {
        private Dictionary<string, T> _dictionary = new Dictionary<string, T>();

        private IntermediateCache()
        {
        }

        public static IntermediateCache<T> Current
        {
            get
            {
                string key = "IntermediateCache|" + typeof(T).FullName;
                IntermediateCache<T> current = HttpContext.Current.Cache[key] as IntermediateCache<T>;
                if (current == null)
                {
                    current = new IntermediateCache<T>();
                    HttpContext.Current.Cache[key] = current;
                }
                return current;
            }
        }

        public T Get(string key, T defaultValue)
        {
            if (key == null)
                throw new ArgumentNullException("key");

            T value;
            if (_dictionary.TryGetValue(key, out value))
                return value;

            return defaultValue;
        }

        public void Set(string key, T value)
        {
            if (key == null)
                throw new ArgumentNullException("key");

            _dictionary[key] = value;
        }

        public void Clear()
        {
            _dictionary.Clear();
        }
    }
</code>```

If my query is represented like this:

```<code>    public class MyQueryObject
    {
       ....
    }
</code>```

Then, I would use the "regional" cache like this:

```<code>// put something in this intermediate cache
IntermediateCache<MyQueryObject>.Current.Set("myKey", myObj);

// clear this cache
IntermediateCache<MyQueryObject>.Current.Clear();
</code>```

Body:
I am building an ASP.NET/Umbraco powered website which is very custom data driven via  entity framework, we are having to cache quite a lot of the data queries (For example searches by keyword) as it's a busy site.

But when a user creates a new data entry, I need to clear all the cached queries (Searches etc..) so the new entry is available in the results.

So in my create, delete and update methods I am calling the following method:

public static void ClearCacheItems()
{
    var enumerator = HttpContext.Current.Cache.GetEnumerator();

    while (enumerator.MoveNext())
    {
        HttpContext.Current.Cache.Remove(enumerator.Key.ToString());
    }
}

Is this really bad? I can't see how else I am supposed to clear the cached items?

Body:
Clearing the whole ASP.NET cache for just one specific functional domain seems a bit overkill.

You could create an intermediate object, and store all your cached queries in there. This object could be just a wrapper on a dictionary object. All queries should use this object instead of playing with the ASP.NET cache directly.

Then you add this object to the ASP.NET Cache when you need it. When you need to clear the queries, just get to this object and clear the underlying dictionary. Here is a sample implentation:

    public sealed class IntermediateCache<T>
    {
        private Dictionary<string, T> _dictionary = new Dictionary<string, T>();

        private IntermediateCache()
        {
        }

        public static IntermediateCache<T> Current
        {
            get
            {
                string key = "IntermediateCache|" + typeof(T).FullName;
                IntermediateCache<T> current = HttpContext.Current.Cache[key] as IntermediateCache<T>;
                if (current == null)
                {
                    current = new IntermediateCache<T>();
                    HttpContext.Current.Cache[key] = current;
                }
                return current;
            }
        }

        public T Get(string key, T defaultValue)
        {
            if (key == null)
                throw new ArgumentNullException("key");

            T value;
            if (_dictionary.TryGetValue(key, out value))
                return value;

            return defaultValue;
        }

        public void Set(string key, T value)
        {
            if (key == null)
                throw new ArgumentNullException("key");

            _dictionary[key] = value;
        }

        public void Clear()
        {
            _dictionary.Clear();
        }
    }

If my query is represented like this:

    public class MyQueryObject
    {
       ....
    }

Then, I would use the "regional" cache like this:

// put something in this intermediate cache
IntermediateCache<MyQueryObject>.Current.Set("myKey", myObj);

// clear this cache
IntermediateCache<MyQueryObject>.Current.Clear();


问:
Instantiate object from an accessor
I have a strange issue with php and instantiating objects:

Background

There's a class structure I've created (some interfaces, some traits etc) where I automatically extend a class with a whole load of functions etc. These are working as expected in almost all scenarios.

I've attempted to close things down to "idiot/public" proof this repo, so I have made sensitive properties/methods private/protected.

This set of functions include object generation and it is done something like as follows:

$object_name = '\SomeClass';

$new_object = new $this->object_name;

// $new_object is successfully instantiated

```

<p>(obviously this is done over a few files, so I'm simplifying as it completely illustrates the issue)</p>

<p>So, in their various classes and for various inheritance/anti-pebkac reasons I want to do the following:</p>

<pre class="lang-php prettyprint-override"><code>
// define accessors
// ...

$this->setObjectName('\SomeClass');

$new_object_direct = new $this->object_name;
$new_object_accessor = new $this->getObjectName();

// $new_object_direct is successfully instantiated
// $new_object_accessor errors!

</code>```

This last line generates an error:

ErrorException: Undefined property: (...)SomeController::$getObjectName

If you do the following:

$this->setObjectName('\SomeClass');

var_dump($this->object_name, $this->getObjectName())

```

<p>.. it outputs:</p>

```
... : string '\SomeClass'
... : string '\SomeClass'

```

Both are exactly the same.

Question

How do you instantiate an object from a string accessor?

答:
After some messing around, I discovered that this needs to be done on separate lines:

// define accessors
// ...

$this->setObjectName('\SomeClass');

$new_object_direct = new $this->object_name;

$name = $this->getObjectName();
$new_object_accessor = new $name;

// $new_object_direct is successfully instantiated
// $new_object_accessor is successfully instantiated

```

I will raise this as a bug in php.

Title: Instantiate object from an accessor

Body:
I have a strange issue with php and instantiating objects:

Background

There's a class structure I've created (some interfaces, some traits etc) where I automatically extend a class with a whole load of functions etc. These are working as expected in almost all scenarios.

I've attempted to close things down to "idiot/public" proof this repo, so I have made sensitive properties/methods private/protected.

This set of functions include object generation and it is done something like as follows:

$object_name = '\SomeClass';

$new_object = new $this->object_name;

// $new_object is successfully instantiated

(obviously this is done over a few files, so I'm simplifying as it completely illustrates the issue)

So, in their various classes and for various inheritance/anti-pebkac reasons I want to do the following:

// define accessors
// ...

$this->setObjectName('\SomeClass');

$new_object_direct = new $this->object_name;
$new_object_accessor = new $this->getObjectName();

// $new_object_direct is successfully instantiated
// $new_object_accessor errors!

This last line generates an error:

ErrorException: Undefined property: (...)SomeController::$getObjectName

If you do the following:

$this->setObjectName('\SomeClass');

var_dump($this->object_name, $this->getObjectName())

.. it outputs:

... : string '\SomeClass'
... : string '\SomeClass'

Both are exactly the same.

Question

How do you instantiate an object from a string accessor?

Body:
After some messing around, I discovered that this needs to be done on separate lines:

// define accessors
// ...

$this->setObjectName('\SomeClass');

$new_object_direct = new $this->object_name;

$name = $this->getObjectName();
$new_object_accessor = new $name;

// $new_object_direct is successfully instantiated
// $new_object_accessor is successfully instantiated

I will raise this as a bug in php.


问:
Xamarin Android Native bindings Java.Lang.NoClassDefFoundError: 'Failed resolution of: [Lkotlin/reflect/KProperty;'
I'm binding Stripe's android library in Xamarin.Android.
I succeeded in creating the binding project and building it finally after a lot of error resolutions.
Now, when I want to use the library I finally built in my project, I get this error without any additional information:

Java.Lang.NoClassDefFoundError: 'Failed resolution of: [Lkotlin/reflect/KProperty;'

I added the .aar library in my android project and set the build property to Androidaarlibrary, and referenced the binding project directly from the .dll created, but nothing worked. I tried everything I could find but nothing worked.

I have added the dependencies found in the kotlin library, as you can see below:

Here is what I added as dependencies in the xamarin binding project:

I really don't know what else to try, can someone help please ?

答:
It seems that you want to use the Stripe payment platform , right ? Fortunately ,it is available in nuget . You could check from the Github Project Site .
 And you could refer the demo from https://github.com/NAXAM/stripe-android-binding/tree/master/Demo .</p>


问:
ActiveAdmin - appending more than one custom link to `actions` in index doesn't work
I'm trying to append custom links in my index view in ActiveAdmin following these examples: http://activeadmin.info/docs/3-index-pages/index-as-table.html. My code is:

```<code>  index do
    actions do |foo|
      link_to 'Link1', '#', class: 'member_link'
      link_to 'Link2', '#', class: 'member_link'
    end
  end
</code>```

Only the last link is appended. How do I append two links?

答:
Something like this works:</p>

```<code>column "Actions" do |affiliate|
  link_to('Approve', '/approve') + " | " + link_to('Deny', '/deny')
end
</code>```

Body:
I'm trying to append custom links in my index view in ActiveAdmin following these examples: http://activeadmin.info/docs/3-index-pages/index-as-table.html. My code is:

  index do
    actions do |foo|
      link_to 'Link1', '#', class: 'member_link'
      link_to 'Link2', '#', class: 'member_link'
    end
  end

Only the last link is appended. How do I append two links?

Body:
Something like this works:

column "Actions" do |affiliate|
  link_to('Approve', '/approve') + " | " + link_to('Deny', '/deny')
end


问:
[nodeJS][python-shell]How to send image using python-shell?(nodejs to python)
I'm working on a project and I need to send image(frame) in realtime.
Server is NodeJs, and I will process this image using OpenCV in python-shell
But I don't know how to send Image through python shell, to python code..
can you tell me how to send image from nodejs to python?

```<code>var PythonShell = require('python-shell');

var options = {
    mode: 'text',
    pythonOptions:['-u'],
    scriptPath:'C:/Users/multi/'
};

PythonShell.PythonShell.run("pycudacode.py",options,function(err){
    if(err) console.log('err msg:', err);
    console.log('finishied');
}
)
</code>```

this is my code.
thank you.

答:
```<code>global.pyshell = require('python-shell');
var fs = require("fs");

var data = fs.readFileSync("testimg.jpg"); // I will get video frame from the client.
var base64 = data.toString("base64");

var options = {
    mode: 'text',
    pythonOptions:['-u'],
    scriptPath:'C:/Users/multi/'
};

shell = new pyshell.PythonShell("sendex.py",options,function(err){
    if(err) console.log('err msg:', err);
    console.log('finishied');
}
)

shell.send(base64);

shell.on("message", rebase64 => {
    var err = null;
    result = Buffer.from(rebase64, "base64");
    console.log(result);
    console.timeEnd("time")
    fs.writeFileSync("result.jpeg",result);
});
shell.end(err=>{
    if(err){
        console.log(err);
    }
});
</code>```

I solved it and it is my code.

Body:
I'm working on a project and I need to send image(frame) in realtime.
Server is NodeJs, and I will process this image using OpenCV in python-shell
But I don't know how to send Image through python shell, to python code..
can you tell me how to send image from nodejs to python?

var PythonShell = require('python-shell');

var options = {
    mode: 'text',
    pythonOptions:['-u'],
    scriptPath:'C:/Users/multi/'
};

PythonShell.PythonShell.run("pycudacode.py",options,function(err){
    if(err) console.log('err msg:', err);
    console.log('finishied');
}
)

this is my code.
thank you.

Body:
global.pyshell = require('python-shell');
var fs = require("fs");

var data = fs.readFileSync("testimg.jpg"); // I will get video frame from the client.
var base64 = data.toString("base64");

var options = {
    mode: 'text',
    pythonOptions:['-u'],
    scriptPath:'C:/Users/multi/'
};

shell = new pyshell.PythonShell("sendex.py",options,function(err){
    if(err) console.log('err msg:', err);
    console.log('finishied');
}
)

shell.send(base64);

shell.on("message", rebase64 => {
    var err = null;
    result = Buffer.from(rebase64, "base64");
    console.log(result);
    console.timeEnd("time")
    fs.writeFileSync("result.jpeg",result);
});
shell.end(err=>{
    if(err){
        console.log(err);
    }
});

I solved it and it is my code.


问:
passenger_min_instances not working with passenger ruby 2.3 docker
I am having the following Nginx config in passenger docker ruby phusion/passenger-ruby23 as below

```<code>server {
    # max body size (request + fileupload)
    client_max_body_size 5M;

    listen 80;
    server_name localhost;

    location ~* ^/assets/ {
      # if $uri, if not exist then '/404.html'
      try_files $uri =404;
      expires 1y;

      # when Last-Modified is present, ETag is discourage
      add_header ETag "";

      add_header Cache-Control public;
      add_header "Access-Control-Allow-Origin" "*";
      add_header "Access-Control-Allow-Methods" "GET";
    }

    # Nginx serve static assets
    root /home/app/avocado/public;

    passenger_min_instances 10;

    passenger_enabled on;
    passenger_user app;

    passenger_app_env staging;

    passenger_ruby /usr/bin/ruby2.3;
}

</code>```

The web server runs just fine except that when I ran the command passenger-status I got the following output:

```<code>> passenger-status

Using /usr/local/rvm/gems/ruby-2.3.8
Version : 6.0.4
Date    : 2020-05-28 10:25:03 +0000
Instance: feaXd0Zv (nginx/1.14.0 Phusion_Passenger/6.0.4)

----------- General information -----------
Max pool size : 6
App groups    : 0
Processes     : 0
Requests in top-level queue : 0

----------- Application groups ------------
</code>```

which means Passenger did not start with the min number of process I specified passenger_min_instances 10; in the above config.

Is there anyone experience with this issue?

答:
Just got it working with the following config</p>

```<code>server {
  ...
  passenger_min_instances 10;
}

passenger_max_pool_size 15;
passenger_pre_start http://localhost:80;
</code>```

Body:
I am having the following Nginx config in passenger docker ruby phusion/passenger-ruby23 as below

server {
    # max body size (request + fileupload)
    client_max_body_size 5M;

    listen 80;
    server_name localhost;

    location ~* ^/assets/ {
      # if $uri, if not exist then '/404.html'
      try_files $uri =404;
      expires 1y;

      # when Last-Modified is present, ETag is discourage
      add_header ETag "";

      add_header Cache-Control public;
      add_header "Access-Control-Allow-Origin" "*";
      add_header "Access-Control-Allow-Methods" "GET";
    }

    # Nginx serve static assets
    root /home/app/avocado/public;

    passenger_min_instances 10;

    passenger_enabled on;
    passenger_user app;

    passenger_app_env staging;

    passenger_ruby /usr/bin/ruby2.3;
}

The web server runs just fine except that when I ran the command passenger-status I got the following output:

> passenger-status

Using /usr/local/rvm/gems/ruby-2.3.8
Version : 6.0.4
Date    : 2020-05-28 10:25:03 +0000
Instance: feaXd0Zv (nginx/1.14.0 Phusion_Passenger/6.0.4)

----------- General information -----------
Max pool size : 6
App groups    : 0
Processes     : 0
Requests in top-level queue : 0

----------- Application groups ------------

which means Passenger did not start with the min number of process I specified passenger_min_instances 10; in the above config.

Is there anyone experience with this issue?

Body:
Just got it working with the following config

server {
  ...
  passenger_min_instances 10;
}

passenger_max_pool_size 15;
passenger_pre_start http://localhost:80;


问:
"Duplicate 'EmbeddedResource' items were included" when using Uno Platform and Xamarin.Forms on WebAssembly
When building I'm getting this error:

```<code>Duplicate 'EmbeddedResource' items were included.
The .NET SDK includes 'EmbeddedResource' items from your project directory by default.
You can either remove these items from your project file, or set the 'EnableDefaultEmbeddedResourceItems' property to 'false' if you want to explicitly include them in your project file. For more information, see https://aka.ms/sdkimplicititems.
The duplicate items were: 'WasmCSS\Fonts.css'
XamNote.Wasm    C:\Program Files\dotnet\sdk\3.1.202\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.Sdk.DefaultItems.targets   306
</code>```

What should be done to fix this error ?

答:
Same thing her , just fallow the instruction her
https://platform.uno/xamarin-forms/

first thing , it generate the Wasm project but could not add it to the sln , so i added it manually
then when i try to build Wasm , got this error

Severity    Code    Description Project File    Line    Suppression State
Error   NETSDK1022  Duplicate 'EmbeddedResource' items were included. The .NET SDK includes 'EmbeddedResource' items from your project directory by default. You can either remove these items from your project file, or set the 'EnableDefaultEmbeddedResourceItems' property to 'false' if you want to explicitly include them in your project file. For more information, see https://aka.ms/sdkimplicititems. The duplicate items were: 'WasmCSS\Fonts.css'    TestingWebAssXamarin.Wasm   C:\Program Files\dotnet\sdk\3.1.300\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.Sdk.DefaultItems.targets   306

visual studio Version 16.6.0
xamarin froms 4.6.0.800

Body:
When building I'm getting this error:

Duplicate 'EmbeddedResource' items were included.
The .NET SDK includes 'EmbeddedResource' items from your project directory by default.
You can either remove these items from your project file, or set the 'EnableDefaultEmbeddedResourceItems' property to 'false' if you want to explicitly include them in your project file. For more information, see https://aka.ms/sdkimplicititems.
The duplicate items were: 'WasmCSS\Fonts.css'
XamNote.Wasm    C:\Program Files\dotnet\sdk\3.1.202\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.Sdk.DefaultItems.targets   306

What should be done to fix this error ?


问:
How to find the size of a C string without using a while loop?
I was recently trying to find the size of an input C string buffer for using it in memcpy to copy the contents of the input buffers to the output buffer without overlapping.
The following is the code snippet.

```<code>char * func(char *buff1, char *buff2, char *outbuff)
{
    int size = 0;
    while(*buff1 != '\0')
     {
       size++;
       buff1++;
     }
   memcpy(outbuff, buff1, sizeof(char)*size);
   memcpy(outbuff + size, buff2, sizeof(char)*size);
   return outbuff;
}
</code>```

However, I found out that this is a very inefficient way of finding size. If you guys know about any other alternatives it would be very helpful to me.

Edit: I am not allowed to pass their sizes as separate parameters.

答:
to copy the contents of the input buffers to the output buffer without overlapping.

As copying is the goal, "I found out that this is a very inefficient way of finding size." is misguided.

The efficiency is  O(n) even if finding the size could be done without a loop as the copy takes O(n).  "very inefficient" belongs to cases when the O() is worse.

Rather than run down the strings twice, once is sufficient as buffers are non-overlapping.

```<code>char * func(const char *buff1, const char *buff2, char *outbuff) {
  char *dest = outbuff;
  while(*buff1) {
    *dest++ = *buff1++;
  }
  while(*buff2) {
    *dest++ = *buff2++;
  }

  // more common to append a \0
  *dest = '\0';

  return outbuff;
}
</code>```

Body:
I was recently trying to find the size of an input C string buffer for using it in memcpy to copy the contents of the input buffers to the output buffer without overlapping.
The following is the code snippet.

char * func(char *buff1, char *buff2, char *outbuff)
{
    int size = 0;
    while(*buff1 != '\0')
     {
       size++;
       buff1++;
     }
   memcpy(outbuff, buff1, sizeof(char)*size);
   memcpy(outbuff + size, buff2, sizeof(char)*size);
   return outbuff;
}

However, I found out that this is a very inefficient way of finding size. If you guys know about any other alternatives it would be very helpful to me.

Edit: I am not allowed to pass their sizes as separate parameters.

Body:
to copy the contents of the input buffers to the output buffer without overlapping.

As copying is the goal, "I found out that this is a very inefficient way of finding size." is misguided.

The efficiency is  O(n) even if finding the size could be done without a loop as the copy takes O(n).  "very inefficient" belongs to cases when the O() is worse.

Rather than run down the strings twice, once is sufficient as buffers are non-overlapping.

char * func(const char *buff1, const char *buff2, char *outbuff) {
  char *dest = outbuff;
  while(*buff1) {
    *dest++ = *buff1++;
  }
  while(*buff2) {
    *dest++ = *buff2++;
  }

  // more common to append a \0
  *dest = '\0';

  return outbuff;
}


问:
How to optimize query which remove duplicates for 2 million items
Good evening,

This is my query which should remove duplicates from table. How can I optimize this for two milion records?

DELETE p1
FROM wp_ads_platform_users p1
INNER JOIN wp_ads_platform_users p2
WHERE p1.id < p2.id
  AND p1.number = p2.number
```

Thanks for help.

答:
In MySQL, you can pre-aggregate:

```<code>DELETE p
    FROM wp_ads_platform_users p JOIN
         (SELECT number, MAX(id) as max_id
          FROM wp_ads_platform_users p2
          GROUP BY number
         ) pp
         ON p.number = pp.number
    WHERE p.id < pp.max_id;
</code>```

That said, deleting 2 million rows will take time.  You might want to recreate the table using a query.

Body:
Good evening,

This is my query which should remove duplicates from table. How can I optimize this for two milion records?

DELETE p1
FROM wp_ads_platform_users p1
INNER JOIN wp_ads_platform_users p2
WHERE p1.id < p2.id
  AND p1.number = p2.number

Thanks for help.

Body:
In MySQL, you can pre-aggregate:

DELETE p
    FROM wp_ads_platform_users p JOIN
         (SELECT number, MAX(id) as max_id
          FROM wp_ads_platform_users p2
          GROUP BY number
         ) pp
         ON p.number = pp.number
    WHERE p.id < pp.max_id;

That said, deleting 2 million rows will take time.  You might want to recreate the table using a query.


问:
Why the semicolon couldn't place in the CommandText of a OracleCommand when C#
Why the semicolon(';') couldn't place in the CommandText of a OracleCommand when C#

Just like below:

```<code>string sql = "select * from table1;";
OracleCommand oc = new OracleCommand(sql , con);
oc.CommandType = CommandType.Text;
oc.ExecuteNonQuery();
</code>```

The result would turn out to be a error.

Why? Can any one tell me the reason?

答:
In the comments, we've worked out the answer for you. Just so you get an official "answer", here it is from the OracleOverflow site (see below):

An OracleCommmand can run only 1 sql or plsql statement at a time. There is no need of separating multiple statements.

The semicolon is part of documentation to divide multiple statements. It is not part of the single DDL statement. For an OracleCommand there is no need to append a semicolon because it can only handle one statement at a time.

Edit: This was the original link, which is now dead: http://www.oracleoverflow.com/questions/145/running-ddl-through-an-oraclecommand-without-the-semicolon

Alternative: http://web.archive.org/web/20100806014022/http://www.oracleoverflow.com/questions/145/running-ddl-through-an-oraclecommand-without-the-semicolon

Question:

When trying to run a series of DDL commands through an OracleCommand
  object, I get an ORA-00911 'invalid character' error if I include the
  final semicolon, even though this is part of the SQL syntax in the
  documentation. It also means that you can only execute SQL one
  statement at a time, rather than executing a whole SQL script at once,
  which seems very odd to me.

After googling for a bit, I found that a workaround is to wrap the DDL
  in an EXECUTE IMMEDIATE PL/SQL statement, but again it fails if the
  DDL has a semicolon at the end (apart from PL/SQL create statements,
  which require the semicolon).

Does anyone know the reason for this behaviour? The semicolon is in
  the syntax documentation, so I would have assumed it is always
  required, but it fails if the semicolon is included...

Answer here:

An OracleCommmand can run only 1 sql or plsql statement at a time.
  There is no need of separating multiple statements.

The semicolon is part of documentation to divide multiple statements.
  It is not part of the single DDL statement. For an OracleCommand there
  is no need to append a semicolon because it can only handle one
  statement at a time.

ADDED: You can bundle more than one statement into an BEGIN ... END;
  Block (yes, this ends with semicolon). But this statements should be
  DML, DDL or PL/SQL function calls. You cannot bundle multiple SELECT
  statements into an BEGIN ... END; Block.

Comments:

Why OracleCommand has this limitation of only being able to run 1 statement at a time?

It's based on DbCommand specification in ADO.Net. It's not a limitation of OracleCommand only.

SqlCommand allows multiple statements in a single command, that must just be an 'addition' for SQL Server.

Body:
Why the semicolon(';') couldn't place in the CommandText of a OracleCommand when C#

Just like below:

string sql = "select * from table1;";
OracleCommand oc = new OracleCommand(sql , con);
oc.CommandType = CommandType.Text;
oc.ExecuteNonQuery();

The result would turn out to be a error.

Why? Can any one tell me the reason?


问:
SGEN: An attempt was made to load an assembly with an incorrect format
I have a project that can build fine on my local machine, however, when I get TFS to build it, I receive the following error -

SGEN: An attempt was made to load an assembly with an incorrect format:

After reading through many other posts here on this topic, most people just say I need to change the build type to either x86 or Any CPU, rather than x64, but after trying countless combinations, this was not the solution. My program is also a windows service, so setting the App Pool to allow 32 bit applications (as suggested by others) is also not the solution.

答:
Per one of the comments in the accepted answer by @james-white the following worked for me:

Chagnge: GenerateSerializationAssemblies property in the project file from 'On' to 'Auto'

Wanted to pull this suggestion into an answer to make it more obvious to anyone just skimming through.  Thank you James White


问:
addEventListener not working in custom element
I'm making a monopoly game for my website, and I have a problem that I can't add event listeners for "i" element in a custom element

Here's my custom element:

class Popup extends HTMLElement {
  constructor() {
    super();
    var that = this;

    var shadow = this.attachShadow({mode: 'open'});
    var wrapper = document.createElement('div');
    wrapper.setAttribute("class","popup-wrapper");
    var popup = document.createElement('div');
    popup.setAttribute('class','popup');

    let exitButton = document.createElement('i');
    exitButton.className = "fas fa-times fa-lg exit";

    exitButton.addEventListener("click", function () {
      console.log('a');
    });

    // styles
    var style = document.createElement('style');
    style.textContent = `
      @import url("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css");
      @import url("https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css");

      .popup-wrapper {
        position: fixed;
        top: 0; left: 0; right: 0; bottom: 0;
        background-color: rgba(0, 0, 0, .6);
        z-index: 9999;
        visibility: visible;
      }

      .popup {
        position: fixed;
        top: 50%; left: 50%;
        transform: translate(-50%, -50%);
        border: 1px solid #d6d6d6;
        background-color: #fff;
        border-radius: .25rem;
        padding: 1rem 2rem;
      }

      /* .exit {
        position: absolute;
        top: .5rem; right: .5rem;
        cursor: pointer;
      } */
    `;

    popup.appendChild(exitButton);

    wrapper.appendChild(popup);

    shadow.appendChild(style);
    shadow.appendChild(wrapper);

    this.isOpen = false;
    this.popup_wrapper = wrapper;
    this.popup = popup;
    this.exitButton = exitButton;
  }

  close() {
    console.log('a');
    this.remove();
  }
}

class TextPopup extends Popup {
  constructor() {
    super();

  }

  show() {
    this.exitButton.addEventListener("click", function () {
      console.log('a');
    });

    this.heading = this.getAttribute("heading");
    this.text = this.getAttribute("text");

    this.popup.innerHTML += `

${this.heading}

${this.text}

    `;
  }
}

customElements.define('text-popup', TextPopup);
```

<p>I had tried to place it in multiple locations but it is still not working</p>

<p>I also have another custom element where addEventListener working:</p>

```class Copy extends HTMLElement {
  constructor() {
    super();

    if (!this.hasAttribute('text')) return console.error("Text is not specified");

    this.text = this.getAttribute('text');
    this.style.cursor = "pointer";
    var that = this;
    this.addEvents(["click", "touchend"], () => {
      that.copy(that.text)
    });
  }

  copy(text) {
    navigator.clipboard.writeText(text).then(function() {
      // successfull
    }, function(err) {
      // unsuccessfull
    });
  }
}

customElements.define('copy-button', Copy);
```

<p>PS: addEvents prototype:</p>

```Element.prototype.addEvents = Document.prototype.addEvents = Window.prototype.addEvents = function (events, callback) {
  for (var i = 0; i < events.length; i++) this.addEventListener(events[i], callback);
};
```

I'm on the last version of chrome

答:
Some pointers:

FontAwesome and Bootstrap CSS inside a shadowDOM also require loading the CSS in the main document

For a single click inside a shadowDOM you don't have to use a Event Listener (tech for adding multiple listeners), setting the onclick Event Handler will do

using a <TEMPLATE> instead of creating HTML with JS is a lot less error prone (and simpler, and less code, and.. )

emit your own CustomEvent with dispatchEvent, saves you from handling path[0] data in a global Event Listener

Note: the CSS loading in this SO snippet causes a 3 second delay after clicks... only on StackOverflow

<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css">

<fa-button icon="fa-bars"></fa-button>

  <fa-button icon="fa-address-card"></fa-button>
  <fa-button icon="fa-camera"></fa-button>
  <fa-button icon="fa-window-close"></fa-button>

<template id="FA-BUTTON">

</template>

```

Body:
I'm making a monopoly game for my website, and I have a problem that I can't add event listeners for "i" element in a custom element

Here's my custom element:

class Popup extends HTMLElement {
  constructor() {
    super();
    var that = this;

    var shadow = this.attachShadow({mode: 'open'});
    var wrapper = document.createElement('div');
    wrapper.setAttribute("class","popup-wrapper");
    var popup = document.createElement('div');
    popup.setAttribute('class','popup');

    let exitButton = document.createElement('i');
    exitButton.className = "fas fa-times fa-lg exit";

    exitButton.addEventListener("click", function () {
      console.log('a');
    });

    // styles
    var style = document.createElement('style');
    style.textContent = `
      @import url("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css");
      @import url("https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css");

      .popup-wrapper {
        position: fixed;
        top: 0; left: 0; right: 0; bottom: 0;
        background-color: rgba(0, 0, 0, .6);
        z-index: 9999;
        visibility: visible;
      }

      .popup {
        position: fixed;
        top: 50%; left: 50%;
        transform: translate(-50%, -50%);
        border: 1px solid #d6d6d6;
        background-color: #fff;
        border-radius: .25rem;
        padding: 1rem 2rem;
      }

      /* .exit {
        position: absolute;
        top: .5rem; right: .5rem;
        cursor: pointer;
      } */
    `;

    popup.appendChild(exitButton);

    wrapper.appendChild(popup);

    shadow.appendChild(style);
    shadow.appendChild(wrapper);

    this.isOpen = false;
    this.popup_wrapper = wrapper;
    this.popup = popup;
    this.exitButton = exitButton;
  }

  close() {
    console.log('a');
    this.remove();
  }
}

class TextPopup extends Popup {
  constructor() {
    super();

  }

  show() {
    this.exitButton.addEventListener("click", function () {
      console.log('a');
    });

    this.heading = this.getAttribute("heading");
    this.text = this.getAttribute("text");

    this.popup.innerHTML += `

${this.heading}

${this.text}

    `;
  }
}

customElements.define('text-popup', TextPopup);

I had tried to place it in multiple locations but it is still not working

I also have another custom element where addEventListener working:

class Copy extends HTMLElement {
  constructor() {
    super();

    if (!this.hasAttribute('text')) return console.error("Text is not specified");

    this.text = this.getAttribute('text');
    this.style.cursor = "pointer";
    var that = this;
    this.addEvents(["click", "touchend"], () => {
      that.copy(that.text)
    });
  }

  copy(text) {
    navigator.clipboard.writeText(text).then(function() {
      // successfull
    }, function(err) {
      // unsuccessfull
    });
  }
}

customElements.define('copy-button', Copy);

PS: addEvents prototype:

Element.prototype.addEvents = Document.prototype.addEvents = Window.prototype.addEvents = function (events, callback) {
  for (var i = 0; i < events.length; i++) this.addEventListener(events[i], callback);
};

I'm on the last version of chrome

Body:
Some pointers:

FontAwesome and Bootstrap CSS inside a shadowDOM also require loading the CSS in the main document

For a single click inside a shadowDOM you don't have to use a Event Listener (tech for adding multiple listeners), setting the onclick Event Handler will do

using a <TEMPLATE> instead of creating HTML with JS is a lot less error prone (and simpler, and less code, and.. )

emit your own CustomEvent with dispatchEvent, saves you from handling path[0] data in a global Event Listener

Note: the CSS loading in this SO snippet causes a 3 second delay after clicks... only on StackOverflow

<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css">

<fa-button icon="fa-bars"></fa-button>
<div id=buttonbar>
  <fa-button icon="fa-address-card"></fa-button>
  <fa-button icon="fa-camera"></fa-button>
  <fa-button icon="fa-window-close"></fa-button>
</div>

<style>
  body {
    font-size: 48px; /* font settings cascade into shadowDOM */
  }
  #buttonbar {
    --buttonbackground: "grey"; /* CSS properties cascade into shadowDOM */
    --buttoncolor: black;
    float: right;
  }
</style>

<template id="FA-BUTTON">
  <style>
    @import url("//cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css");
    :host {
      display: inline-block;
    }
    i {
      background: var(--buttonbackground, yellow);
      color: var(--buttoncolor, red);
    }
  </style>
  <i class="fas"></i>
</template>

<script>
  customElements.define('fa-button', class extends HTMLElement {
    constructor() {
      super() // returns 'this'
        .attachShadow({ mode: 'open' }) // returns AND sets 'this.shadowRoot'
        .append(document.getElementById(this.nodeName).content.cloneNode(true));
    }
    connectedCallback() {
      this.shadowRoot.querySelector("i").classList.add(this.getAttribute("icon"));
      this.onclick = () =>
        this.dispatchEvent(new CustomEvent("buttonclick", {
          detail: {
            clicked: this.getAttribute("icon")
          },
          bubbles: true,
          composed: true //escape shadowDOM
        }));
    }
  });

  document.body.addEventListener("buttonclick", (evt) => {
    console.log(evt.detail, evt.composedPath()); // full path into shadowDOM
  });

</script>


问:
c# Discord BOT : send string with underscore (escape underscore in Visual Studio string)
I want to send string with several underscore "__hello__its_me_" but Discord interpret it as markdown and underline or italic my string.

I know I have to escape the underscore with backslash but in Visual Studio I can't escape underscore (unrecognized escape sequence).

How can I build this string and send it to Discord escaping underscore ?

答: If you are using Discord.Net you can use the Format.Sanitize method to escape all formatting characters. If you are not using this library, then just copy the code and create your own method. </p>


问:
High-performance replacement for multiprocessing.Queue
My distributed application consists of many producers that push tasks into several FIFO queues, and multiple consumers for every one of these queues. All these components live on a single node, so no networking involved.

This pattern is perfectly supported by Python's built-in multiprocessing.Queue, however when I am scaling up my application the queue implementation seems to be a bottleneck. I am not sending large amounts of data, so memory sharing does not solve the problem. What I need is fast guaranteed delivery of 10^4-10^5 small messages per second. Each message is about 100 bytes.

I am new to the world of fast distributed computing and I am very confused by the sheer amount of options. There is RabbitMQ, Redis, Kafka, etc.

ZeroMQ is a more focused and compact alternative, which also has successors such as nanomsg and nng. Also, implementing something like a many-to-many queue with a guaranteed delivery seems nontrivial without a broker.

I would really appreciate if someone could point me to a "standard" way of doing something like this with one of the faster frameworks.

答:
After trying a few available implementations and frameworks, I still could not find anything that would be suitable for my task. Either too slow or too heavy.

To solve the issue my colleagues and I developed this: https://github.com/alex-petrenko/faster-fifo

faster-fifo is a drop-in replacement for Python's multiprocessing.Queue and is significantly faster. In fact, it is up to 30x faster in the configurations I cared about (many producers, few consumers) because it additionally supports get_many() method on the consumer side.

It is brokereless, lightweight, supports arbitrary many-to-many configurations, implemented for Posix systems using pthread synchronization primitives.


问:
how to save image,audio,video files to database as link?
i m not getting how to store a file to database so that at time application is uploaded to webserver user can download that file.
till now i was just saving the file name to database and it is wrong.so do i need to save the link to database?
i m getting confused?any suggession?
till now i m using this code to store file in database,</p>

```<code>protected void dbInsert(string fileType,string fileName,string fileExt)
{
     String getSQL1 = "INSERT into tbluploadedfilesdetail (FileDownloaded,FileType,FileName,FileExt) VALUES ("+0+",'"+fileType+"','"+fileName+"','"+fileExt+"');";

     MySqlConnection objMyCon1 = new MySqlConnection(strProvider);
     objMyCon1.Open();

     MySqlCommand cmd1 = new MySqlCommand(getSQL1, objMyCon1);
     cmd1.ExecuteNonQuery();
     objMyCon1.Close();
     dbLoad();
}
</code>```

答: Why don't you read bytes from files and write it to database you have to take Image as data type in data base.</p>

Body:
i m not getting how to store a file to database so that at time application is uploaded to webserver user can download that file.
till now i was just saving the file name to database and it is wrong.so do i need to save the link to database?
i m getting confused?any suggession?
till now i m using this code to store file in database,

protected void dbInsert(string fileType,string fileName,string fileExt)
{
     String getSQL1 = "INSERT into tbluploadedfilesdetail (FileDownloaded,FileType,FileName,FileExt) VALUES ("+0+",'"+fileType+"','"+fileName+"','"+fileExt+"');";

     MySqlConnection objMyCon1 = new MySqlConnection(strProvider);
     objMyCon1.Open();

     MySqlCommand cmd1 = new MySqlCommand(getSQL1, objMyCon1);
     cmd1.ExecuteNonQuery();
     objMyCon1.Close();
     dbLoad();
}


问:
gpg: can't connect to the agent: IPC connect call failed
I am having a problem while trying to decrypt some keys using GPG. The following output is given to me:

```<code>gpg: can't connect to the agent: IPC connect call failed
</code>```

I already edited some files, pointed in this tutorial: https://michaelheap.com/gpg-cant-connect-to-the-agent-ipc-connect-call-failed/ but with no success.

Possible reasons for that?

答:
I had to use:</p>
```<code>sudo apt autoremove gpg gnupg1 gnupg2
</code>```

Body:
I am having a problem while trying to decrypt some keys using GPG. The following output is given to me:

gpg: can't connect to the agent: IPC connect call failed

I already edited some files, pointed in this tutorial: https://michaelheap.com/gpg-cant-connect-to-the-agent-ipc-connect-call-failed/ but with no success.

Possible reasons for that?

Body:
I had to use:

sudo apt autoremove gpg gnupg1 gnupg2


问:
how do you download 2D-extras in unity
I am making a game in Unity 2019.1 and I do not know how to download 2D extras into unity. let alone I do not understand how to do it.</p>

答:
Unity techdemos 2d extras is a repository by unity  having some scripts to add additional functionality on a 2d basis. To download 2d extras go to the link https://github.com/Unity-Technologies/2d-extras and download the repo. After extracting it in your project, you can easily add scripts available there on the game objects and simply avail various tilemap brushes.

@Bonnie49er1

Title: how do you download 2D-extras in unity