问:
How to add plus one position to setSelectionRange
I am trying to move cursor one more position to the right in input.

```<code>var start = this.selectionStart,
    end = this.selectionEnd;

this.setSelectionRange(start, end);
</code>```

This works for keeping position in the same place after input value changed, but iam trying to add one more position to it, because my format code add "-" character after 4 chars.

    $("input[name=login-access-token]").keypress(function(event){
        var start = this.selectionStart,
        end = this.selectionEnd;
        console.log(start);
        var input = $(this).val();
        input = input.replace(/[\W\s\._\-]+/g, '');
        var split = 4;
        var chunk = [];

        for (var i = 0, len = input.length; i < len; i += split) {
            split = 4;
            chunk.push( input.substr( i, split ) );
        }

        var test = [];
        chunk.forEach(element => {
            test.push(element.match(/.{1,4}/g));
        });

        test.forEach(element => {
            if(element.length!=4){
                $(this).val(function() {
                    var out = chunk.join("-").toUpperCase();

                    if(out.length == 4 && event.keyCode != 8){
                            out += "-";
                    }

                    if(out.length == 9 && event.keyCode != 8 ){
                            out += "-";
                    }

                    return out;
                });
            }
        });

        this.setSelectionRange(start, end);
        var selection = window.getSelection();
        selection.addRange(1);

    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<input type="text" name="login-access-token" placeholder="Code" /></code>```

```<code>    var selection = window.getSelection();
    selection.addRange(1); //not working :/
</code>```

答:
I solved it! Just add +1 to start and end which is values what we get from selectionStart.</p>
```<code> if(out.length == 4 && event.keyCode != 8){
                        out += "-";
                        start = start+1;
                        end = end +1;
                }

                if(out.length == 9 && event.keyCode != 8 ){
                        out += "-";
                        start = start+1;
                        end = end +1;
                }
</code>```

Body:
I am trying to move cursor one more position to the right in input.

var start = this.selectionStart,
    end = this.selectionEnd;

this.setSelectionRange(start, end);

This works for keeping position in the same place after input value changed, but iam trying to add one more position to it, because my format code add "-" character after 4 chars.

    $("input[name=login-access-token]").keypress(function(event){
        var start = this.selectionStart,
        end = this.selectionEnd;
        console.log(start);
        var input = $(this).val();
        input = input.replace(/[\W\s\._\-]+/g, '');
        var split = 4;
        var chunk = [];

        for (var i = 0, len = input.length; i < len; i += split) {
            split = 4;
            chunk.push( input.substr( i, split ) );
        }

        var test = [];
        chunk.forEach(element => {
            test.push(element.match(/.{1,4}/g));
        });

        test.forEach(element => {
            if(element.length!=4){
                $(this).val(function() {
                    var out = chunk.join("-").toUpperCase();

                    if(out.length == 4 && event.keyCode != 8){
                            out += "-";
                    }

                    if(out.length == 9 && event.keyCode != 8 ){
                            out += "-";
                    }

                    return out;
                });
            }
        });

        this.setSelectionRange(start, end);
        var selection = window.getSelection();
        selection.addRange(1);

    });

<input type="text" name="login-access-token" placeholder="Code" />

    var selection = window.getSelection();
    selection.addRange(1); //not working :/

Body:
I solved it! Just add +1 to start and end which is values what we get from selectionStart.

 if(out.length == 4 && event.keyCode != 8){
                        out += "-";
                        start = start+1;
                        end = end +1;
                }

                if(out.length == 9 && event.keyCode != 8 ){
                        out += "-";
                        start = start+1;
                        end = end +1;
                }


来源: stackexchange

问:
pydantic nested model response
I want to pass nested models into the response. I am trying by making object of 1 model then storing the related values to it, making object of 2nd model and storing related values to it and at the last trying to store thoes 2 model in the response model. Can you guys please help me out. Thank you

Models

```<code>class SetImageSetInput(BaseModel):
  profileId: str

  class Config:
    orm_mode = True

class ValidateFaceAlignmentInput(BaseModel):
  currentFrame: str

  class Config:
    orm_mode = True

class outputResponse(BaseModel):
    response1: ValidateFaceAlignmentInput
    response2: SetImageSetInput

SetImageSetInput.profileId="pic1"
ValidateFaceAlignmentInput.currentFrame="1"
outputResponse.response1 = SetImageSetInput
outputResponse.response2 = ValidateFaceAlignmentInput

return SetImageSetInput
</code>```

But I am getting error while executing this api

```<code>pydantic.error_wrappers.ValidationError: 1 validation error for outputResponse
response -> response1
  field required (type=value_error.missing)
</code>```

答:
You just have to create instances of the corresponding classes and pass those to your reponse model object in the constructor. In code, it should read like

response = outputResponse(
    response1= ValidateFaceAlignmentInput(currentFrame ='1'),
    response2=SetImageSetInput(profileId ='pic1'),
)
return response
```

ContentLicense: CC BY-SA 4.0

Title: pydantic nested model response

Body:
I want to pass nested models into the response. I am trying by making object of 1 model then storing the related values to it, making object of 2nd model and storing related values to it and at the last trying to store thoes 2 model in the response model. Can you guys please help me out. Thank you

Models

class SetImageSetInput(BaseModel):
  profileId: str

  class Config:
    orm_mode = True

class ValidateFaceAlignmentInput(BaseModel):
  currentFrame: str

  class Config:
    orm_mode = True

class outputResponse(BaseModel):
    response1: ValidateFaceAlignmentInput
    response2: SetImageSetInput

SetImageSetInput.profileId="pic1"
ValidateFaceAlignmentInput.currentFrame="1"
outputResponse.response1 = SetImageSetInput
outputResponse.response2 = ValidateFaceAlignmentInput

return SetImageSetInput

But I am getting error while executing this api

pydantic.error_wrappers.ValidationError: 1 validation error for outputResponse
response -> response1
  field required (type=value_error.missing)


问:
Can you convert String version of R.id to int?
As an exercise, I am building a calendar. Below is a small segment of my code. I have a class MyCalendar that extends Activity.
This Activity will be linked to an XML file whose layout includes seven TextViews with ids R.id.day0 thru R.id.day6.

If converted from String to int, will the Activity's findViewById() method recognize the int version of these ids?

```<code>        String Days [] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
        TextView dayViews [];

        private void populateViews (){

            for (int counter = 0; counter < Days.length; counter++){
                int ID = Integer.parseInt("R.id.day"+counter);
                dayViews [counter] = (TextView) findViewById(ID);
                dayViews[counter].setText(Days[counter]);
            }
</code>```

答:
I know that's an old question, but it might help more people. What you can do is to call getIdentifier(), like our friends said. For that, you'll need to call it inside a loop, inserting after what value you want for a this variable, to make the string that you want for your resource ID. For exemple:

Your resources file:

```<code>R.string.string0
R.string.string1
R.string.string2
...
R.string.string9
</code>```

In java:

```<code>for (i=0;i<10;i++){
    int resourceId = getResources().getIdentifier("string"+i, "string", this.getPackageName())
    println(getResources().getString(resourceId));
}
</code>```

Then, in your rescourceId variable, you'll have an equivalent to: R.string.string0 to R.string.string9. And, in println, you'll have the value correspondent of your resources string.

In Kotlin:

```<code>for (i in 0..10){
    val resourceId = this.resources.getIdentifier("string"+i, "string", this.packageName)
    println(resources.getString(resourceId))
}
</code>```

With the same explanation that I said before.

ContentLicense: CC BY-SA 3.0

Body:
As an exercise, I am building a calendar. Below is a small segment of my code. I have a class MyCalendar that extends Activity.
This Activity will be linked to an XML file whose layout includes seven TextViews with ids R.id.day0 thru R.id.day6.

If converted from String to int, will the Activity's findViewById() method recognize the int version of these ids?

        String Days [] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
        TextView dayViews [];

        private void populateViews (){

            for (int counter = 0; counter < Days.length; counter++){
                int ID = Integer.parseInt("R.id.day"+counter);
                dayViews [counter] = (TextView) findViewById(ID);
                dayViews[counter].setText(Days[counter]);
            }

Body:
I know that's an old question, but it might help more people. What you can do is to call getIdentifier(), like our friends said. For that, you'll need to call it inside a loop, inserting after what value you want for a this variable, to make the string that you want for your resource ID. For exemple:

Your resources file:

R.string.string0
R.string.string1
R.string.string2
...
R.string.string9

In java:

for (i=0;i<10;i++){
    int resourceId = getResources().getIdentifier("string"+i, "string", this.getPackageName())
    println(getResources().getString(resourceId));
}

Then, in your rescourceId variable, you'll have an equivalent to: R.string.string0 to R.string.string9. And, in println, you'll have the value correspondent of your resources string.

In Kotlin:

for (i in 0..10){
    val resourceId = this.resources.getIdentifier("string"+i, "string", this.packageName)
    println(resources.getString(resourceId))
}

With the same explanation that I said before.


问:
How to filter an associative arrays using array of keys in PHP?
I have an associative arrays and an array of keys.

```<code>$A = array('a'=>'book', 'b'=>'pencil', 'c'=>'pen');
$B = array('a', 'b');
</code>```

How I build an associative array from all element of $A where the key is in $B?
For the example above, the answer should be

```<code>$C = array('a'=>'book', 'b'=>'pencil');
</code>```

答:
```<code>$keys = array_keys($B);
$C = array();
foreach ($A as $key => $value)
{
  if (in_array($key, $keys))
  {
    $C[$key] = $value;
  }
}
</code>```

Body:
I have an associative arrays and an array of keys.

$A = array('a'=>'book', 'b'=>'pencil', 'c'=>'pen');
$B = array('a', 'b');

How I build an associative array from all element of $A where the key is in $B?
For the example above, the answer should be

$C = array('a'=>'book', 'b'=>'pencil');


问:
How to pass schema to create a new Dataframe from existing Dataframe?
To pass schema to a json file we do this:

```<code>from pyspark.sql.types import (StructField, StringType, StructType, IntegerType)
data_schema = [StructField('age', IntegerType(), True), StructField('name', StringType(), True)]
final_struc = StructType(fields = data_schema)
df =spark.read.json('people.json', schema=final_struc)
</code>```

The above code works as expected. However now, I have data in table which I display by:

```<code>df = sqlContext.sql("SELECT * FROM people_json")
</code>```

But if I try to pass a new schema to it by using following command it does not work.

```<code>df2 = spark.sql("SELECT * FROM people_json", schema=final_struc)
</code>```

It gives the following error:

sql() got an unexpected keyword argument 'schema'

NOTE: I am using Databrics Community Edition

What am I missing?

How do I pass the new schema if I have data in the table instead of some JSON file?

答:
There is already one answer available but still I want to add something.

Create DF from RDD

using toDF

newDf = rdd.toDF(schema, column_name_list)

using createDataFrame

newDF = spark.createDataFrame(rdd ,schema, [list_of_column_name])

Create DF from other DF

suppose I have DataFrame with columns|data type - name|string, marks|string, gender|string.

if I want to get only marks as integer.

```<code>newDF = oldDF.select("marks")
newDF_with_int = newDF.withColumn("marks", df['marks'].cast('Integer'))
</code>```

This will convert marks to integer.

Body:
To pass schema to a json file we do this:

from pyspark.sql.types import (StructField, StringType, StructType, IntegerType)
data_schema = [StructField('age', IntegerType(), True), StructField('name', StringType(), True)]
final_struc = StructType(fields = data_schema)
df =spark.read.json('people.json', schema=final_struc)

The above code works as expected. However now, I have data in table which I display by:

df = sqlContext.sql("SELECT * FROM people_json")

But if I try to pass a new schema to it by using following command it does not work.

df2 = spark.sql("SELECT * FROM people_json", schema=final_struc)

It gives the following error:

sql() got an unexpected keyword argument 'schema'

NOTE: I am using Databrics Community Edition

What am I missing?

How do I pass the new schema if I have data in the table instead of some JSON file?

Body:
There is already one answer available but still I want to add something.

Create DF from RDD

using toDF

newDf = rdd.toDF(schema, column_name_list)

using createDataFrame

newDF = spark.createDataFrame(rdd ,schema, [list_of_column_name])

Create DF from other DF

suppose I have DataFrame with columns|data type - name|string, marks|string, gender|string.

if I want to get only marks as integer.

newDF = oldDF.select("marks")
newDF_with_int = newDF.withColumn("marks", df['marks'].cast('Integer'))

This will convert marks to integer.


问:
How do I select groups of customer references that don't use a particular service?
Using the following table (customer_table):

customer_ref
product
service

PI-003
cube
streaming

PI-722
cube
streaming

PI-723
cube
streaming

PI-724
cube
streaming

PI-724
pyramid
download

PI-725
cube
streaming

PI-727
cube
streaming

PI-728
cube
streaming

PI-729
cube
streaming

PI-729
pyramid
download

PI-730
cube
streaming

PI-730
sphere
radio

How do I select groups of customer references that don't use a download as a service?

If I do:
SELECT customer_ref FROM customer_table WHERE service <> download

It will return customer_ref PI-724 and PI-729 which do have a service that isn't download but I don't want to return them because under the same customer_ref they do have a service that is download - if that makes sense.

Under my parameters I want to return the following customer_ref:

customer_ref

PI-003

PI-722

PI-723

PI-725

PI-727

PI-728

PI-730

答:
You can aggregate and using bool_and() in the having clause:

```<code>select customer_ref
from the_table
group by customer_ref
having bool_and(service <> 'download');
</code>```

bool_and(service <> 'download') will only return true if all services of the customer_ref are not equal to download

Body:
You can aggregate and using bool_and() in the having clause:

select customer_ref
from the_table
group by customer_ref
having bool_and(service <> 'download');

bool_and(service <> 'download') will only return true if all services of the customer_ref are not equal to download


问:
The same stored procedure in schema doesn't work package
I have following stored procedure inside the package:

CREATE OR REPLACE PROCEDURE P_TRUNC_I_SUB_PARTITION (
      P_TABLE_NAME   IN VARCHAR2,
      P_STICHTAG     IN NUMBER,
      P_SUB_ID       IN VARCHAR2 DEFAULT '*')
   IS
      SQL_TRUNCATE                   VARCHAR2 (4000);
      VVPRUEF                        VARCHAR2 (4000);
      SQL_ADD_SUBPARTITION           VARCHAR2 (4000);
      PROOF_IF_DATA                  VARCHAR2 (4000);
      PARTITION_DOES_EXIST           EXCEPTION;
      PRAGMA EXCEPTION_INIT (PARTITION_DOES_EXIST, -14622);

      PARTITION_DOES_NOT_EXIST_SUB   EXCEPTION;
      PRAGMA EXCEPTION_INIT (PARTITION_DOES_NOT_EXIST_SUB, -14702);
      PARTITION_DOES_NOT_EXIST2      EXCEPTION;
      PRAGMA EXCEPTION_INIT (PARTITION_DOES_NOT_EXIST2, -02149);
   BEGIN
      -- Wenn keine bestimmte Subpartition angegeben ist, dann truncate auf Partition Ebene
      IF P_SUB_ID = '' OR P_SUB_ID = '*'
      THEN
         SQL_TRUNCATE :=
               'ALTER TABLE '
            || P_TABLE_NAME
            || ' TRUNCATE PARTITION FOR ('
            || P_STICHTAG
            || ') UPDATE INDEXES';
      ELSE
         SQL_TRUNCATE :=
               'ALTER TABLE '
            || P_TABLE_NAME
            || ' TRUNCATE SUBPARTITION FOR ('
            || P_STICHTAG
            || ','
            || ''''
            || P_SUB_ID
            || ''''
            || ') UPDATE INDEXES';
      END IF;

      EXECUTE IMMEDIATE (SQL_TRUNCATE);
   EXCEPTION
      -- Wenn diese bestimmte Subpartition bereits vorhanden ist, dann leere sie
      WHEN PARTITION_DOES_NOT_EXIST2
      THEN
         DBMS_OUTPUT.PUT_LINE (SQLERRM);
         NULL;
      WHEN PARTITION_DOES_NOT_EXIST_SUB
      THEN
         DBMS_OUTPUT.PUT_LINE (SQLERRM);
         NULL;
      WHEN OTHERS
      THEN
         RAISE_APPLICATION_ERROR (
            -20002,
            'P_TRUNC_I_SUB_PARTITION(): ' || SUBSTR (SQLERRM, 1, 500));
   END P_TRUNC_I_SUB_PARTITION;

```
<p>Inside a schema it works:</p>
<pre class="lang-sql prettyprint-override"><code>CALL BAISMART.P_TRUNC_I_SUB_PARTITION('TABLE_NAME', 20220126, 'PURTITION_NAME')
</code>```

but when I call it from the package:

CALL BAISMART.PCK_BAIS_UTIL.P_TRUNC_I_SUB_PARTITION('TABLE_NAME', 20220126, 'PURTITION_NAME')
```
<p>I get an error:</p>
<blockquote>
<p>SQL Error [6553] [65000]: ORA-06553: PLS-306: wrong number or types of arguments in call to 'P_TRUNC_I_SUB_PARTITION'.</p>
</blockquote>
<p>Code of the package itself:</p>
<pre class="lang-sql prettyprint-override"><code>
-- DROP PACKAGE BAISMART.PCK_BAIS_UTIL;

CREATE OR REPLACE PACKAGE BAISMART.PCK_BAIS_UTIL
AS
   PROCEDURE P_TRUNC_I_SUB_PARTITION;
END PCK_BAIS_UTIL;

CREATE OR REPLACE PACKAGE BODY BAISMART.PCK_BAIS_UTIL
AS
     ------------------------
  PROCEDURE P_TRUNC_I_SUB_PARTITION (
      P_TABLE_NAME   IN VARCHAR2,
      P_STICHTAG     IN NUMBER,
      P_SUB_ID       IN VARCHAR2 DEFAULT '*')
   IS
      SQL_TRUNCATE                   VARCHAR2 (4000);
      VVPRUEF                        VARCHAR2 (4000);
      SQL_ADD_SUBPARTITION           VARCHAR2 (4000);
      PROOF_IF_DATA                  VARCHAR2 (4000);
      PARTITION_DOES_EXIST           EXCEPTION;
      PRAGMA EXCEPTION_INIT (PARTITION_DOES_EXIST, -14622);

      PARTITION_DOES_NOT_EXIST_SUB   EXCEPTION;
      PRAGMA EXCEPTION_INIT (PARTITION_DOES_NOT_EXIST_SUB, -14702);
      PARTITION_DOES_NOT_EXIST2      EXCEPTION;
      PRAGMA EXCEPTION_INIT (PARTITION_DOES_NOT_EXIST2, -02149);
   BEGIN
      -- Wenn keine bestimmte Subpartition angegeben ist, dann truncate auf Partition Ebene
      IF P_SUB_ID = '' OR P_SUB_ID = '*'
      THEN
         SQL_TRUNCATE :=
               'ALTER TABLE '
            || P_TABLE_NAME
            || ' TRUNCATE PARTITION FOR ('
            || P_STICHTAG
            || ') UPDATE INDEXES';
      ELSE
         SQL_TRUNCATE :=
               'ALTER TABLE '
            || P_TABLE_NAME
            || ' TRUNCATE SUBPARTITION FOR ('
            || P_STICHTAG
           || ','
            || ''''
            || P_SUB_ID
            || ''''
            || ') UPDATE INDEXES';
      END IF;

      EXECUTE IMMEDIATE (SQL_TRUNCATE);
   EXCEPTION
      -- Wenn diese bestimmte Subpartition bereits vorhanden ist, dann leere sie
      WHEN PARTITION_DOES_NOT_EXIST2
      THEN
         DBMS_OUTPUT.PUT_LINE (SQLERRM);
         NULL;
      WHEN PARTITION_DOES_NOT_EXIST_SUB
      THEN
         DBMS_OUTPUT.PUT_LINE (SQLERRM);
         NULL;
      WHEN OTHERS
      THEN
         RAISE_APPLICATION_ERROR (
            -20002,
            'P_TRUNC_I_SUB_PARTITION(): ' || SUBSTR (SQLERRM, 1, 500));
   END P_TRUNC_I_SUB_PARTITION;

END PCK_BAIS_UTIL;
</code>```

Has anybody any idea why it can happen?

答:
Your package specification and body don't match; so you will get a compilation error from the body, and your call will get PLS-00306.

Your specification says:

```<code>   PROCEDURE P_TRUNC_I_SUB_PARTITION;
</code>```

so the procedure takes no arguments. That should match the body:

```<code>   PROCEDURE P_TRUNC_I_SUB_PARTITION (
      P_TABLE_NAME   IN VARCHAR2,
      P_STICHTAG     IN NUMBER,
      P_SUB_ID       IN VARCHAR2 DEFAULT '*'
   );
</code>```

db<>fiddle with the modified specification.

Body:
I have following stored procedure inside the package:

CREATE OR REPLACE PROCEDURE P_TRUNC_I_SUB_PARTITION (
      P_TABLE_NAME   IN VARCHAR2,
      P_STICHTAG     IN NUMBER,
      P_SUB_ID       IN VARCHAR2 DEFAULT '*')
   IS
      SQL_TRUNCATE                   VARCHAR2 (4000);
      VVPRUEF                        VARCHAR2 (4000);
      SQL_ADD_SUBPARTITION           VARCHAR2 (4000);
      PROOF_IF_DATA                  VARCHAR2 (4000);
      PARTITION_DOES_EXIST           EXCEPTION;
      PRAGMA EXCEPTION_INIT (PARTITION_DOES_EXIST, -14622);

      PARTITION_DOES_NOT_EXIST_SUB   EXCEPTION;
      PRAGMA EXCEPTION_INIT (PARTITION_DOES_NOT_EXIST_SUB, -14702);
      PARTITION_DOES_NOT_EXIST2      EXCEPTION;
      PRAGMA EXCEPTION_INIT (PARTITION_DOES_NOT_EXIST2, -02149);
   BEGIN
      -- Wenn keine bestimmte Subpartition angegeben ist, dann truncate auf Partition Ebene
      IF P_SUB_ID = '' OR P_SUB_ID = '*'
      THEN
         SQL_TRUNCATE :=
               'ALTER TABLE '
            || P_TABLE_NAME
            || ' TRUNCATE PARTITION FOR ('
            || P_STICHTAG
            || ') UPDATE INDEXES';
      ELSE
         SQL_TRUNCATE :=
               'ALTER TABLE '
            || P_TABLE_NAME
            || ' TRUNCATE SUBPARTITION FOR ('
            || P_STICHTAG
            || ','
            || ''''
            || P_SUB_ID
            || ''''
            || ') UPDATE INDEXES';
      END IF;

      EXECUTE IMMEDIATE (SQL_TRUNCATE);
   EXCEPTION
      -- Wenn diese bestimmte Subpartition bereits vorhanden ist, dann leere sie
      WHEN PARTITION_DOES_NOT_EXIST2
      THEN
         DBMS_OUTPUT.PUT_LINE (SQLERRM);
         NULL;
      WHEN PARTITION_DOES_NOT_EXIST_SUB
      THEN
         DBMS_OUTPUT.PUT_LINE (SQLERRM);
         NULL;
      WHEN OTHERS
      THEN
         RAISE_APPLICATION_ERROR (
            -20002,
            'P_TRUNC_I_SUB_PARTITION(): ' || SUBSTR (SQLERRM, 1, 500));
   END P_TRUNC_I_SUB_PARTITION;

Inside a schema it works:

CALL BAISMART.P_TRUNC_I_SUB_PARTITION('TABLE_NAME', 20220126, 'PURTITION_NAME')

but when I call it from the package:

CALL BAISMART.PCK_BAIS_UTIL.P_TRUNC_I_SUB_PARTITION('TABLE_NAME', 20220126, 'PURTITION_NAME')

I get an error:

SQL Error [6553] [65000]: ORA-06553: PLS-306: wrong number or types of arguments in call to 'P_TRUNC_I_SUB_PARTITION'.

Code of the package itself:

-- DROP PACKAGE BAISMART.PCK_BAIS_UTIL;

CREATE OR REPLACE PACKAGE BAISMART.PCK_BAIS_UTIL
AS
   PROCEDURE P_TRUNC_I_SUB_PARTITION;
END PCK_BAIS_UTIL;

CREATE OR REPLACE PACKAGE BODY BAISMART.PCK_BAIS_UTIL
AS
     ------------------------
  PROCEDURE P_TRUNC_I_SUB_PARTITION (
      P_TABLE_NAME   IN VARCHAR2,
      P_STICHTAG     IN NUMBER,
      P_SUB_ID       IN VARCHAR2 DEFAULT '*')
   IS
      SQL_TRUNCATE                   VARCHAR2 (4000);
      VVPRUEF                        VARCHAR2 (4000);
      SQL_ADD_SUBPARTITION           VARCHAR2 (4000);
      PROOF_IF_DATA                  VARCHAR2 (4000);
      PARTITION_DOES_EXIST           EXCEPTION;
      PRAGMA EXCEPTION_INIT (PARTITION_DOES_EXIST, -14622);

      PARTITION_DOES_NOT_EXIST_SUB   EXCEPTION;
      PRAGMA EXCEPTION_INIT (PARTITION_DOES_NOT_EXIST_SUB, -14702);
      PARTITION_DOES_NOT_EXIST2      EXCEPTION;
      PRAGMA EXCEPTION_INIT (PARTITION_DOES_NOT_EXIST2, -02149);
   BEGIN
      -- Wenn keine bestimmte Subpartition angegeben ist, dann truncate auf Partition Ebene
      IF P_SUB_ID = '' OR P_SUB_ID = '*'
      THEN
         SQL_TRUNCATE :=
               'ALTER TABLE '
            || P_TABLE_NAME
            || ' TRUNCATE PARTITION FOR ('
            || P_STICHTAG
            || ') UPDATE INDEXES';
      ELSE
         SQL_TRUNCATE :=
               'ALTER TABLE '
            || P_TABLE_NAME
            || ' TRUNCATE SUBPARTITION FOR ('
            || P_STICHTAG
           || ','
            || ''''
            || P_SUB_ID
            || ''''
            || ') UPDATE INDEXES';
      END IF;

      EXECUTE IMMEDIATE (SQL_TRUNCATE);
   EXCEPTION
      -- Wenn diese bestimmte Subpartition bereits vorhanden ist, dann leere sie
      WHEN PARTITION_DOES_NOT_EXIST2
      THEN
         DBMS_OUTPUT.PUT_LINE (SQLERRM);
         NULL;
      WHEN PARTITION_DOES_NOT_EXIST_SUB
      THEN
         DBMS_OUTPUT.PUT_LINE (SQLERRM);
         NULL;
      WHEN OTHERS
      THEN
         RAISE_APPLICATION_ERROR (
            -20002,
            'P_TRUNC_I_SUB_PARTITION(): ' || SUBSTR (SQLERRM, 1, 500));
   END P_TRUNC_I_SUB_PARTITION;

END PCK_BAIS_UTIL;

Has anybody any idea why it can happen?

Body:
Your package specification and body don't match; so you will get a compilation error from the body, and your call will get PLS-00306.

Your specification says:

   PROCEDURE P_TRUNC_I_SUB_PARTITION;

so the procedure takes no arguments. That should match the body:

   PROCEDURE P_TRUNC_I_SUB_PARTITION (
      P_TABLE_NAME   IN VARCHAR2,
      P_STICHTAG     IN NUMBER,
      P_SUB_ID       IN VARCHAR2 DEFAULT '*'
   );

db<>fiddle with the modified specification.


答:
Set operation can help you

```<code>select customer_ref from customer_table
EXCEPT /* = MINUS */
select customer_ref from customer_table
where service = 'download'
</code>```

It is as easy as you would formulate it: all customers except those that used download.

Note also that the set operations return distinct key, so you do not nead to used distinct or some group by

Title: How do I select groups of customer references that don't use a particular service?

Body:
Using the following table (customer_table):

customer_ref
product
service

PI-003
cube
streaming

PI-722
cube
streaming

PI-723
cube
streaming

PI-724
cube
streaming

PI-724
pyramid
download

PI-725
cube
streaming

PI-727
cube
streaming

PI-728
cube
streaming

PI-729
cube
streaming

PI-729
pyramid
download

PI-730
cube
streaming

PI-730
sphere
radio

How do I select groups of customer references that don't use a download as a service?

If I do:
SELECT customer_ref FROM customer_table WHERE service <> download

It will return customer_ref PI-724 and PI-729 which do have a service that isn't download but I don't want to return them because under the same customer_ref they do have a service that is download - if that makes sense.

Under my parameters I want to return the following customer_ref:

customer_ref

PI-003

PI-722

PI-723

PI-725

PI-727

PI-728

PI-730

Body:
Set operation can help you

select customer_ref from customer_table
EXCEPT /* = MINUS */
select customer_ref from customer_table
where service = 'download'

It is as easy as you would formulate it: all customers except those that used download.

Note also that the set operations return distinct key, so you do not nead to used distinct or some group by


问:
Using css module in react app. How can I get rid of styles keyword
I used css modules in my react app and here is my code:

```<code>import styles from './PlayerCard.module.css';
import PlayerPhoto from '../../images/players/Farahani.png';

export default function PlayerCard() {
  return (
    <div className={styles.PlayerCard}>
      <img className={styles.PlayerPhoto} src={PlayerPhoto} alt="Player" />
      <p className={styles.PlayerName}>Farahani</p>

      <div className={styles.SkillBox}>
        <div className={styles.SkillName}>
          <p>Defence:</p>
</code>```

How can I get rid of those styles keywords? is there any way like destructuring or something?

答:
Yes you can use Object destructuring.

import styles from './PlayerCard.module.css';
import PlayerPhoto from '../../images/players/Farahani.png';

const { PlayerCard: PlayerCardStyle, PlayerPhoto: PlayerPhotoStyle, PlayerName: PlayerNameStyle, SkillBox, SkillName } = styles;

export default function PlayerCard() {
  return (

Farahani

Defence:

```
<p>Note that for <code>PlayerCard</code>, <code>PlayerPhoto</code>, and <code>PlayerName</code>, I need to alias it to different names so that they don't get conflicted with the components' names.</p>
<p>Alternatively, you can also import the styles like below:</p>
<pre class="lang-js prettyprint-override"><code>import { PlayerCard as PlayerCardStyle, PlayerPhoto as PlayerPhotoStyle, PlayerName as PlayerNameStyle, SkillBox, SkillName } from './PlayerCard.module.css'
</code>```

Similarly, you also have to alias the imports.

Body:
I used css modules in my react app and here is my code:

import styles from './PlayerCard.module.css';
import PlayerPhoto from '../../images/players/Farahani.png';

export default function PlayerCard() {
  return (

Farahani

Defence:

How can I get rid of those styles keywords? is there any way like destructuring or something?

Body:
Yes you can use Object destructuring.

import styles from './PlayerCard.module.css';
import PlayerPhoto from '../../images/players/Farahani.png';

const { PlayerCard: PlayerCardStyle, PlayerPhoto: PlayerPhotoStyle, PlayerName: PlayerNameStyle, SkillBox, SkillName } = styles;

export default function PlayerCard() {
  return (
    <div className={PlayerCardStyle}>
      <img className={PlayerPhotoStyle} src={PlayerPhoto} alt="Player" />
      <p className={PlayerNameStyle}>Farahani</p>

      <div className={styles.SkillBox}>
        <div className={styles.SkillName}>
          <p>Defence:</p>

Note that for PlayerCard, PlayerPhoto, and PlayerName, I need to alias it to different names so that they don't get conflicted with the components' names.

Alternatively, you can also import the styles like below:

import { PlayerCard as PlayerCardStyle, PlayerPhoto as PlayerPhotoStyle, PlayerName as PlayerNameStyle, SkillBox, SkillName } from './PlayerCard.module.css'

Similarly, you also have to alias the imports.


问:
Lock screen on Linux-based screens
Is there a lock screen on Linux-based systems?

When the screen is locked, the user should enter a PIN code to enter back. Like the PIN screen lock on an iPhone.

答: Often you have that choice in the screen saver. Then the computer will be locked after a specific time that you decide. You have it in Ubuntus screen saver.</p>

Title: Lock screen on Linux-based screens


问:
Why are colors not visible in the vuetify buttons?

i have made a card for sign in and there are no colours on any of the created components. the bottom of card consitst of two button but even those colors are not visible. i have attached the template section of my code. even the blue color of text fields is not visible. what can be the possible error?

<template>

    <v-container>
      <v-layout wrap>
        <v-row>
          <v-col cols="5">
            <v-img
              src="https://image.freepik.com/free-vector/programmer-working-flat-style_52683-15041.jpg?w=740"
              width="500"
              height="400"
            ></v-img>
          </v-col>
          <v-col cols="7" align-self="end">
            <v-flex sm12 md-8 offset-md3>
              <v-card elevation="6"  width="700">
                <v-card-title>
                  <v-layout align-center justify-space-between>

Sign In

                  </v-layout>
                </v-card-title>
                <v-divider></v-divider>
                <v-card-text>

Sign in with your username and password:

                  <v-text-field

                    autofocus
                    label="Email"
                    v-model="email"
                    type="email"
                  ></v-text-field>
                  <v-text-field
                    outline
                    hide-details
                    label="Password"
                    type="password"
                    v-model="password"
                  ></v-text-field>
                </v-card-text>

                <v-divider></v-divider>
                <v-container class="px-5" >
                  <v-checkbox
                    class="pl-1"
                    dense
                    label="Remember Me"
                  ></v-checkbox>
                </v-container>
                <v-card-actions>
                  <v-btn class="green--text" color="info" flat to="/forgotdialogue">
                  Forgot password?
                  </v-btn>
                  <v-spacer></v-spacer>

                  <v-btn @click="signUp" color="info">
                    <v-icon left>mdi-lock</v-icon>
                    Signup
                  </v-btn>
                </v-card-actions>
              </v-card>
            </v-flex>
          </v-col>
        </v-row>
      </v-layout>
    </v-container>

</template>```

答:
Got it
i just had to change my App.vue file.
in App.vue I included the code in between v-app tags. After this all the colors were restored. Read about it here in this vuetify page https://vuetifyjs.com/en/components/application/


问:
Does any monitoring metrics/events exist for ClickHouse keeper?
I am considering using ClickHouse keeper to replace zookeeper for data replication. And zookeeper has lots of useful metrics for monitoring/convenient triage. I checked ClickHouse documents and CurrentMetrics/ProfileEvents files but found no similar monitoring data to zk(https://zookeeper.apache.org/doc/r3.7.0/zookeeperMonitor.html).
Pls. direct me to the right way, thanks!</p>

答:
ClickHouse-keeper already supports 4-letter commands 'ruok' and 'mntr'

```<code># echo 'mntr' | nc localhost 9181
zk_version  v22.2.1.2764-testing-4fab6bec4ec53b66246a055919a4ed4c0610f650
zk_avg_latency  0
zk_max_latency  33
zk_min_latency  0
zk_packets_received 15430936
zk_packets_sent 15430936
zk_num_alive_connections    1
zk_outstanding_requests 0
zk_server_state standalone
zk_znode_count  4272
zk_watch_count  235
zk_ephemerals_count 111
zk_approximate_data_size    781777
zk_open_file_descriptor_count   203
zk_max_file_descriptor_count    18446744073709551615
zk_followers    0
zk_synced_followers 0

echo 'ruok' | nc localhost 9181
imok
</code>```

It is possible to export those in Prometheus format using external tools like https://github.com/dabealu/zookeeper-exporter

Future versions will have embedded Prometheus exporter.

Body:
ClickHouse-keeper already supports 4-letter commands 'ruok' and 'mntr'

# echo 'mntr' | nc localhost 9181
zk_version  v22.2.1.2764-testing-4fab6bec4ec53b66246a055919a4ed4c0610f650
zk_avg_latency  0
zk_max_latency  33
zk_min_latency  0
zk_packets_received 15430936
zk_packets_sent 15430936
zk_num_alive_connections    1
zk_outstanding_requests 0
zk_server_state standalone
zk_znode_count  4272
zk_watch_count  235
zk_ephemerals_count 111
zk_approximate_data_size    781777
zk_open_file_descriptor_count   203
zk_max_file_descriptor_count    18446744073709551615
zk_followers    0
zk_synced_followers 0

echo 'ruok' | nc localhost 9181
imok

It is possible to export those in Prometheus format using external tools like https://github.com/dabealu/zookeeper-exporter

Future versions will have embedded Prometheus exporter.


问:
How to stop a periodic function in golang
So I have a function that is called after every 2 seconds. Like this

```<code>package main

import (
    "fmt"
    "time"
)

func doEvery(d time.Duration, f func(time.Time)) {
    for x := range time.Tick(d) {
        f(x)
    }
}

func helloworld(t time.Time) {
    fmt.Printf("%v: Hello, World!\n", t)
}

func main() {
    doEvery(20*time.Millisecond, helloworld)
}
</code>```

Now lets say I no longer want this function to execute after every 2 seconds. Is there a way I can achieve this in golang? Or is there any better way than this to call a periodic function in golang? Thank you.

答:
Documentation of time.Tick() states it cannot be stopped:

Tick is a convenience wrapper for NewTicker providing access to the ticking channel only. While Tick is useful for clients that have no need to shut down the Ticker, be aware that without a way to shut it down the underlying Ticker cannot be recovered by the garbage collector; it "leaks".

If you need to stop it, use time.NewTicker() instead. Run doEvery() in a new goroutine, and pass a channel to it which gives you a mean to stop it, e.g. by closing the channel:

```<code>func doEvery(d time.Duration, done chan bool, f func(time.Time)) {
    ticker := time.NewTicker(d)
    defer ticker.Stop()

    for {
        select {
        case <-done:
            fmt.Println("Done!")
            return
        case t := <-ticker.C:
            f(t)
        }
    }
}
</code>```

Testing it:

```<code>done := make(chan bool)
go doEvery(300*time.Millisecond, done, helloworld)

time.Sleep(time.Second)
close(done)

time.Sleep(time.Second)
fmt.Println("Quitting")
</code>```

This will output (try it on the Go Playground):

```<code>2009-11-10 23:00:00.3 +0000 UTC m=+0.300000001: Hello, World!
2009-11-10 23:00:00.6 +0000 UTC m=+0.600000001: Hello, World!
2009-11-10 23:00:00.9 +0000 UTC m=+0.900000001: Hello, World!
Done!
Quitting
</code>```

Body:
So I have a function that is called after every 2 seconds. Like this

package main

import (
    "fmt"
    "time"
)

func doEvery(d time.Duration, f func(time.Time)) {
    for x := range time.Tick(d) {
        f(x)
    }
}

func helloworld(t time.Time) {
    fmt.Printf("%v: Hello, World!\n", t)
}

func main() {
    doEvery(20*time.Millisecond, helloworld)
}

Now lets say I no longer want this function to execute after every 2 seconds. Is there a way I can achieve this in golang? Or is there any better way than this to call a periodic function in golang? Thank you.

Body:
Documentation of time.Tick() states it cannot be stopped:

Tick is a convenience wrapper for NewTicker providing access to the ticking channel only. While Tick is useful for clients that have no need to shut down the Ticker, be aware that without a way to shut it down the underlying Ticker cannot be recovered by the garbage collector; it "leaks".

If you need to stop it, use time.NewTicker() instead. Run doEvery() in a new goroutine, and pass a channel to it which gives you a mean to stop it, e.g. by closing the channel:

func doEvery(d time.Duration, done chan bool, f func(time.Time)) {
    ticker := time.NewTicker(d)
    defer ticker.Stop()

    for {
        select {
        case <-done:
            fmt.Println("Done!")
            return
        case t := <-ticker.C:
            f(t)
        }
    }
}

Testing it:

done := make(chan bool)
go doEvery(300*time.Millisecond, done, helloworld)

time.Sleep(time.Second)
close(done)

time.Sleep(time.Second)
fmt.Println("Quitting")

This will output (try it on the Go Playground):

2009-11-10 23:00:00.3 +0000 UTC m=+0.300000001: Hello, World!
2009-11-10 23:00:00.6 +0000 UTC m=+0.600000001: Hello, World!
2009-11-10 23:00:00.9 +0000 UTC m=+0.900000001: Hello, World!
Done!
Quitting


问:
VBA userform to write down timestamp to range on sheet
In my excel file I have a worksheet for every person. This worksheet is copied according a template sheet after entering data.

Now for the next part I would like to add data to a specific range on the sheet of that person.

Let's start with a simple date stamp to Range E4:E53 for the specified sheet. I'm using a combobox so you can select someone from the list and this is where i'm struggling;

After selecting someone from the list, my code does not write down the data.

As shown in the picture, the Worksheet is set to nothing. How do I set the worksheet according to the selected person from the combobox?

```<code>Public Sub CommandButton1_Click()

    Dim lRow As String
    Dim Rng As Range
    Dim Rng2 As Range
    Dim ws As Worksheet

    Set ws = ComboBox1.List(I, 0)

    Set Rng = Range("C4, C53")
    Set Rng2 = Range("E4, Q53")
    lRow = ws.Cells(Rows.Count, 1).End(xlUp).Row

        With ws
            Rng.Cells.lRow.Value = Format(Time, "DD:MM:YYYY:HH:MM")

        End With
End sub
</code>```

答:
I assume that your list contains names of worksheets for each person, like {"Monica", "Adam"...}, right?

The problem in your case is that you try to use string value from ComboBox1 to define worksheet which is an object in worksheets collection.

You should get string value (name) of worksheet and then use it to set your ws object.

Here is simple code snippet, hope it is what you wanted to achieve :)

```<code>Private Sub ComboBox1_click()

Dim ws As Worksheet

'Define worksheet from worksheets collection
Set ws = worksheets(ComboBox1.Value)

ws.Range("A5").Value = "Hello!"

End Sub

Private Sub UserForm_Initialize()

Dim ws As Worksheet

'Make list of all worksheets
For Each ws In worksheets
    ComboBox1.AddItem ws.Name
Next ws

End Sub
</code>```

Body:
In my excel file I have a worksheet for every person. This worksheet is copied according a template sheet after entering data.

Now for the next part I would like to add data to a specific range on the sheet of that person.

Let's start with a simple date stamp to Range E4:E53 for the specified sheet. I'm using a combobox so you can select someone from the list and this is where i'm struggling;

After selecting someone from the list, my code does not write down the data.

As shown in the picture, the Worksheet is set to nothing. How do I set the worksheet according to the selected person from the combobox?

Public Sub CommandButton1_Click()

    Dim lRow As String
    Dim Rng As Range
    Dim Rng2 As Range
    Dim ws As Worksheet

    Set ws = ComboBox1.List(I, 0)

    Set Rng = Range("C4, C53")
    Set Rng2 = Range("E4, Q53")
    lRow = ws.Cells(Rows.Count, 1).End(xlUp).Row

        With ws
            Rng.Cells.lRow.Value = Format(Time, "DD:MM:YYYY:HH:MM")

        End With
End sub

Body:
I assume that your list contains names of worksheets for each person, like {"Monica", "Adam"...}, right?

The problem in your case is that you try to use string value from ComboBox1 to define worksheet which is an object in worksheets collection.

You should get string value (name) of worksheet and then use it to set your ws object.

Here is simple code snippet, hope it is what you wanted to achieve :)

Private Sub ComboBox1_click()

Dim ws As Worksheet

'Define worksheet from worksheets collection
Set ws = worksheets(ComboBox1.Value)

ws.Range("A5").Value = "Hello!"

End Sub

Private Sub UserForm_Initialize()

Dim ws As Worksheet

'Make list of all worksheets
For Each ws In worksheets
    ComboBox1.AddItem ws.Name
Next ws

End Sub


问:
Is there a scripting tool for Mac?
Is there a tool for Mac OS like Windows VBScript?

I want to write some script which generates folders automatically and copy & paste files according to input.

答: There is Automator, a tool to create automated tasks.  It's quite packed with useful stuff out of the box and easy and fun to use.</p>

Title: Is there a scripting tool for Mac?


问:
How to detect platform using Ionic 4
How to detect browser and mobileweb platform using Ionic 4 because when I tried with below code in desktop browser it is not falling in ‘core’ condition.

```<code>if (this.platform.is('core')) {
    alert('core platform');
  } else {
    alert('something else');
  }
</code>```

When I have debug in chrome developer tool it showing 'android' platform as per below snapshot.

Can anyone please help me how to detect platform in Ionic 4 or what can be the alternative for this?

答:
just do this:
First import</p>
```<code>import {Platform } from 'ionic-angular';

// >> Then init the platform like this:

 private platform: Platform,

     if(this.platform.is('ios')==true){
        //ios PlatForm
        }else{
        //Android PlatForm
     }
</code>```

Title: How to detect platform using Ionic 4

Body:
How to detect browser and mobileweb platform using Ionic 4 because when I tried with below code in desktop browser it is not falling in ‘core’ condition.

if (this.platform.is('core')) {
    alert('core platform');
  } else {
    alert('something else');
  }

When I have debug in chrome developer tool it showing 'android' platform as per below snapshot.

Can anyone please help me how to detect platform in Ionic 4 or what can be the alternative for this?

Body:
just do this:
First import

import {Platform } from 'ionic-angular';

// >> Then init the platform like this:

 private platform: Platform,

     if(this.platform.is('ios')==true){
        //ios PlatForm
        }else{
        //Android PlatForm
     }


问:
Close webview2 application after webpage submit button click
I have created a simple windows application that uses a webview2 to shows a Website in a winform. I need to close this windows application after submit button click on the website.

Is it possible?
I am new to Windows Development.

答:
The solution really depends to the content and how the page works. In most cases you should not close the app immediately after clicking on submit button and you need to wait until you receive the response of the submit and if the submit is successful, then you can close the window.

Here I share two examples:

Handle submit event and call a C# method from WebView2

Detect success of a submitted survey form based on URL

Please keep in mind, both examples are here for learning purpose to give you some idea on handling js events in C#. You need to tweak them to make them working on your specific case.

Example 1 - Handle submit event and call a C# method from WebView2

In the following example you can learn:

How to handle submit event of the form

How to call a C# method from JavaScript code and pass js object to .NET

Here is the code:

```<code>WebView2Host host;
private async void TestForm_Load(object sender, EventArgs e)
{
    await webView21.EnsureCoreWebView2Async();
    host = new WebView2Host(this);
    webView21.NavigateToString(
        "<html>" +
        "<head><title>Test from</title></head>" +
        "<body>" +
        "<form id='form1' action='/' method='post'>" +
        "<input type='text' name='someProperty' value ='something'/>" +
        "<input type='submit' value='Click me'/>" +
        "</form>" +
        "</body>");
    webView21.CoreWebView2.AddHostObjectToScript("host", host);
    webView21.CoreWebView2.DOMContentLoaded += CoreWebView2_DOMContentLoaded;
}
private async void CoreWebView2_DOMContentLoaded(object sender,
    CoreWebView2DOMContentLoadedEventArgs e)
{
    await webView21.ExecuteScriptAsync(
    "var form = document.getElementById('form1');" +
    "form.addEventListener('submit', function(e){" +
    "var data = JSON.stringify(Object.fromEntries(new FormData(form)));" +
    "window.chrome.webview.hostObjects.sync.host.OnSubmit(data);" +
    "});");
}
public class WebView2Host
{
    TestForm hostForm;
    public WebView2Host(TestForm hostForm)
    {
        this.hostForm = hostForm;
    }
    public void OnSubmit(string data)
    {
        //data is in json format
        MessageBox.Show($"data: {data}", "C# OnSubmit!");
        //You can close form like this: hostForm.Close();
    }
}
</code>```

Exmaple 2 - Detect success of a submitted survey form based on URL

You can rely on any of the navigation events and check the URL of the page, to see whether the submit has been successful. In this example I show how you can do it with a google survey form:

```<code>private async void TestForm_Load(object sender, EventArgs e)
{
    await webView21.EnsureCoreWebView2Async();
    webView21.Source = new Uri("https://forms.gle/pspLBJFZW5z8J1K37");
    webView21.CoreWebView2.SourceChanged += CoreWebView2_SourceChanged;
}
private void CoreWebView2_SourceChanged(object? sender,
    CoreWebView2SourceChangedEventArgs e)
{
    if (webView21.Source.ToString().EndsWith("/formResponse"))
    {
        MessageBox.Show("Submitted successfully.");
    }
}
</code>```

Body:
The solution really depends to the content and how the page works. In most cases you should not close the app immediately after clicking on submit button and you need to wait until you receive the response of the submit and if the submit is successful, then you can close the window.

Here I share two examples:

Handle submit event and call a C# method from WebView2

Detect success of a submitted survey form based on URL

Please keep in mind, both examples are here for learning purpose to give you some idea on handling js events in C#. You need to tweak them to make them working on your specific case.

Example 1 - Handle submit event and call a C# method from WebView2

In the following example you can learn:

How to handle submit event of the form

How to call a C# method from JavaScript code and pass js object to .NET

Here is the code:

WebView2Host host;
private async void TestForm_Load(object sender, EventArgs e)
{
    await webView21.EnsureCoreWebView2Async();
    host = new WebView2Host(this);
    webView21.NavigateToString(
        "<html>" +
        "<head><title>Test from</title></head>" +
        "<body>" +
        "<form id='form1' action='/' method='post'>" +
        "<input type='text' name='someProperty' value ='something'/>" +
        "<input type='submit' value='Click me'/>" +
        "</form>" +
        "</body>");
    webView21.CoreWebView2.AddHostObjectToScript("host", host);
    webView21.CoreWebView2.DOMContentLoaded += CoreWebView2_DOMContentLoaded;
}
private async void CoreWebView2_DOMContentLoaded(object sender,
    CoreWebView2DOMContentLoadedEventArgs e)
{
    await webView21.ExecuteScriptAsync(
    "var form = document.getElementById('form1');" +
    "form.addEventListener('submit', function(e){" +
    "var data = JSON.stringify(Object.fromEntries(new FormData(form)));" +
    "window.chrome.webview.hostObjects.sync.host.OnSubmit(data);" +
    "});");
}
public class WebView2Host
{
    TestForm hostForm;
    public WebView2Host(TestForm hostForm)
    {
        this.hostForm = hostForm;
    }
    public void OnSubmit(string data)
    {
        //data is in json format
        MessageBox.Show($"data: {data}", "C# OnSubmit!");
        //You can close form like this: hostForm.Close();
    }
}

Exmaple 2 - Detect success of a submitted survey form based on URL

You can rely on any of the navigation events and check the URL of the page, to see whether the submit has been successful. In this example I show how you can do it with a google survey form:

private async void TestForm_Load(object sender, EventArgs e)
{
    await webView21.EnsureCoreWebView2Async();
    webView21.Source = new Uri("https://forms.gle/pspLBJFZW5z8J1K37");
    webView21.CoreWebView2.SourceChanged += CoreWebView2_SourceChanged;
}
private void CoreWebView2_SourceChanged(object? sender,
    CoreWebView2SourceChangedEventArgs e)
{
    if (webView21.Source.ToString().EndsWith("/formResponse"))
    {
        MessageBox.Show("Submitted successfully.");
    }
}


问:
Error while trying to do App Registration using Terraform Azure AD Provider 2.0
I am trying to do app registration using Terraform Azure AD 2.0 provider and i get the below error while apply.
The Object ID is that for Microsoft Graph.
All the well known IDs are provided below :

https://github.com/manicminer/hamilton/blob/main/environments/published.go
https://registry.terraform.io/providers/hashicorp/azuread/latest/docs/data-sources/application_published_app_ids

│

```<code>Error: Updating service principal with object ID: "a2f717fe-bc5d-42e5-b0b4-801562508280"
│
│   with azuread_service_principal.msgraph,
│   on resources.application.tf line 220, in resource "azuread_service_principal" "msgraph":
│  220: resource "azuread_service_principal" "msgraph" {
│
│ ServicePrincipalsClient.BaseClient.Patch(): unexpected status 403 with
│ OData error: Authorization_RequestDenied: Insufficient privileges to
│ complete the operation.
</code>```

Below is my code :

```<code>data "azuread_application_published_app_ids" "well_known" {}

data "azuread_service_principal" "msgraph" {
  application_id = data.azuread_application_published_app_ids.well_known.result.MicrosoftGraph
}

resource "azuread_service_principal" "msgraph" {
  application_id = data.azuread_application_published_app_ids.well_known.result.MicrosoftGraph
  use_existing   = true
}

resource "azuread_application" "app-api" {
  display_name = format("app-%s-api-%s", var.project.name, var.project.environment.name)
  owners       = [data.azuread_client_config.default.object_id]

  api {
    oauth2_permission_scope {
      admin_consent_description  = "Allows the app to read and write data"
      admin_consent_display_name = local.oauth2_permissions.read-and-write.admin_consent_display_name
      enabled                    = true
      id                         = random_uuid.opsys-gw.result
      type                       = "User"
      value                      = "read-and-write"
    }
  }

  app_role {
    allowed_member_types = ["User", "Application"]
    description          = "Application administrators have the ability to administer the application."
    display_name         = local.app_roles.application-administrator.display_name
    enabled              = true
    id                   = data.azuread_client_config.default.object_id
    value                = "application-administrator"
  }

  web {
    logout_url    = format("https://%s.azurewebsites.net/.auth/logout", module.name_app_service_api.location.app_service.name_unique)
    redirect_uris = [format("https://%s.azurewebsites.net/.auth/login/aad/callback", module.name_app_service_api.location.app_service.name_unique)]

    implicit_grant {
      access_token_issuance_enabled = true
      id_token_issuance_enabled     = true
    }
  }

  required_resource_access {
    resource_app_id = data.azuread_application_published_app_ids.well_known.result.MicrosoftGraph # Microsoft Graph

     resource_access {
          id   = azuread_service_principal.msgraph.app_role_ids["User.Read.All"]
          type = "Role"
        }

        resource_access {
          id   = random_uuid.opsys-gw.result # User.Read.All
          type = "Scope"
        }
      }
    }
</code>```

Azure AD API Service Principal Resource

```<code>resource "azuread_service_principal" "api-sp" {
  application_id               = azuread_application.app-api.application_id
  app_role_assignment_required = false
  owners                       = [data.azuread_client_config.default.object_id]
}
</code>```

Azure AD API App Service Principal Secret

```<code>resource "azuread_application_password" "api-app-sp-secret" {
  application_object_id = azuread_application.app-api.object_id
}
</code>```

My Terraform Service Principal Application  already has been assigned the required permissions  in Azure AD as shown in the attachment

答:
When i tried with your above code as a normal user was getting the same error(as i didn't know i should require a priviledge of Application Administator Or Global AdminStrator Role in my tenant.

Once I got the above one of roles and adminsitator permission so then able to run the code.

Also you need to Remove this statement from your code.

```<code> data "azuread_service_principal" "msgraph" {
      application_id = data.azuread_application_published_app_ids.well_known.result.MicrosoftGraph
    }
</code>```

Terraform Code:

```<code># Configure the Azure Active Directory Provider
provider "azuread" {

}

data "azuread_client_config" "current" {}

data "azuread_application_published_app_ids" "well_known" {}

resource "azuread_service_principal" "msgraph" {
  application_id = data.azuread_application_published_app_ids.well_known.result.MicrosoftGraph
  use_existing = true
}

resource "azuread_application" "app-api" {
  display_name = "example3724"
  owners       = [data.azuread_client_config.current.object_id]

  api {
     oauth2_permission_scope {
      admin_consent_description  = "Allow the application to access example on behalf of the signed-in user."
      admin_consent_display_name = "Access example"
      enabled                    = true
      id                         = "96183846-204b-4b43-82e1-5d2222eb4b9b"
      type                       = "User"
      user_consent_description   = "Allow the application to access example on your behalf."
      user_consent_display_name  = "Access example"
      value                      = "user_impersonation"
    }
  }

  app_role {
    allowed_member_types = ["User", "Application"]
    description          = "Admins can manage roles and perform all task actions"
    display_name         = "Admin"
    enabled              = true
    id                   = data.azuread_client_config.current.object_id
    value                = "application-administrator"
  }

  web {
    homepage_url  = "https://app.example.net"
    logout_url    = "https://app.example.net/logout"
    redirect_uris = ["https://app.example.net/account"]

    implicit_grant {
      access_token_issuance_enabled = true
      id_token_issuance_enabled     = true
    }
  }

  required_resource_access {
    resource_app_id = data.azuread_application_published_app_ids.well_known.result.MicrosoftGraph # Microsoft Graph

     resource_access {
          id   = azuread_service_principal.msgraph.app_role_ids["User.Read.All"]
          type = "Role"
        }

        resource_access {
          id   = azuread_service_principal.msgraph.oauth2_permission_scope_ids["User.ReadWrite"]# User.Read.All
          type = "Scope"
        }
      }
    }
</code>```

OutPut--

Body:
I am trying to do app registration using Terraform Azure AD 2.0 provider and i get the below error while apply.
The Object ID is that for Microsoft Graph.
All the well known IDs are provided below :

https://github.com/manicminer/hamilton/blob/main/environments/published.go
https://registry.terraform.io/providers/hashicorp/azuread/latest/docs/data-sources/application_published_app_ids

│

Error: Updating service principal with object ID: "a2f717fe-bc5d-42e5-b0b4-801562508280"
│
│   with azuread_service_principal.msgraph,
│   on resources.application.tf line 220, in resource "azuread_service_principal" "msgraph":
│  220: resource "azuread_service_principal" "msgraph" {
│
│ ServicePrincipalsClient.BaseClient.Patch(): unexpected status 403 with
│ OData error: Authorization_RequestDenied: Insufficient privileges to
│ complete the operation.

Below is my code :

data "azuread_application_published_app_ids" "well_known" {}

data "azuread_service_principal" "msgraph" {
  application_id = data.azuread_application_published_app_ids.well_known.result.MicrosoftGraph
}

resource "azuread_service_principal" "msgraph" {
  application_id = data.azuread_application_published_app_ids.well_known.result.MicrosoftGraph
  use_existing   = true
}

resource "azuread_application" "app-api" {
  display_name = format("app-%s-api-%s", var.project.name, var.project.environment.name)
  owners       = [data.azuread_client_config.default.object_id]

  api {
    oauth2_permission_scope {
      admin_consent_description  = "Allows the app to read and write data"
      admin_consent_display_name = local.oauth2_permissions.read-and-write.admin_consent_display_name
      enabled                    = true
      id                         = random_uuid.opsys-gw.result
      type                       = "User"
      value                      = "read-and-write"
    }
  }

  app_role {
    allowed_member_types = ["User", "Application"]
    description          = "Application administrators have the ability to administer the application."
    display_name         = local.app_roles.application-administrator.display_name
    enabled              = true
    id                   = data.azuread_client_config.default.object_id
    value                = "application-administrator"
  }

  web {
    logout_url    = format("https://%s.azurewebsites.net/.auth/logout", module.name_app_service_api.location.app_service.name_unique)
    redirect_uris = [format("https://%s.azurewebsites.net/.auth/login/aad/callback", module.name_app_service_api.location.app_service.name_unique)]

    implicit_grant {
      access_token_issuance_enabled = true
      id_token_issuance_enabled     = true
    }
  }

  required_resource_access {
    resource_app_id = data.azuread_application_published_app_ids.well_known.result.MicrosoftGraph # Microsoft Graph

     resource_access {
          id   = azuread_service_principal.msgraph.app_role_ids["User.Read.All"]
          type = "Role"
        }

        resource_access {
          id   = random_uuid.opsys-gw.result # User.Read.All
          type = "Scope"
        }
      }
    }

Azure AD API Service Principal Resource

resource "azuread_service_principal" "api-sp" {
  application_id               = azuread_application.app-api.application_id
  app_role_assignment_required = false
  owners                       = [data.azuread_client_config.default.object_id]
}

Azure AD API App Service Principal Secret

resource "azuread_application_password" "api-app-sp-secret" {
  application_object_id = azuread_application.app-api.object_id
}

My Terraform Service Principal Application  already has been assigned the required permissions  in Azure AD as shown in the attachment

Body:
When i tried with your above code as a normal user was getting the same error(as i didn't know i should require a priviledge of Application Administator Or Global AdminStrator Role in my tenant.

Once I got the above one of roles and adminsitator permission so then able to run the code.

Also you need to Remove this statement from your code.

 data "azuread_service_principal" "msgraph" {
      application_id = data.azuread_application_published_app_ids.well_known.result.MicrosoftGraph
    }

Terraform Code:

# Configure the Azure Active Directory Provider
provider "azuread" {

}

data "azuread_client_config" "current" {}

data "azuread_application_published_app_ids" "well_known" {}

resource "azuread_service_principal" "msgraph" {
  application_id = data.azuread_application_published_app_ids.well_known.result.MicrosoftGraph
  use_existing = true
}

resource "azuread_application" "app-api" {
  display_name = "example3724"
  owners       = [data.azuread_client_config.current.object_id]

  api {
     oauth2_permission_scope {
      admin_consent_description  = "Allow the application to access example on behalf of the signed-in user."
      admin_consent_display_name = "Access example"
      enabled                    = true
      id                         = "96183846-204b-4b43-82e1-5d2222eb4b9b"
      type                       = "User"
      user_consent_description   = "Allow the application to access example on your behalf."
      user_consent_display_name  = "Access example"
      value                      = "user_impersonation"
    }
  }

  app_role {
    allowed_member_types = ["User", "Application"]
    description          = "Admins can manage roles and perform all task actions"
    display_name         = "Admin"
    enabled              = true
    id                   = data.azuread_client_config.current.object_id
    value                = "application-administrator"
  }

  web {
    homepage_url  = "https://app.example.net"
    logout_url    = "https://app.example.net/logout"
    redirect_uris = ["https://app.example.net/account"]

    implicit_grant {
      access_token_issuance_enabled = true
      id_token_issuance_enabled     = true
    }
  }

  required_resource_access {
    resource_app_id = data.azuread_application_published_app_ids.well_known.result.MicrosoftGraph # Microsoft Graph

     resource_access {
          id   = azuread_service_principal.msgraph.app_role_ids["User.Read.All"]
          type = "Role"
        }

        resource_access {
          id   = azuread_service_principal.msgraph.oauth2_permission_scope_ids["User.ReadWrite"]# User.Read.All
          type = "Scope"
        }
      }
    }

OutPut--


问:
Jenkins: Set job timeout from a variable in scripted pipeline
I premise that I am not very familiar with Jenkins and Groovy.
I am trying to set a timeout with a time value that can change based on a specific condition. I was wondering if it is possible to do this and how.

This is a shortened example for simplicity, of the pipeline I'm dealing with:

```<code>/**
 * prepare tests for parallel
 * @param filename Name of the file that contains the testsuites list
 */
def doDynamicParallelSteps(filename){
    tests = [:]
    echo "doDynamicParallelSteps"
    def w = pwd()
    def path = "$w/$filename"
    // read all the lines into a list, each line is an element in the list
    def fh = new File(path)
    def lines = fh.readLines()
    for (line in lines) {
        def values = line.split(":")
        def testsuite_name = values[0].trim()
        def test_path = values[1].trim()
        def test_filename_or_directory = test_path.split("/").getAt(-1);
        def is_file = test_filename_or_directory.matches("(.*).php")
        def is_custom_mycondition = test_filename_or_directory.matches("MyMatchCondition")
        if (is_custom_mycondition){ // large timeout
            def time_val = 10
        } else { // default timeout
            def time_val = 5
        }
        tests["${test_filename_or_directory}"] = {
            stage("UnitTest ${test_filename_or_directory}") {
                timeout(time: time_val, unit: 'MINUTES') { // scripted syntax
                    // other stuff here
                } // end timeout
            } // end stage
        } // end MAP
    }
    parallel tests
}
</code>```

If I run this pipeline I got the following output:

hudson.remoting.ProxyException: groovy.lang.MissingPropertyException: No such property: time_val for class: mycustomJob

Then I've tried to set it as global value and it worked but not as expected, because its value doesn't seems to changed, it outputs "5" ignoring my condition.

What am I doing wrong? Can anyone show me the right way or a better approach?

答:
What you are doing looks more pythonic than groovy. You must define the variable 'time_val' on a higher level to make it visible in your scope, like:

def time_val = 5
if (is_custom_mycondition){ // large timeout
    time_val = 10
}
```
<p>Instead of your else part.<br />
You can also define it in a single line, like:</p>
<pre class="lang-groovy prettyprint-override"><code>def time_val = is_custom_mycondition ? 10 : 5
</code>```

Your 'timeout' usage looks correct to me. Just define the variable properly.

Body:
I premise that I am not very familiar with Jenkins and Groovy.
I am trying to set a timeout with a time value that can change based on a specific condition. I was wondering if it is possible to do this and how.

This is a shortened example for simplicity, of the pipeline I'm dealing with:

/**
 * prepare tests for parallel
 * @param filename Name of the file that contains the testsuites list
 */
def doDynamicParallelSteps(filename){
    tests = [:]
    echo "doDynamicParallelSteps"
    def w = pwd()
    def path = "$w/$filename"
    // read all the lines into a list, each line is an element in the list
    def fh = new File(path)
    def lines = fh.readLines()
    for (line in lines) {
        def values = line.split(":")
        def testsuite_name = values[0].trim()
        def test_path = values[1].trim()
        def test_filename_or_directory = test_path.split("/").getAt(-1);
        def is_file = test_filename_or_directory.matches("(.*).php")
        def is_custom_mycondition = test_filename_or_directory.matches("MyMatchCondition")
        if (is_custom_mycondition){ // large timeout
            def time_val = 10
        } else { // default timeout
            def time_val = 5
        }
        tests["${test_filename_or_directory}"] = {
            stage("UnitTest ${test_filename_or_directory}") {
                timeout(time: time_val, unit: 'MINUTES') { // scripted syntax
                    // other stuff here
                } // end timeout
            } // end stage
        } // end MAP
    }
    parallel tests
}

If I run this pipeline I got the following output:

hudson.remoting.ProxyException: groovy.lang.MissingPropertyException: No such property: time_val for class: mycustomJob

Then I've tried to set it as global value and it worked but not as expected, because its value doesn't seems to changed, it outputs "5" ignoring my condition.

What am I doing wrong? Can anyone show me the right way or a better approach?

Body:
What you are doing looks more pythonic than groovy. You must define the variable 'time_val' on a higher level to make it visible in your scope, like:

def time_val = 5
if (is_custom_mycondition){ // large timeout
    time_val = 10
}

Instead of your else part.

You can also define it in a single line, like:

def time_val = is_custom_mycondition ? 10 : 5

Your 'timeout' usage looks correct to me. Just define the variable properly.


问:
Applying insert or update on aggregated column in ADF Dataflow
I have dataflow that is doing some joins and a count on columns which then sinks into Azure SQL table.
Azure SQL table structure has a GUID as ID column.

What I want is that when the values in the count column change, for it to update in the Azure SQL table. Rather than an insert.

I use this code in SQL for it to work, but I want to implement this in ADF Dataflow. I am using Alter Row expression true() for upserts. Doesn't seem to be working when it comes to counts. Not sure where I am wrong.
Please ask for clarification if needed.

Below is the SQL code that works and I want to implement that in ADF.

```<code>MERGE [Target] AS [T]
USING [#Temp] AS [S]
ON [T].[Filter] = [S].[Filter]
   AND ISNULL([T].[OrganisationGroup], '') = ISNULL([S].[OrganisationGroup], '')
   AND ISNULL([T].[ItemCatalog], '') = ISNULL([S].[FinancialReference], '')
   AND ISNULL([T].[CIType], '') = ISNULL([S].[CIType], '')
   AND ISNULL([T].[ConfigurationItemTypeName], '') = ISNULL([S].[ConfigurationItemTypeName], '')
   AND ISNULL([T].[Status], '') = ISNULL([S].[Status], '')
  AND ISNULL([T].[Further_Detail], '') = ISNULL([S].[Further_Detail], '')
   AND ISNULL([T].[PartitionKey], '') = ISNULL([S].[PartitionKey], '')
WHEN MATCHED AND [T].[CICount] <> [S].[CICount] THEN
    UPDATE SET [T].[CICount] = [S].[CICount]
WHEN NOT MATCHED BY SOURCE THEN
    DELETE
WHEN NOT MATCHED THEN
    INSERT
</code>```

答:
I have repro’d in my lab with some sample data, please find the below steps.

Existing data in the SQL table (table tb2):

ADF data flow:

Connect the source to the input dataset. Here I have new records compared to existing SQL data, so the count will be updated, and new records will be inserted if not matched.

Adding aggregate to get the count of the input records.

Aggregate data preview:

Adding Alter row transformation to perform upsert.

Upsert condition:

and(and(isNull(Name)== false(),isNull(Department)== false()),isNull(Status)== false())

Note: Here, include all columns except count as we are performing upsert based on Count column.

Alter row data preview:

Connect Sink to SQL table. In settings, enable Allow upsert and include a list of key columns.

Sink preview:

After execution, Count in the sink table is updated for existing records when the count is not matched and new records are inserted.

Body:
I have dataflow that is doing some joins and a count on columns which then sinks into Azure SQL table.
Azure SQL table structure has a GUID as ID column.

What I want is that when the values in the count column change, for it to update in the Azure SQL table. Rather than an insert.

I use this code in SQL for it to work, but I want to implement this in ADF Dataflow. I am using Alter Row expression true() for upserts. Doesn't seem to be working when it comes to counts. Not sure where I am wrong.
Please ask for clarification if needed.

Below is the SQL code that works and I want to implement that in ADF.

MERGE [Target] AS [T]
USING [#Temp] AS [S]
ON [T].[Filter] = [S].[Filter]
   AND ISNULL([T].[OrganisationGroup], '') = ISNULL([S].[OrganisationGroup], '')
   AND ISNULL([T].[ItemCatalog], '') = ISNULL([S].[FinancialReference], '')
   AND ISNULL([T].[CIType], '') = ISNULL([S].[CIType], '')
   AND ISNULL([T].[ConfigurationItemTypeName], '') = ISNULL([S].[ConfigurationItemTypeName], '')
   AND ISNULL([T].[Status], '') = ISNULL([S].[Status], '')
  AND ISNULL([T].[Further_Detail], '') = ISNULL([S].[Further_Detail], '')
   AND ISNULL([T].[PartitionKey], '') = ISNULL([S].[PartitionKey], '')
WHEN MATCHED AND [T].[CICount] <> [S].[CICount] THEN
    UPDATE SET [T].[CICount] = [S].[CICount]
WHEN NOT MATCHED BY SOURCE THEN
    DELETE
WHEN NOT MATCHED THEN
    INSERT


问:
irazasyed/telegram-bot-sdk get update object on commands
I was using irazasyed/telegram-bot-sdk for a Telegram bot in Laravel. I just wanted to access the update object on my StartCommand class and send a welcome message to a user with his name. The StartCommand class looks like this:

```<code><?php

namespace App\TelegramCommands;

use Telegram\Bot\Commands\Command;

class StartCommand extends Command
{
    protected $name = "start";

    protected $description = "Lets you get started";

    public function handle()
    {
        $this->replyWithMessage(['text' => 'Welcome ']);
    }
}
</code>```

And the route (which is inside api.php) is:

```<code>Route::post('/'.env('TELEGRAM_BOT_TOKEN').'/webhook', function (Request $request) {
    $update = Telegram::commandsHandler(true);
    return 'ok';
});
</code>```

I just wanted to access users data when he sends /start command and replay with a message like, "Welcome [his name]". Thank you in advance.

答:
I just have got the answer. It was mainly adding the following to the handle method of StartCommand class:

```<code>$update= $this->getUpdate();
</code>```

So the final file will look like:

```<code><?php

namespace App\TelegramCommands;

use Telegram\Bot\Commands\Command;

class StartCommand extends Command
{
    protected $name = "start";

    protected $description = "Lets you get started";

    public function handle()
    {
        $update= $this->getUpdate();
        $name = $update['message']['from']['first_name'];
        $this->replyWithMessage(['text' => 'Welcome '.$name]);
    }
}
</code>```

A good tutorial is here

Body:
I was using irazasyed/telegram-bot-sdk for a Telegram bot in Laravel. I just wanted to access the update object on my StartCommand class and send a welcome message to a user with his name. The StartCommand class looks like this:

<?php

namespace App\TelegramCommands;

use Telegram\Bot\Commands\Command;

class StartCommand extends Command
{
    protected $name = "start";

    protected $description = "Lets you get started";

    public function handle()
    {
        $this->replyWithMessage(['text' => 'Welcome ']);
    }
}

And the route (which is inside api.php) is:

Route::post('/'.env('TELEGRAM_BOT_TOKEN').'/webhook', function (Request $request) {
    $update = Telegram::commandsHandler(true);
    return 'ok';
});

I just wanted to access users data when he sends /start command and replay with a message like, "Welcome [his name]". Thank you in advance.

Body:
I just have got the answer. It was mainly adding the following to the handle method of StartCommand class:

$update= $this->getUpdate();

So the final file will look like:

<?php

namespace App\TelegramCommands;

use Telegram\Bot\Commands\Command;

class StartCommand extends Command
{
    protected $name = "start";

    protected $description = "Lets you get started";

    public function handle()
    {
        $update= $this->getUpdate();
        $name = $update['message']['from']['first_name'];
        $this->replyWithMessage(['text' => 'Welcome '.$name]);
    }
}

A good tutorial is here


问:
How to add HTML-Payload for all redirections via Location-Header
Is it possible to intercept all responses with redirection via location header to enrich the payload with HTML meta refresh or redirection via JS?</p>

答:
Current Solution that works for me and is used during authentication redirection:

Configure a Filter after LogoutFilter.class. This Filter wraps HttpServletResponse. This wrapper of HttpServletResponse overrides HttpServletResponse#sendRedirect(String) to print to response writer and HttpServletResponse#setHeader(String) to also print to response writer -- in case someone didn't use #sendRedirect(String) but set Location header.

The Reason to override #sendRedirect(String) ist that the response stream is reset before at the beginn and closes the stream at the end.

No embedded implementation provides by default a payload for redirection.
Tomcat can use 'coyoteResponse.sendRedirect.note' property and print it in redirect. Jetty and Undertow do not print to response writer any payload.

Note: Not using Location header to redirect slows website response and IMHO makes a horrible user experience.


问:
I need to insert .csv file (stripping out a certain characters from a column) into a Table in SSMS, using T-SQL
I have the following .csv file:

I need to import this file into the table (MyTable) with the same fields-  in SSMS, using T-SQL statements.

My import result should also remove any characters before '-' sign, in the ID column

So, I expect the following in the SSMS table:

Trying the following code, but I am not familiar with the correct syntax.
It's incorrect and I don't know the correct way of writing this.
Also, not sure if this even possible to achieve:

```<code>      INSERT INTO myTable1 ([Name], [ID])

      SELECT
            (Text1.[Name],
             RIGHT(Text1.[ID]), LEN(Text1.[ID]) - Charindex('-', Text1.[ID]))

      FROM OPENROWSET(BULK 'E:\$_Data\OQ\Text1.csv', SINGLE_BLOB) AS ttt;
</code>```

RIGHT(Text1.[ID]), LEN(Text1.[ID]) - Charindex('-', Text1.[ID])) - that's where I am stripping out  everything before '-', including this character. It works in a regular SELECT OR JOIN statement
But not here

答:
I'd suggest to use OPENROWSET with a format file describing the columns in your CSV file. According to the docs an xml format file could look like this for your sample data:

```<code><?xml version="1.0"?>
<BCPFORMAT    xmlns="http://schemas.microsoft.com/sqlserver/2004/bulkload/format" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <RECORD>
      <FIELD ID="1" xsi:type="CharTerm" TERMINATOR=";" MAX_LENGTH="7"/>
      <FIELD ID="2" xsi:type="CharTerm" TERMINATOR="\r\n" MAX_LENGTH="20" COLLATION="SQL_Latin1_General_CP1_CI_AS"/>
    </RECORD>
    <ROW>
      <COLUMN SOURCE="1" NAME="Name" xsi:type="SQLNVARCHAR"/>
      <COLUMN SOURCE="2" NAME="ID" xsi:type="SQLNVARCHAR"/>
    </ROW>
</BCPFORMAT>
</code>```

Then, use it in the openrowset statement:

```<code>SELECT
     Name
    ,[ID]
FROM OPENROWSET (
    BULK N'path-to\test.csv',
    FIRSTROW=2,
    FORMATFILE = N'path-to\test-csv.xml'
) AS ttt;
</code>```

And at last your stripping code seems to have bad syntax - RIGHT expects two arguments:

```<code>RIGHT([ID], LEN([ID]) - Charindex('-', [ID])) AS STRIPPED_ID
</code>```

Body:
I have the following .csv file:

I need to import this file into the table (MyTable) with the same fields-  in SSMS, using T-SQL statements.

My import result should also remove any characters before '-' sign, in the ID column

So, I expect the following in the SSMS table:

Trying the following code, but I am not familiar with the correct syntax.
It's incorrect and I don't know the correct way of writing this.
Also, not sure if this even possible to achieve:

      INSERT INTO myTable1 ([Name], [ID])

      SELECT
            (Text1.[Name],
             RIGHT(Text1.[ID]), LEN(Text1.[ID]) - Charindex('-', Text1.[ID]))

      FROM OPENROWSET(BULK 'E:\$_Data\OQ\Text1.csv', SINGLE_BLOB) AS ttt;

RIGHT(Text1.[ID]), LEN(Text1.[ID]) - Charindex('-', Text1.[ID])) - that's where I am stripping out  everything before '-', including this character. It works in a regular SELECT OR JOIN statement
But not here

Body:
I'd suggest to use OPENROWSET with a format file describing the columns in your CSV file. According to the docs an xml format file could look like this for your sample data:

<?xml version="1.0"?>
<BCPFORMAT    xmlns="http://schemas.microsoft.com/sqlserver/2004/bulkload/format" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <RECORD>
      <FIELD ID="1" xsi:type="CharTerm" TERMINATOR=";" MAX_LENGTH="7"/>
      <FIELD ID="2" xsi:type="CharTerm" TERMINATOR="\r\n" MAX_LENGTH="20" COLLATION="SQL_Latin1_General_CP1_CI_AS"/>
    </RECORD>
    <ROW>
      <COLUMN SOURCE="1" NAME="Name" xsi:type="SQLNVARCHAR"/>
      <COLUMN SOURCE="2" NAME="ID" xsi:type="SQLNVARCHAR"/>
    </ROW>
</BCPFORMAT>

Then, use it in the openrowset statement:

SELECT
     Name
    ,[ID]
FROM OPENROWSET (
    BULK N'path-to\test.csv',
    FIRSTROW=2,
    FORMATFILE = N'path-to\test-csv.xml'
) AS ttt;

And at last your stripping code seems to have bad syntax - RIGHT expects two arguments:

RIGHT([ID], LEN([ID]) - Charindex('-', [ID])) AS STRIPPED_ID


问:
How to solve this weird caching issue in PHP?
I'm running into a weird caching issue, which I don't understand how to fix it.

I load a json file:

```<code>$json       = file_get_contents($filename);
</code>```

This is the content of the json file:

```<code>[{"Original":"original_1","Replacement":"replacement_1"},{"Original":"original_2","Replacement":"replacement_2"}
</code>```

The content is fresh. When I edit the json file content and reload it, a dump shows that $json contains the actual content.

The json file contains words and their replacements. I will use these in a string replace routine:

```<code>$srarr      = json_decode($json, true);
$original   = array_column($srarr, 'Original');
$replacement= array_column($srarr, 'Replacement');
$text_after = str_ireplace($original, $replacement, $text);
</code>```

The values in $original show the actual (fresh) original words. (a dump shows they're up to date and not cached)

The values in $replacement also show the actual (fresh) replacement words. (also up to date and not cached)

But the variable $text_after contains old cached replacement versions of replacement words that are not in $replacement.

These replacement words are not in the json file anymore, not in $srarr and not in $replacement.

Still the final result is that $text_after contains these old replacement words.

Somehow it looks like the old values are cached somewhere. But where? And how do I flush this cache everytime? Or how do I prevent this caching?

I tried adding opcache_invalidate(__FILE__, true); but that doesn't change anything.

Any suggestions, please?

答:
After all it was not a caching issue. The issue was that parts of larger words were also replaced instead of whole words only. That changed the final text and other replacements could not be found anymore.

It looked like I was dealing with a caching issue, but in fact it was my misinterpretation of the functionality of the str_ireplace function.

I changed the code into preg_replace and put it in a 'for' loop. With preg_replace it's possible to replace whole words only.

If anyone has a similar issue, maybe the following code can help:

```<code>    if (file_exists($filename)) {

        $json       = file_get_contents($filename);
        $json       = '['.$json.']';

        $srarr      = json_decode($json, true);
        $ori_arr    = array_column($srarr, 'Original');
        $rep_arr    = array_column($srarr, 'Replacement');

        $count = count($ori_arr);

        for ($i = 0; $i < $count; $i++) {
            $text    = preg_replace("/\b$ori_arr[$i]\b/",$rep_arr[$i],$text);
        }
    }
</code>```

Body:
I'm running into a weird caching issue, which I don't understand how to fix it.

I load a json file:

$json       = file_get_contents($filename);

This is the content of the json file:

[{"Original":"original_1","Replacement":"replacement_1"},{"Original":"original_2","Replacement":"replacement_2"}

The content is fresh. When I edit the json file content and reload it, a dump shows that $json contains the actual content.

The json file contains words and their replacements. I will use these in a string replace routine:

$srarr      = json_decode($json, true);
$original   = array_column($srarr, 'Original');
$replacement= array_column($srarr, 'Replacement');
$text_after = str_ireplace($original, $replacement, $text);

The values in $original show the actual (fresh) original words. (a dump shows they're up to date and not cached)

The values in $replacement also show the actual (fresh) replacement words. (also up to date and not cached)

But the variable $text_after contains old cached replacement versions of replacement words that are not in $replacement.

These replacement words are not in the json file anymore, not in $srarr and not in $replacement.

Still the final result is that $text_after contains these old replacement words.

Somehow it looks like the old values are cached somewhere. But where? And how do I flush this cache everytime? Or how do I prevent this caching?

I tried adding opcache_invalidate(__FILE__, true); but that doesn't change anything.

Any suggestions, please?

Body:
After all it was not a caching issue. The issue was that parts of larger words were also replaced instead of whole words only. That changed the final text and other replacements could not be found anymore.

It looked like I was dealing with a caching issue, but in fact it was my misinterpretation of the functionality of the str_ireplace function.

I changed the code into preg_replace and put it in a 'for' loop. With preg_replace it's possible to replace whole words only.

If anyone has a similar issue, maybe the following code can help:

    if (file_exists($filename)) {

        $json       = file_get_contents($filename);
        $json       = '['.$json.']';

        $srarr      = json_decode($json, true);
        $ori_arr    = array_column($srarr, 'Original');
        $rep_arr    = array_column($srarr, 'Replacement');

        $count = count($ori_arr);

        for ($i = 0; $i < $count; $i++) {
            $text    = preg_replace("/\b$ori_arr[$i]\b/",$rep_arr[$i],$text);
        }
    }


问:
Extracting string between two characters in helm
I am trying to extract all strings between ( and ) from values.yaml in _helper.tpl.

In my _helper.tpl

```<code>{{- define "firstchart.extraction" -}}
{{- regexFindAll "(?<=\()(.*?)(?=\))"  .Values.monitor.url -1 -}}
{{- end -}}
</code>```

my values.yaml file

```<code>monitor:
   url: "(zone-base-url)/google.com/(some-random-text)"
</code>```

so i want to extract zone-base-url and some-random-text. How to do this?

答:
It looks like the regex library is RE2 that does not support lookarounds of any type.
That means, you need to "convert" non-consuming lookarounds into consuming patterns, still keeping the capturing group in between the \( and \) delimiters:

```<code>{{- regexFindAll "\\((.*?)\\)"  .Values.monitor.url -1 -}}
</code>```

Or,

```<code>{{- regexFindAll "\\(([^()]*)\\)"  .Values.monitor.url -1 -}}
</code>```

Details:

\( - a ( char

(.*?) - Group 1: any zero or more chars other than line break chars as few as possible ([^()]* matches zero or more chars other than ( and ) chars)

\) - a ) char

The -1 argument extracts just the Group 1 contents.

A literal backslash in the pattern must be doubled to represent a literal backslash.

Body:
I am trying to extract all strings between ( and ) from values.yaml in _helper.tpl.

In my _helper.tpl

{{- define "firstchart.extraction" -}}
{{- regexFindAll "(?<=\()(.*?)(?=\))"  .Values.monitor.url -1 -}}
{{- end -}}

my values.yaml file

monitor:
   url: "(zone-base-url)/google.com/(some-random-text)"

so i want to extract zone-base-url and some-random-text. How to do this?

Body:
It looks like the regex library is RE2 that does not support lookarounds of any type.
That means, you need to "convert" non-consuming lookarounds into consuming patterns, still keeping the capturing group in between the \( and \) delimiters:

{{- regexFindAll "\\((.*?)\\)"  .Values.monitor.url -1 -}}

Or,

{{- regexFindAll "\\(([^()]*)\\)"  .Values.monitor.url -1 -}}

Details:

\( - a ( char

(.*?) - Group 1: any zero or more chars other than line break chars as few as possible ([^()]* matches zero or more chars other than ( and ) chars)

\) - a ) char

The -1 argument extracts just the Group 1 contents.

A literal backslash in the pattern must be doubled to represent a literal backslash.


问:
How do I remove parentheses and single quotation marks from my output?
How do I remove parentheses and single quotation marks from my output? There is no requirement in my code to show brackets and single quotation marks.

person = "    xx   "
what_he_said = "    abc！"
print(f"{person.split()}曾经说过，“{what_he_said.split()}”")
```
<p>This is the actual output:</p>
```['xx']曾经说过，“['abc！']”
```

I don't want to output the middle brackets and quotation marks.
I'm using Python 3.10, the IDE is pycharm.

答:
Just to print you can try:

Supposing it's necessary to use .split()

```<code>person = "    xx   "
what_he_said = "    abc！"
print(*person.split(),'曾经说过',*what_he_said.split())
</code>```

Body:
How do I remove parentheses and single quotation marks from my output? There is no requirement in my code to show brackets and single quotation marks.

person = "    xx   "
what_he_said = "    abc！"
print(f"{person.split()}曾经说过，“{what_he_said.split()}”")

This is the actual output:

['xx']曾经说过，“['abc！']”

I don't want to output the middle brackets and quotation marks.
I'm using Python 3.10, the IDE is pycharm.

Body:
Just to print you can try:

Supposing it's necessary to use .split()

person = "    xx   "
what_he_said = "    abc！"
print(*person.split(),'曾经说过',*what_he_said.split())