问:
I am getting Expression Expected; Error ':' expected
In the line of categoryName : categories.find((category) => category.id === post.categoryId)?.title

Iam getting error Expression Expected; Error ':' expected

```<code>getPostsWithCategory(){
        return this.getUsers().pipe(mergeMap((posts)=>{
            return this.categoryService.getCategories().pipe(map((categories) =>{
                return posts.map((post) =>{
                  return{
                    ...post,
                    categoryName : categories.find((category) => category.id === post.categoryId)?.title,
                  };
                });
            }));
        }));
      }
</code>```

答:
It seems that you're using a version of Angular < v9, which doesn't support the TypeScript v3.7 or higher (which includes the extremely popular optional chaining feature).

So you can't use the optional chaining feature in your TS files: object?.property.

categoryName: categories.find((category) => category.id === post.categoryId)?.title
```
<p>To resolve this issue, you either need to upgrade your project to Angular ≥ v9, or simply replace the optional chaining operator with the following:</p>
<pre class="lang-js prettyprint-override"><code>// ...
const category = categories.find((category) => category.id === post.categoryId);
return {
  ...post,
  categoryName: category ? category.title : undefined, // OR `category && category.title`
};
</code>```

Body:
In the line of categoryName : categories.find((category) => category.id === post.categoryId)?.title

Iam getting error Expression Expected; Error ':' expected

getPostsWithCategory(){
        return this.getUsers().pipe(mergeMap((posts)=>{
            return this.categoryService.getCategories().pipe(map((categories) =>{
                return posts.map((post) =>{
                  return{
                    ...post,
                    categoryName : categories.find((category) => category.id === post.categoryId)?.title,
                  };
                });
            }));
        }));
      }

Body:
It seems that you're using a version of Angular < v9, which doesn't support the TypeScript v3.7 or higher (which includes the extremely popular optional chaining feature).

So you can't use the optional chaining feature in your TS files: object?.property.

categoryName: categories.find((category) => category.id === post.categoryId)?.title

To resolve this issue, you either need to upgrade your project to Angular ≥ v9, or simply replace the optional chaining operator with the following:

// ...
const category = categories.find((category) => category.id === post.categoryId);
return {
  ...post,
  categoryName: category ? category.title : undefined, // OR `category && category.title`
};


来源: stackexchange

问:
Flutter convert Color to hex string
How can I convert a flutter Color class instance into a hex string?

For example, I would like to convert Colors.blue to what would be '#4286f4'.

Usecase is letting the user choose a color and save it in the database as a hex color.

I have checked related questions and they are for converting the other way around.

答:
This is my favorite way of handling color to string conversions. I use this really simple extension class.</p>
```<code>extension HexColor on Color {
  /// String is in the format "aabbcc" or "ffaabbcc" with an optional leading "#".
  static Color fromHex(String hexString) {
    final buffer = StringBuffer();
    if (hexString.length == 6 || hexString.length == 7) buffer.write('ff');
    buffer.write(hexString.replaceFirst('#', ''));
    return Color(int.parse(buffer.toString(), radix: 16));
  }

  /// Prefixes a hash sign if [leadingHashSign] is set to `true` (default is `true`).
  String toHex({bool leadingHashSign = true}) => '${leadingHashSign ? '#' : ''}'
      '${red.toRadixString(16).padLeft(2, '0')}'
      '${green.toRadixString(16).padLeft(2, '0')}'
      '${blue.toRadixString(16).padLeft(2, '0')}'
      '${alpha.toRadixString(16).padLeft(2, '0')}';
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Flutter convert Color to hex string

Body:
This is my favorite way of handling color to string conversions. I use this really simple extension class.

extension HexColor on Color {
  /// String is in the format "aabbcc" or "ffaabbcc" with an optional leading "#".
  static Color fromHex(String hexString) {
    final buffer = StringBuffer();
    if (hexString.length == 6 || hexString.length == 7) buffer.write('ff');
    buffer.write(hexString.replaceFirst('#', ''));
    return Color(int.parse(buffer.toString(), radix: 16));
  }

  /// Prefixes a hash sign if [leadingHashSign] is set to `true` (default is `true`).
  String toHex({bool leadingHashSign = true}) => '${leadingHashSign ? '#' : ''}'
      '${red.toRadixString(16).padLeft(2, '0')}'
      '${green.toRadixString(16).padLeft(2, '0')}'
      '${blue.toRadixString(16).padLeft(2, '0')}'
      '${alpha.toRadixString(16).padLeft(2, '0')}';
}


问:
Why can't C++ locals captured by reference be accessed through the stack pointer?
I noticed that compilers implement capture by reference by making an array on the stack of pointers to the captured locals, which can be passed to the lambda to access them. That surprised me because the compiler knows where the locals are relative to the stack pointer, so I thought it could just pass the stack pointer. That would make one less indirection in the lambda and save the work of putting the pointers on the stack. I was wondering why the compiler can't do that?

For example, this C++:

```<code>#include <functional>
extern void test(std::function<void()>& f);
int test2(int x, int y)
{
    std::function<void()> f([&]() { x += y; });
    test(f);
    return x;
}
</code>```

generates this assembly on Clang 13 -O3 (comments mine):

```<code>mov     dword ptr [rsp + 8], edi    // put x on the stack
mov     dword ptr [rsp + 12], esi   // put y on the stack
lea     rax, [rsp + 8]
mov     qword ptr [rsp + 16], rax   // put &x on the stack
lea     rax, [rsp + 12]
mov     qword ptr [rsp + 24], rax   // put &y on the stack
mov     qword ptr [rsp + 40], offset std::_Function_handler<void (), test2(int, int)::$_0>::_M_invoke(std::_Any_data const&)
mov     qword ptr [rsp + 32], offset std::_Function_handler<void (), test2(int, int)::$_0>::_M_manager(std::_Any_data&, std::_Any_data const&, std::_Manager_operation)
lea     rdi, [rsp + 16]
call    test(std::function<void ()>&)
</code>```

and similar on GCC and MSVC.

答:
Here is godbolt demo (extended a bit).

I've added testABI to show that parameters to you function are passed by registry.

useTestABI():                        # @useTestABI()
        mov     edi, 3
        mov     esi, 5
        jmp     testABI(int, int)                    # TAILCALL
```

So in test2 starts by creating x and y to create locals on stack so it would be possible to pass them by reference.

After that lambda is created on stack, so addresses of x and y are saved to stack. Also addresses of functions to be invoked when lambda is used (polymorphism without vtable) are added to labda on stack

Now you do not know what test will do with f. It can clone f so in such case f have to be copied from stack to other place. Also on other side when test is compiled compiler do not know what kind of lambda was passed. Creating copy may have side effect or not. So creating a copy must be possible and must be compatible with predefined ABI.

So this shortcut you are describing is possible only when compiler could known content of test. When content of test is not know f must be fully created to make it possible to clone it when needed.

Body:
I noticed that compilers implement capture by reference by making an array on the stack of pointers to the captured locals, which can be passed to the lambda to access them. That surprised me because the compiler knows where the locals are relative to the stack pointer, so I thought it could just pass the stack pointer. That would make one less indirection in the lambda and save the work of putting the pointers on the stack. I was wondering why the compiler can't do that?

For example, this C++:

#include <functional>
extern void test(std::function<void()>& f);
int test2(int x, int y)
{
    std::function<void()> f([&]() { x += y; });
    test(f);
    return x;
}

generates this assembly on Clang 13 -O3 (comments mine):

mov     dword ptr [rsp + 8], edi    // put x on the stack
mov     dword ptr [rsp + 12], esi   // put y on the stack
lea     rax, [rsp + 8]
mov     qword ptr [rsp + 16], rax   // put &x on the stack
lea     rax, [rsp + 12]
mov     qword ptr [rsp + 24], rax   // put &y on the stack
mov     qword ptr [rsp + 40], offset std::_Function_handler<void (), test2(int, int)::$_0>::_M_invoke(std::_Any_data const&)
mov     qword ptr [rsp + 32], offset std::_Function_handler<void (), test2(int, int)::$_0>::_M_manager(std::_Any_data&, std::_Any_data const&, std::_Manager_operation)
lea     rdi, [rsp + 16]
call    test(std::function<void ()>&)

and similar on GCC and MSVC.

Body:
Here is godbolt demo (extended a bit).

I've added testABI to show that parameters to you function are passed by registry.

useTestABI():                        # @useTestABI()
        mov     edi, 3
        mov     esi, 5
        jmp     testABI(int, int)                    # TAILCALL

So in test2 starts by creating x and y to create locals on stack so it would be possible to pass them by reference.

After that lambda is created on stack, so addresses of x and y are saved to stack. Also addresses of functions to be invoked when lambda is used (polymorphism without vtable) are added to labda on stack

Now you do not know what test will do with f. It can clone f so in such case f have to be copied from stack to other place. Also on other side when test is compiled compiler do not know what kind of lambda was passed. Creating copy may have side effect or not. So creating a copy must be possible and must be compatible with predefined ABI.

So this shortcut you are describing is possible only when compiler could known content of test. When content of test is not know f must be fully created to make it possible to clone it when needed.


问:
cocoapods not installing
What does it mean and how can I fix it:</p>

```<code>pod install
/Library/Ruby/Site/2.0.0/rubygems.rb:250:in `find_spec_for_exe': can't find gem cocoapods (>= 0.a) (Gem::GemNotFoundException)
from /Library/Ruby/Site/2.0.0/rubygems.rb:278:in `activate_bin_path'
from /usr/local/bin/pod:22:in `<main>'
</code>```

答:
To relink, run:</p>
```<code>brew unlink cocoapods && brew link cocoapods
</code>```

ContentLicense: CC BY-SA 3.0

Title: cocoapods not installing

Body:
What does it mean and how can I fix it:

pod install
/Library/Ruby/Site/2.0.0/rubygems.rb:250:in `find_spec_for_exe': can't find gem cocoapods (>= 0.a) (Gem::GemNotFoundException)
from /Library/Ruby/Site/2.0.0/rubygems.rb:278:in `activate_bin_path'
from /usr/local/bin/pod:22:in `'

Body:
To relink, run:

brew unlink cocoapods && brew link cocoapods


问:
Problem on performing CRUD operation using Django REST API
Hey I am new to Django Rest Framework.I have recently created REST API name "api/studentapi" using django REST framework in local host. The CRUD operation works perfectly fine in browseable API. But When I try to access the same API from third party python file, I am not able to perform POST operation although I am able to perform GET operation.While performing POST operation the server reponse me as "Unsupported Media Type: /api/studentapi/".I am posting series of code images so that the stuffs gets more clear
The third party python app that I have created to access the "api/studentapi"

The file structure of my project

The model form that I have created

The serializer files that I have created

The urls code

And Finally the view file

答:
Make sure you a passing the content type header during your post and put request, as that's how django_rest_framework understands which parser it will use. The Django rest framework supports content type of form-data,  JSON, x-www-form-urlencoded and multipart out of the box.

If you're sending JSON data add the header to your request:

```<code>Content-Type: application/json
</code>```

If you send form data or file(s) add the header:

```<code>Content-Type: multipart/form-data
</code>```

If you're sending only form data use:

```<code>Content-Type: application/x-form-urlencoded
</code>```

For your code this is how to add the header

r = request.post(
    url=URL,
    data=json_data,
    headers= {
        'Content-Type': 'application/json'
    }
)
```

Body:
Make sure you a passing the content type header during your post and put request, as that's how django_rest_framework understands which parser it will use. The Django rest framework supports content type of form-data,  JSON, x-www-form-urlencoded and multipart out of the box.

If you're sending JSON data add the header to your request:

Content-Type: application/json

If you send form data or file(s) add the header:

Content-Type: multipart/form-data

If you're sending only form data use:

Content-Type: application/x-form-urlencoded

For your code this is how to add the header

r = request.post(
    url=URL,
    data=json_data,
    headers= {
        'Content-Type': 'application/json'
    }
)


问:
TuneError: ('Trials did not complete')
I wrote a program using keras that detects real texts from fake (I used 5000 training data and 10,000 test data), I used Transformer and 'distilbert-base-uncased' model for detection. Now I decide to hyperparameters tuning using the grid search , which I encountered the following error:

```<code>    TuneError                                 Traceback (most recent call last)
    <ipython-input-15-c4a44a2180d8> in <module>()
        156     tune_iris,
        157     verbose=1,
    --> 158     config=hyperparameter_space,
        159    )
        160

    /usr/local/lib/python3.6/dist-packages/ray/tune/tune.py in run(run_or_experiment, name, stop, config, resources_per_trial, num_samples, local_dir, upload_dir, trial_name_creator, loggers, sync_to_cloud, sync_to_driver, checkpoint_freq, checkpoint_at_end, sync_on_checkpoint, keep_checkpoints_num, checkpoint_score_attr, global_checkpoint_period, export_formats, max_failures, fail_fast, restore, search_alg, scheduler, with_server, server_port, verbose, progress_reporter, resume, queue_trials, reuse_actors, trial_executor, raise_on_failed_trial, return_trials, ray_auto_init)
        354     if incomplete_trials:
        355         if raise_on_failed_trial:
    --> 356             raise TuneError("Trials did not complete", incomplete_trials)
        357         else:
        358             logger.error("Trials did not complete: %s", incomplete_trials)

    TuneError: ('Trials did not complete', [tune_iris_83131_00000, tune_iris_83131_00001, tune_iris_83131_00002, tune_iris_83131_00003, tune_iris_83131_00004, tune_iris_83131_00005, tune_iris_83131_00006, tune_iris_83131_00007, tune_iris_83131_00008, tune_iris_83131_00009, tune_iris_83131_00010, tune_iris_83131_00011, tune_iris_83131_00012, tune_iris_83131_00013, tune_iris_83131_00014, tune_iris_83131_00015, tune_iris_83131_00016, tune_iris_83131_00017])
</code>```

The program I wrote is as follows:

```<code>data = pd.concat([train_webtext,train_gen,valid_webtext,valid_gen])

sentences=data['text']
labels=labels1+labels2
len(sentences),len(labels)

DistilBertTokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-cased",do_lower_case=False)

input_ids=[]
attention_masks=[]

for sent in sentences:
    bert_inp=DistilBertTokenizer.encode_plus(sent,add_special_tokens = True,max_length =64,pad_to_max_length = True,return_attention_mask = True)
    input_ids.append(bert_inp['input_ids'])
    attention_masks.append(bert_inp['attention_mask'])

input_ids=np.asarray(input_ids)
attention_masks=np.array(attention_masks)
labels=np.array(labels)

class TuneReporterCallback(keras.callbacks.Callback):
    """Tune Callback for Keras.

    The callback is invoked every epoch.
    """

    def __init__(self, logs={}):
        self.iteration = 0
        super(TuneReporterCallback, self).__init__()

    def on_epoch_end(self, batch, logs={}):
        self.iteration += 1
        tune.report(keras_info=logs, mean_accuracy=logs.get("accuracy"), mean_loss=logs.get("loss"))

def tune_gpt(config):
  train_inp,val_inp,train_label,val_label,train_mask,val_mask=train_test_split(input_ids,labels,attention_masks,test_size=0.6666666666666666)
  DistilBert_model = TFDistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased',num_labels=2)
  loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
  metric = tf.keras.metrics.SparseCategoricalAccuracy('accuracy')
  optimizer = tf.keras.optimizers.Adam(learning_rate=config["learning_rate"],epsilon=1e-08)
  DistilBert_model.compile(loss=loss,optimizer=optimizer,metrics=[metric])
  checkpoint_callback = [tf.keras.callbacks.ModelCheckpoint( "DistilBert_model.h5",monitor='val_loss',mode='min',save_best_only=True)]
  callbacks = [checkpoint_callback, TuneReporterCallback()]
  history=DistilBert_model.fit([train_inp,train_mask],train_label,batch_size=config["batch_size"],epochs=config["epochs"],validation_data=([val_inp,val_mask],val_label),callbacks=callbacks)
  assert len(inspect.getargspec(tune_gpt).args) == 1, "The `tune_gpt` function needs to take in the arg `config`."

hyperparameter_space  ={
       "batch_size": tune.grid_search([16, 32]),
       "learning_rate": tune.grid_search([2e-5, 3e-5, 5e-5]),
       "epochs": tune.grid_search([2, 3, 4])
    }

analysis = tune.run(
    tune_gpt,
    verbose=1,
    config=hyperparameter_space,
   )
</code>```

答:
It seems your code has some errors, but the detailed error messages do not appear due to the verbose option.

Please change the verbose option

```<code>verbose=1
</code>```

to

```<code>verbose=3
</code>```

to see the detailed error.

( Verbosity mode. 0 = silent, 1 = only status updates, 2 = status and brief trial results, 3 = status and detailed trial results. Defaults to 3.)

Title: TuneError: ('Trials did not complete')

Body:
I wrote a program using keras that detects real texts from fake (I used 5000 training data and 10,000 test data), I used Transformer and 'distilbert-base-uncased' model for detection. Now I decide to hyperparameters tuning using the grid search , which I encountered the following error:

    TuneError                                 Traceback (most recent call last)
    <ipython-input-15-c4a44a2180d8> in <module>()
        156     tune_iris,
        157     verbose=1,
    --> 158     config=hyperparameter_space,
        159    )
        160

    /usr/local/lib/python3.6/dist-packages/ray/tune/tune.py in run(run_or_experiment, name, stop, config, resources_per_trial, num_samples, local_dir, upload_dir, trial_name_creator, loggers, sync_to_cloud, sync_to_driver, checkpoint_freq, checkpoint_at_end, sync_on_checkpoint, keep_checkpoints_num, checkpoint_score_attr, global_checkpoint_period, export_formats, max_failures, fail_fast, restore, search_alg, scheduler, with_server, server_port, verbose, progress_reporter, resume, queue_trials, reuse_actors, trial_executor, raise_on_failed_trial, return_trials, ray_auto_init)
        354     if incomplete_trials:
        355         if raise_on_failed_trial:
    --> 356             raise TuneError("Trials did not complete", incomplete_trials)
        357         else:
        358             logger.error("Trials did not complete: %s", incomplete_trials)

    TuneError: ('Trials did not complete', [tune_iris_83131_00000, tune_iris_83131_00001, tune_iris_83131_00002, tune_iris_83131_00003, tune_iris_83131_00004, tune_iris_83131_00005, tune_iris_83131_00006, tune_iris_83131_00007, tune_iris_83131_00008, tune_iris_83131_00009, tune_iris_83131_00010, tune_iris_83131_00011, tune_iris_83131_00012, tune_iris_83131_00013, tune_iris_83131_00014, tune_iris_83131_00015, tune_iris_83131_00016, tune_iris_83131_00017])

The program I wrote is as follows:

data = pd.concat([train_webtext,train_gen,valid_webtext,valid_gen])

sentences=data['text']
labels=labels1+labels2
len(sentences),len(labels)

DistilBertTokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-cased",do_lower_case=False)

input_ids=[]
attention_masks=[]

for sent in sentences:
    bert_inp=DistilBertTokenizer.encode_plus(sent,add_special_tokens = True,max_length =64,pad_to_max_length = True,return_attention_mask = True)
    input_ids.append(bert_inp['input_ids'])
    attention_masks.append(bert_inp['attention_mask'])

input_ids=np.asarray(input_ids)
attention_masks=np.array(attention_masks)
labels=np.array(labels)

class TuneReporterCallback(keras.callbacks.Callback):
    """Tune Callback for Keras.

    The callback is invoked every epoch.
    """

    def __init__(self, logs={}):
        self.iteration = 0
        super(TuneReporterCallback, self).__init__()

    def on_epoch_end(self, batch, logs={}):
        self.iteration += 1
        tune.report(keras_info=logs, mean_accuracy=logs.get("accuracy"), mean_loss=logs.get("loss"))

def tune_gpt(config):
  train_inp,val_inp,train_label,val_label,train_mask,val_mask=train_test_split(input_ids,labels,attention_masks,test_size=0.6666666666666666)
  DistilBert_model = TFDistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased',num_labels=2)
  loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
  metric = tf.keras.metrics.SparseCategoricalAccuracy('accuracy')
  optimizer = tf.keras.optimizers.Adam(learning_rate=config["learning_rate"],epsilon=1e-08)
  DistilBert_model.compile(loss=loss,optimizer=optimizer,metrics=[metric])
  checkpoint_callback = [tf.keras.callbacks.ModelCheckpoint( "DistilBert_model.h5",monitor='val_loss',mode='min',save_best_only=True)]
  callbacks = [checkpoint_callback, TuneReporterCallback()]
  history=DistilBert_model.fit([train_inp,train_mask],train_label,batch_size=config["batch_size"],epochs=config["epochs"],validation_data=([val_inp,val_mask],val_label),callbacks=callbacks)
  assert len(inspect.getargspec(tune_gpt).args) == 1, "The `tune_gpt` function needs to take in the arg `config`."

hyperparameter_space  ={
       "batch_size": tune.grid_search([16, 32]),
       "learning_rate": tune.grid_search([2e-5, 3e-5, 5e-5]),
       "epochs": tune.grid_search([2, 3, 4])
    }

analysis = tune.run(
    tune_gpt,
    verbose=1,
    config=hyperparameter_space,
   )

Body:
It seems your code has some errors, but the detailed error messages do not appear due to the verbose option.

Please change the verbose option

verbose=1

to

verbose=3

to see the detailed error.

( Verbosity mode. 0 = silent, 1 = only status updates, 2 = status and brief trial results, 3 = status and detailed trial results. Defaults to 3.)


问:
Why is memset() incorrectly initializing int?
Why is the output of the following program 84215045?

```<code>int grid[110];
int main()
{
    memset(grid, 5, 100 * sizeof(int));
    printf("%d", grid[0]);
    return 0;
}
</code>```

答:
Don't use memset.

You set each byte [] of the memory to the value of 5.  Each int is 4 bytes long [5][5][5][5], which the compiler correctly interprets as 5*256*256*256 + 5*256*256 + 5*256 + 5 = 84215045.  Instead, use a for loop, which also doesn't require sizeof().  In general, sizeof() means you're doing something the hard way.

```<code>for(int i=0; i<110; ++i)
    grid[i] = 5;
</code>```

Body:
Why is the output of the following program 84215045?

int grid[110];
int main()
{
    memset(grid, 5, 100 * sizeof(int));
    printf("%d", grid[0]);
    return 0;
}

Body:
Don't use memset.

You set each byte [] of the memory to the value of 5.  Each int is 4 bytes long [5][5][5][5], which the compiler correctly interprets as 5*256*256*256 + 5*256*256 + 5*256 + 5 = 84215045.  Instead, use a for loop, which also doesn't require sizeof().  In general, sizeof() means you're doing something the hard way.

for(int i=0; i<110; ++i)
    grid[i] = 5;


问:
Check col1 if duplicate then check col2 if distinct
Hey guys I've been struggling to get a simple query done in SnowFlake.
A sample of the data is explained below,

Number
ID

2559
23

2559
33

2559
55

2550
89

2499
14

2499
14

Based on the table above I would like to create a column that checks if (column Number) have duplicated values if yes; then check (column ID) if the values associated with that Number were duplicated or distinct. If values were duplicated then return 0 if values were distinct then return 1.

The desired outcome is as follows,

Number
ID
Check

2559
23
1

2559
33
1

2559
55
1

2550
89
0

2499
14
0

2499
14
0

and the last outcome should be on the Number column level (group by) and would be like the following table,

Number
Check

2559
1

2550
0

2499
0

Any suggestions are appreciated.

Edited tables

The scenario has changed based on new requirements

The original table have two IDs (ID1 and ID2) and those IDs must be linked to two different tables T-ID1 and T-ID2.

Number
ID1
ID2

2559
23
null

2559
33
null

2559
55
null

2550
89
null

2499
14
null

2499
14
null

2498
null
14

2498
null
50

2498
null
null

So the idea is if Number has duplicated IDs (in ID1 or ID2) then return 1, if Number has unique ID (in ID1 or ID2) then return ID1 or ID2. if Number have null values for ID1 and ID2 then ignore the entire row.

This is the query I am using - everything works based on solution provided below, but I am getting nulls along with ID values.

ID1 is linked to Supplier_ID_Ekuep and ID2 is linked to Supplier_ID_Qava.

```<code>select wbd.WAYBILL_ID, sup.WAYBILL_NO,
       sup.Supplier_ID_Qava, supq.Supplier_Qava, supq.Supllier_City_Qava, supq.Supplier_Qava_Add,
       sup.Supplier_ID_Ekuep, supc.Supplier_Ekuep, supc.Supllier_City_Ekuep, supc.Supplier_Ekuep_Add
from WAYBILL_PRODUCTS wbd
left join (select wb.WAYBILL_ID, ow.WAYBILL_NO,
       case when mult.multi_supp_qava = 1 then '1'
            when mult.multi_supp_qava = 0 then op.ID_Supplier_Qava
            else null end as Supplier_ID_Qava,
       case when mult.multi_supp_ekuep = 1 then '1'
            when mult.multi_supp_ekuep = 0 then op.ID_Supplier_Ekuep
            else null end as Supplier_ID_Ekuep
from WAYBILL_PRODUCTS wb
left join (select ID, ORDER_ID, WAYBILL_NO from ORDER_WAYBILLS) ow on wb.WAYBILL_ID = ow.id
left join (select opr.ID_ORDER, opr.ID_PRODUCT, ss.ID_Supplier_Ekuep, ss.ID_Supplier_Qava
          from ORDER_PRODUCTS opr
left join (select s.id, supc.*, supq.*
          from SUPPLIERS s
left join (select ID_SUPPLIER as ID_Supplier_Ekuep
from EKUEP_KSA_EKUEP_STAGING.PS_SUPPLIER where USED_SUPPLIER_ID is null) supc on supc.ID_Supplier_Ekuep = s.ID_SUPPLIER and s.STORE_ID = 1
left join (select ID_SUPPLIER as ID_Supplier_Qava
from QAVASHOP_KSA_QAVAISH_MAINSHOP.PS_SUPPLIER where USED_SUPPLIER_ID is null) supq on supq.ID_Supplier_Qava = s.ID_SUPPLIER and s.STORE_ID = 2) ss on opr.SUPPLIER_ID = ss.ID
group by opr.ID_ORDER, opr.ID_PRODUCT, ss.ID_Supplier_Ekuep, ss.ID_Supplier_Qava) op on op.ID_PRODUCT = wb.PRODUCT_ID and op.ID_ORDER = ow.ORDER_ID
------------------------------------------------------------------------------------------------------------------------
left join (select wb.WAYBILL_ID, ow.WAYBILL_NO,
       (count(distinct op.ID_Supplier_Qava) > 1)::int as multi_supp_qava,
       (count(distinct op.ID_Supplier_Ekuep) > 1)::int as multi_supp_ekuep
from WAYBILL_PRODUCTS wb
left join (select ID, ORDER_ID, WAYBILL_NO from ORDER_WAYBILLS) ow on wb.WAYBILL_ID = ow.id
left join (select opr.ID_ORDER, opr.ID_PRODUCT, ss.ID_Supplier_Ekuep, ss.ID_Supplier_Qava
          from ORDER_PRODUCTS opr
left join (select s.id, supc.ID_Supplier_Ekuep, supq.ID_Supplier_Qava
          from SUPPLIERS s
left join (select ID_SUPPLIER as ID_Supplier_Ekuep
from EKUEP_KSA_EKUEP_STAGING.PS_SUPPLIER where USED_SUPPLIER_ID is null) supc on supc.ID_Supplier_Ekuep = s.ID_SUPPLIER and s.STORE_ID = 1
left join (select ID_SUPPLIER as ID_Supplier_Qava
from QAVASHOP_KSA_QAVAISH_MAINSHOP.PS_SUPPLIER where USED_SUPPLIER_ID is null) supq on supq.ID_Supplier_Qava = s.ID_SUPPLIER and s.STORE_ID = 2
    ) ss on opr.SUPPLIER_ID = ss.ID
group by opr.ID_ORDER, opr.ID_PRODUCT, ss.ID_Supplier_Ekuep, ss.ID_Supplier_Qava) op on op.ID_PRODUCT = wb.PRODUCT_ID and op.ID_ORDER = ow.ORDER_ID
where _FIVETRAN_DELETED = 0
group by wb.WAYBILL_ID, ow.WAYBILL_NO) mult on mult.WAYBILL_NO = ow.WAYBILL_NO
------------------------------------------------------------------------------------------------------------------------
group by wb.WAYBILL_ID, ow.WAYBILL_NO, mult.multi_supp_qava, mult.multi_supp_ekuep, op.ID_Supplier_Qava, op.ID_Supplier_Ekuep) sup on wbd.WAYBILL_ID = sup.WAYBILL_ID

left join
(select ps.ID_SUPPLIER                  as ID_Supplier_Qava,
        ps.name                         as Supplier_Qava,
        listagg(distinct pa.CITY, ', ') as Supllier_City_Qava,
        ps.DATE_ADD                     as Supplier_Qava_Add
from QAVASHOP_KSA_QAVAISH_MAINSHOP.PS_SUPPLIER ps
left join (select * from QAVASHOP_KSA_QAVAISH_MAINSHOP.PS_ADDRESS) pa on pa.ID_SUPPLIER = ps.ID_SUPPLIER and pa._FIVETRAN_DELETED = 0
where ps.USED_SUPPLIER_ID is null and ps._FIVETRAN_DELETED = 0
group by ID_Supplier_Qava, Supplier_Qava, Supplier_Qava_Add) supq on supq.ID_Supplier_Qava = sup.Supplier_ID_Qava

left join
(select ps.ID_SUPPLIER                  as ID_Supplier_Ekuep,
        ps.name                         as Supplier_Ekuep,
        listagg(distinct pa.CITY, ', ') as Supllier_City_Ekuep,
        ps.DATE_ADD                     as Supplier_Ekuep_Add
from EKUEP_KSA_EKUEP_STAGING.PS_SUPPLIER ps
left join (select * from EKUEP_KSA_EKUEP_STAGING.PS_ADDRESS) pa on pa.ID_SUPPLIER = ps.ID_SUPPLIER and pa._FIVETRAN_DELETED = 0
where ps.USED_SUPPLIER_ID is null and ps._FIVETRAN_DELETED = 0
group by ID_Supplier_Ekuep, Supplier_Ekuep, Supplier_Ekuep_Add) supc on supc.ID_Supplier_Ekuep = sup.Supplier_ID_Ekuep
where _FIVETRAN_DELETED = 0
group by wbd.WAYBILL_ID, sup.WAYBILL_NO,
       sup.Supplier_ID_Qava, supq.Supplier_Qava, supq.Supllier_City_Qava, supq.Supplier_Qava_Add,
       sup.Supplier_ID_Ekuep, supc.Supplier_Ekuep, supc.Supllier_City_Ekuep, supc.Supplier_Ekuep_Add
</code>```

The output I am getting for Waybill_No = 43265104 is as follows, I just want to get rid of the null row.

答:
```<code>WITH data(num, id) AS (
    SELECT * FROM VALUES
      (2559,    23),
      (2559,    33),
      (2559,    55),
      (2550,    89),
      (2499,    14),
      (2499,    14)
)
SELECT
    num,
    id,
    count(*) over(partition by num) as num_dup,
    count(distinct id)over(partition by num) as id_dup,
    iff(num_dup > 1 AND num_dup = id_dup, 1, 0) as "check"
FROM data;
</code>```

gives:

NUM
ID
NUM_DUP
ID_DUP
check

2559
23
3
3
1

2559
33
3
3
1

2559
55
3
3
1

2550
89
1
1
0

2499
14
2
1
0

2499
14
2
1
0

Extra Data:

```<code>WITH data(num, id) AS (
    SELECT * FROM VALUES
      (2559,    23),
      (2559,    33),
      (2559,    33),
      (2559,    55),
      (2550,    89),
      (2499,    14),
      (2499,    14)
)
SELECT
    num,
    id,
    count(*) over(partition by num) as num_dup,
    count(distinct id)over(partition by num) as id_dup,
    iff(num_dup > 1 AND num_dup = id_dup, 1, 0) as "check"
FROM data;
</code>```

if we make 2559 have two 33's then it show change to 0/false

NUM
ID
NUM_DUP
ID_DUP
check

2559
23
4
3
0

2559
33
4
3
0

2559
33
4
3
0

2559
55
4
3
0

2550
89
1
1
0

2499
14
2
1
0

2499
14
2
1
0

Last Step:

```<code>WITH data(num, id) AS (
    SELECT * FROM VALUES
      (2559,    23),
      (2559,    33),
      (2559,    55),
      (2550,    89),
      (2499,    14),
      (2499,    14)
)
SELECT
    num,
    iff(count(*) > 1 AND count(*) = count(distinct id), 1, 0) as output
FROM data
GROUP BY 1;
</code>```

gives:

NUM
OUTPUT

2559
1

2550
0

2499
0

Body:
Hey guys I've been struggling to get a simple query done in SnowFlake.
A sample of the data is explained below,

Number
ID

2559
23

2559
33

2559
55

2550
89

2499
14

2499
14

Based on the table above I would like to create a column that checks if (column Number) have duplicated values if yes; then check (column ID) if the values associated with that Number were duplicated or distinct. If values were duplicated then return 0 if values were distinct then return 1.

The desired outcome is as follows,

Number
ID
Check

2559
23
1

2559
33
1

2559
55
1

2550
89
0

2499
14
0

2499
14
0

and the last outcome should be on the Number column level (group by) and would be like the following table,

Number
Check

2559
1

2550
0

2499
0

Any suggestions are appreciated.

Edited tables

The scenario has changed based on new requirements

The original table have two IDs (ID1 and ID2) and those IDs must be linked to two different tables T-ID1 and T-ID2.

Number
ID1
ID2

2559
23
null

2559
33
null

2559
55
null

2550
89
null

2499
14
null

2499
14
null

2498
null
14

2498
null
50

2498
null
null

So the idea is if Number has duplicated IDs (in ID1 or ID2) then return 1, if Number has unique ID (in ID1 or ID2) then return ID1 or ID2. if Number have null values for ID1 and ID2 then ignore the entire row.

This is the query I am using - everything works based on solution provided below, but I am getting nulls along with ID values.

ID1 is linked to Supplier_ID_Ekuep and ID2 is linked to Supplier_ID_Qava.

select wbd.WAYBILL_ID, sup.WAYBILL_NO,
       sup.Supplier_ID_Qava, supq.Supplier_Qava, supq.Supllier_City_Qava, supq.Supplier_Qava_Add,
       sup.Supplier_ID_Ekuep, supc.Supplier_Ekuep, supc.Supllier_City_Ekuep, supc.Supplier_Ekuep_Add
from WAYBILL_PRODUCTS wbd
left join (select wb.WAYBILL_ID, ow.WAYBILL_NO,
       case when mult.multi_supp_qava = 1 then '1'
            when mult.multi_supp_qava = 0 then op.ID_Supplier_Qava
            else null end as Supplier_ID_Qava,
       case when mult.multi_supp_ekuep = 1 then '1'
            when mult.multi_supp_ekuep = 0 then op.ID_Supplier_Ekuep
            else null end as Supplier_ID_Ekuep
from WAYBILL_PRODUCTS wb
left join (select ID, ORDER_ID, WAYBILL_NO from ORDER_WAYBILLS) ow on wb.WAYBILL_ID = ow.id
left join (select opr.ID_ORDER, opr.ID_PRODUCT, ss.ID_Supplier_Ekuep, ss.ID_Supplier_Qava
          from ORDER_PRODUCTS opr
left join (select s.id, supc.*, supq.*
          from SUPPLIERS s
left join (select ID_SUPPLIER as ID_Supplier_Ekuep
from EKUEP_KSA_EKUEP_STAGING.PS_SUPPLIER where USED_SUPPLIER_ID is null) supc on supc.ID_Supplier_Ekuep = s.ID_SUPPLIER and s.STORE_ID = 1
left join (select ID_SUPPLIER as ID_Supplier_Qava
from QAVASHOP_KSA_QAVAISH_MAINSHOP.PS_SUPPLIER where USED_SUPPLIER_ID is null) supq on supq.ID_Supplier_Qava = s.ID_SUPPLIER and s.STORE_ID = 2) ss on opr.SUPPLIER_ID = ss.ID
group by opr.ID_ORDER, opr.ID_PRODUCT, ss.ID_Supplier_Ekuep, ss.ID_Supplier_Qava) op on op.ID_PRODUCT = wb.PRODUCT_ID and op.ID_ORDER = ow.ORDER_ID
------------------------------------------------------------------------------------------------------------------------
left join (select wb.WAYBILL_ID, ow.WAYBILL_NO,
       (count(distinct op.ID_Supplier_Qava) > 1)::int as multi_supp_qava,
       (count(distinct op.ID_Supplier_Ekuep) > 1)::int as multi_supp_ekuep
from WAYBILL_PRODUCTS wb
left join (select ID, ORDER_ID, WAYBILL_NO from ORDER_WAYBILLS) ow on wb.WAYBILL_ID = ow.id
left join (select opr.ID_ORDER, opr.ID_PRODUCT, ss.ID_Supplier_Ekuep, ss.ID_Supplier_Qava
          from ORDER_PRODUCTS opr
left join (select s.id, supc.ID_Supplier_Ekuep, supq.ID_Supplier_Qava
          from SUPPLIERS s
left join (select ID_SUPPLIER as ID_Supplier_Ekuep
from EKUEP_KSA_EKUEP_STAGING.PS_SUPPLIER where USED_SUPPLIER_ID is null) supc on supc.ID_Supplier_Ekuep = s.ID_SUPPLIER and s.STORE_ID = 1
left join (select ID_SUPPLIER as ID_Supplier_Qava
from QAVASHOP_KSA_QAVAISH_MAINSHOP.PS_SUPPLIER where USED_SUPPLIER_ID is null) supq on supq.ID_Supplier_Qava = s.ID_SUPPLIER and s.STORE_ID = 2
    ) ss on opr.SUPPLIER_ID = ss.ID
group by opr.ID_ORDER, opr.ID_PRODUCT, ss.ID_Supplier_Ekuep, ss.ID_Supplier_Qava) op on op.ID_PRODUCT = wb.PRODUCT_ID and op.ID_ORDER = ow.ORDER_ID
where _FIVETRAN_DELETED = 0
group by wb.WAYBILL_ID, ow.WAYBILL_NO) mult on mult.WAYBILL_NO = ow.WAYBILL_NO
------------------------------------------------------------------------------------------------------------------------
group by wb.WAYBILL_ID, ow.WAYBILL_NO, mult.multi_supp_qava, mult.multi_supp_ekuep, op.ID_Supplier_Qava, op.ID_Supplier_Ekuep) sup on wbd.WAYBILL_ID = sup.WAYBILL_ID

left join
(select ps.ID_SUPPLIER                  as ID_Supplier_Qava,
        ps.name                         as Supplier_Qava,
        listagg(distinct pa.CITY, ', ') as Supllier_City_Qava,
        ps.DATE_ADD                     as Supplier_Qava_Add
from QAVASHOP_KSA_QAVAISH_MAINSHOP.PS_SUPPLIER ps
left join (select * from QAVASHOP_KSA_QAVAISH_MAINSHOP.PS_ADDRESS) pa on pa.ID_SUPPLIER = ps.ID_SUPPLIER and pa._FIVETRAN_DELETED = 0
where ps.USED_SUPPLIER_ID is null and ps._FIVETRAN_DELETED = 0
group by ID_Supplier_Qava, Supplier_Qava, Supplier_Qava_Add) supq on supq.ID_Supplier_Qava = sup.Supplier_ID_Qava

left join
(select ps.ID_SUPPLIER                  as ID_Supplier_Ekuep,
        ps.name                         as Supplier_Ekuep,
        listagg(distinct pa.CITY, ', ') as Supllier_City_Ekuep,
        ps.DATE_ADD                     as Supplier_Ekuep_Add
from EKUEP_KSA_EKUEP_STAGING.PS_SUPPLIER ps
left join (select * from EKUEP_KSA_EKUEP_STAGING.PS_ADDRESS) pa on pa.ID_SUPPLIER = ps.ID_SUPPLIER and pa._FIVETRAN_DELETED = 0
where ps.USED_SUPPLIER_ID is null and ps._FIVETRAN_DELETED = 0
group by ID_Supplier_Ekuep, Supplier_Ekuep, Supplier_Ekuep_Add) supc on supc.ID_Supplier_Ekuep = sup.Supplier_ID_Ekuep
where _FIVETRAN_DELETED = 0
group by wbd.WAYBILL_ID, sup.WAYBILL_NO,
       sup.Supplier_ID_Qava, supq.Supplier_Qava, supq.Supllier_City_Qava, supq.Supplier_Qava_Add,
       sup.Supplier_ID_Ekuep, supc.Supplier_Ekuep, supc.Supllier_City_Ekuep, supc.Supplier_Ekuep_Add

The output I am getting for Waybill_No = 43265104 is as follows, I just want to get rid of the null row.

Body:
WITH data(num, id) AS (
    SELECT * FROM VALUES
      (2559,    23),
      (2559,    33),
      (2559,    55),
      (2550,    89),
      (2499,    14),
      (2499,    14)
)
SELECT
    num,
    id,
    count(*) over(partition by num) as num_dup,
    count(distinct id)over(partition by num) as id_dup,
    iff(num_dup > 1 AND num_dup = id_dup, 1, 0) as "check"
FROM data;

gives:

NUM
ID
NUM_DUP
ID_DUP
check

2559
23
3
3
1

2559
33
3
3
1

2559
55
3
3
1

2550
89
1
1
0

2499
14
2
1
0

2499
14
2
1
0

Extra Data:

WITH data(num, id) AS (
    SELECT * FROM VALUES
      (2559,    23),
      (2559,    33),
      (2559,    33),
      (2559,    55),
      (2550,    89),
      (2499,    14),
      (2499,    14)
)
SELECT
    num,
    id,
    count(*) over(partition by num) as num_dup,
    count(distinct id)over(partition by num) as id_dup,
    iff(num_dup > 1 AND num_dup = id_dup, 1, 0) as "check"
FROM data;

if we make 2559 have two 33's then it show change to 0/false

NUM
ID
NUM_DUP
ID_DUP
check

2559
23
4
3
0

2559
33
4
3
0

2559
33
4
3
0

2559
55
4
3
0

2550
89
1
1
0

2499
14
2
1
0

2499
14
2
1
0

Last Step:

WITH data(num, id) AS (
    SELECT * FROM VALUES
      (2559,    23),
      (2559,    33),
      (2559,    55),
      (2550,    89),
      (2499,    14),
      (2499,    14)
)
SELECT
    num,
    iff(count(*) > 1 AND count(*) = count(distinct id), 1, 0) as output
FROM data
GROUP BY 1;

gives:

NUM
OUTPUT

2559
1

2550
0

2499
0


问:
How to send an image in Java to a Python server that uses requests?
I have 2 python scripts, 1 is the server itself and the other for POST-ing and image.
Server.py ->

```<code>app = Flask(__name__)

@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "POST":
        file = request.files.get('file')
        if file is None or file.filename == "":
            return jsonify({"error": "nothing inside file"})

        try:
            image_bytes = file.read()
            pillow_img = imageio.imread(image_bytes, pilmode='RGB')
            start_time = time.time()
            result = tfnet.return_predict(pillow_img)[0]
            end_time = time.time()
            result['response_time'] = end_time - start_time
            return jsonify({'Output': str(result)})
        except Exception as e:
            return jsonify({"error": str(e)})

    return "OK"
</code>```

I'm trying to re-create the test.py into java, I'm able to POST to the server and get 200 response. But I'm having trouble sending and image to the server.py thats running.
I'm breaking this problem into 2 parts: 1) Try POST a json for my server.py to recognize it as some JSON instead of None. 2) Try encode an image and POST it to server.py to recognize and send a response back.
I'm not able to do both the steps.
Test.py ->

```<code>import requests

resp = requests.post("http://xxxxxxxxxxxxxx:8080/",
                    files={'file': open('D://Jupyter//GCP Deploy//darkflow-master//1.jpg', 'rb')})

print(resp.json())
</code>```

and the respective java file that doesnt send the image but a json.

```<code>public class HttpURLConnectionExample {
public static void main(String[] args) throws IOException {
    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
        HttpPost httpPost = new HttpPost("http://xxxxxxxxxxxxxx:8080/");
        String json = "{\r\n" +
            "  \"file\": \"string value\"\r\n" +
            "}";

        StringEntity stringEntity = new StringEntity(json);
        httpPost.setEntity(stringEntity);
        System.out.println("Executing request " + httpPost.getRequestLine());

        // Create a custom response handler
        ResponseHandler < String > responseHandler = response -> {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
        };
        String responseBody = httpclient.execute(httpPost, responseHandler);
        System.out.println("----------------------------------------");
        System.out.println(responseBody);
    }
}
</code>```

}

The only success I'm having from this is that the server recognizes the POST request, but doesnt go into the try block, the file in the Server.py is None.

答:
```<code>file = request.files.get('file')
</code>```

This line in Server.py was changes to request.get_data() to get the raw data being transfered. However, the problem now is with the bytes file of image. Java POST request of bytes image is of varying length when run multiple times, Python POST request has fixed bytes of image when run multiple times.

eg: Python POST request of image => 474525 length (fixed on every run)
Java POST request of image => 474741, 474744, 474740 length (Varying on every run)

Body:
I have 2 python scripts, 1 is the server itself and the other for POST-ing and image.
Server.py ->

app = Flask(__name__)

@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "POST":
        file = request.files.get('file')
        if file is None or file.filename == "":
            return jsonify({"error": "nothing inside file"})

        try:
            image_bytes = file.read()
            pillow_img = imageio.imread(image_bytes, pilmode='RGB')
            start_time = time.time()
            result = tfnet.return_predict(pillow_img)[0]
            end_time = time.time()
            result['response_time'] = end_time - start_time
            return jsonify({'Output': str(result)})
        except Exception as e:
            return jsonify({"error": str(e)})

    return "OK"

I'm trying to re-create the test.py into java, I'm able to POST to the server and get 200 response. But I'm having trouble sending and image to the server.py thats running.
I'm breaking this problem into 2 parts: 1) Try POST a json for my server.py to recognize it as some JSON instead of None. 2) Try encode an image and POST it to server.py to recognize and send a response back.
I'm not able to do both the steps.
Test.py ->

import requests

resp = requests.post("http://xxxxxxxxxxxxxx:8080/",
                    files={'file': open('D://Jupyter//GCP Deploy//darkflow-master//1.jpg', 'rb')})

print(resp.json())

and the respective java file that doesnt send the image but a json.

public class HttpURLConnectionExample {
public static void main(String[] args) throws IOException {
    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
        HttpPost httpPost = new HttpPost("http://xxxxxxxxxxxxxx:8080/");
        String json = "{\r\n" +
            "  \"file\": \"string value\"\r\n" +
            "}";

        StringEntity stringEntity = new StringEntity(json);
        httpPost.setEntity(stringEntity);
        System.out.println("Executing request " + httpPost.getRequestLine());

        // Create a custom response handler
        ResponseHandler < String > responseHandler = response -> {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
        };
        String responseBody = httpclient.execute(httpPost, responseHandler);
        System.out.println("----------------------------------------");
        System.out.println(responseBody);
    }
}

}

The only success I'm having from this is that the server recognizes the POST request, but doesnt go into the try block, the file in the Server.py is None.

Body:
file = request.files.get('file')

This line in Server.py was changes to request.get_data() to get the raw data being transfered. However, the problem now is with the bytes file of image. Java POST request of bytes image is of varying length when run multiple times, Python POST request has fixed bytes of image when run multiple times.

eg: Python POST request of image => 474525 length (fixed on every run)
Java POST request of image => 474741, 474744, 474740 length (Varying on every run)


问:
How do i animate the opacity of an element when scrolling is selected?
I'm at the very beginning of learning JS, right now what's bugging me is I want to animate the opacity of a div when scrolling is detected
I have 2 options from what i've found online:

```<code>window.addEventListener('scroll',function());
</code>```

or

```<code>window.onscroll()=function();
</code>```

Using the first variant, and the console, I see it is detecting the scrolling but here comes my trouble.

Let:

```<code>let loadingscreen=document.getElementsByTagName('div')[3];
loadingscreen.style.opacity="0";
</code>```

Why won't this work?

```<code>window.addEventListener('scroll',()=>{
console.log("!"); //detecting the scroll in the console
setInterval(function(){loadingscreen.style.opacity+=".1"},100);});`
</code>```

The opacity only changes once, i believe it is from 0 to 0.1

Is it that my opacity goes from 0 to 0.1 to 0.11 to 0.111? Tho i cant understand why that would be.
Thank you for taking your time to read this, any response is apreciated!!

I know the code doesn't look that tidy, i promise it is better in my vsc, im having a little trouble with stackoverflow

答:
This is because you are adding a string to a string, not a number to another number. If you want to add 0.1 of opacity when scrolling is detected, you would have to parse the opacity value with parseInt(loadingscreen.style.opacity), then add 0.1 and then apply it to loadingscreen.style.opacity.

However:

scroll events can fire at a high rate

see https://developer.mozilla.org/en-US/docs/Web/API/Document/scroll_event

So, if you scroll one time, your event-handler will maybe fire 20 times, and everytime there is an eventlistener added. So, first you should add { once: true } to your eventListener options.

Secondly, you are adding more opacity every 100 milliseconds.

If you want a nice animation, you should add a class and animate the opacity in CSS.

Consider the following example:

let loadingscreen = document.querySelector(".loadingscreen");

window.addEventListener("scroll", () => {
  loadingscreen.classList.add("scrolled");
}, {
    once: true
}
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  height: 200vh;
}

div.loadingscreen {
  margin-top: 25%;
  height: 50%;
  width: 100%;
  background: red;
  opacity: 0;
}

div.loadingscreen.scrolled {
  opacity: 1;
  transition: opacity 1s linear;
}</code>```

```

Body:
I'm at the very beginning of learning JS, right now what's bugging me is I want to animate the opacity of a div when scrolling is detected
I have 2 options from what i've found online:

window.addEventListener('scroll',function());

or

window.onscroll()=function();

Using the first variant, and the console, I see it is detecting the scrolling but here comes my trouble.

Let:

let loadingscreen=document.getElementsByTagName('div')[3];
loadingscreen.style.opacity="0";

Why won't this work?

window.addEventListener('scroll',()=>{
console.log("!"); //detecting the scroll in the console
setInterval(function(){loadingscreen.style.opacity+=".1"},100);});`

The opacity only changes once, i believe it is from 0 to 0.1

Is it that my opacity goes from 0 to 0.1 to 0.11 to 0.111? Tho i cant understand why that would be.
Thank you for taking your time to read this, any response is apreciated!!

I know the code doesn't look that tidy, i promise it is better in my vsc, im having a little trouble with stackoverflow

Body:
This is because you are adding a string to a string, not a number to another number. If you want to add 0.1 of opacity when scrolling is detected, you would have to parse the opacity value with parseInt(loadingscreen.style.opacity), then add 0.1 and then apply it to loadingscreen.style.opacity.

However:

scroll events can fire at a high rate

see https://developer.mozilla.org/en-US/docs/Web/API/Document/scroll_event

So, if you scroll one time, your event-handler will maybe fire 20 times, and everytime there is an eventlistener added. So, first you should add { once: true } to your eventListener options.

Secondly, you are adding more opacity every 100 milliseconds.

If you want a nice animation, you should add a class and animate the opacity in CSS.

Consider the following example:

let loadingscreen = document.querySelector(".loadingscreen");

window.addEventListener("scroll", () => {
  loadingscreen.classList.add("scrolled");
}, {
    once: true
}
);

body {
  height: 200vh;
}

div.loadingscreen {
  margin-top: 25%;
  height: 50%;
  width: 100%;
  background: red;
  opacity: 0;
}

div.loadingscreen.scrolled {
  opacity: 1;
  transition: opacity 1s linear;
}

<div class="loadingscreen"></div>


问:
Text alignment in HTML table column through VBA
I am trying to draft one Outlook mail body with html table using Excel VBA.

I am able to draft the mail with table and data. I am not able to align the text in the amount column as right alignment.

How do I align the text in the amount column to right?

Dim strTableHeader As String
Dim strTableBody As String
itb="abc"
balance=1000
strTableHeader = "" & _
                    "
" & _
                        TD("ITB") & _
                        TD("Balance Amount") & _
                    "
"

strTableBody= strTableBody & strTableHeader
strTableBody = strTableBody & _
                      "
" & _
                          TD(itb) & _
                          TD(balance) & _
                      "
"
```
<p>I am using this in my mail sending procedure:</p>
<pre class="lang-vb prettyprint-override"><code>Sub sendmailmdl()
    DoEvents
    Set olApp = Outlook.Application
    Set objMail = olApp.CreateItem(olMailItem)
    With objMail

        .HTMLBody = "<HTML><BODY>"  & strTableBody & " </BODY></HTML>"

        .Display
        DoEvents

    End With
End Sub
</code>```

where

```<code>TD(strIn As String) As String TD = "<TD nowrap>" & strIn & "</TD>" End Function
</code>```

答:
Add

```<code>tbody tr td:nth-child(2) { text-align: right; }
</code>```

to your stylesheet

or pass a second parameter to TD() to add

```<code>style="text-align: right; white-space:nowrap"
</code>```

to the cell

Body:
I am trying to draft one Outlook mail body with html table using Excel VBA.

I am able to draft the mail with table and data. I am not able to align the text in the amount column as right alignment.

How do I align the text in the amount column to right?

Dim strTableHeader As String
Dim strTableBody As String
itb="abc"
balance=1000
strTableHeader = "" & _
                    "
" & _
                        TD("ITB") & _
                        TD("Balance Amount") & _
                    "
"

strTableBody= strTableBody & strTableHeader
strTableBody = strTableBody & _
                      "
" & _
                          TD(itb) & _
                          TD(balance) & _
                      "
"

I am using this in my mail sending procedure:

Sub sendmailmdl()
    DoEvents
    Set olApp = Outlook.Application
    Set objMail = olApp.CreateItem(olMailItem)
    With objMail

        .HTMLBody = ""  & strTableBody & " "

        .Display
        DoEvents

    End With
End Sub

where

TD(strIn As String) As String TD = "" & strIn & "	" End Function

Body:
Add

tbody tr td:nth-child(2) { text-align: right; }

to your stylesheet

or pass a second parameter to TD() to add

style="text-align: right; white-space:nowrap"

to the cell


问:
Prevent updated_at and created_at from being hacked in postgresql
Let's say I have:

posts

id
created_at
updated_at
...

The default value for created_at is now(), and I have a trigger for updated_at like so:

create trigger posts_updated_at before update on posts
for each row execute procedure moddatetime (updated_at);
```
<p>How do I prevent everyone from updating the dates manually?</p>
<ul>
<li>created_at</li>
<li>updated_at</li>
</ul>
<p>I imagine there is a standard way to protect these field (column level security maybe)?</p>
<p>Something like this...</p>
<pre class="lang-sql prettyprint-override"><code>CREATE POLICY no_date_change ON posts
    FOR UPDATE
    USING (created_at === created_at);
</code>```

Either created_at does not change or created_at before = created_at after?

What is the standard way to protect these fields?

J

答:
Best way to implement this is to use column privilege and security group together.

GRANT ... update(<column_name>..) on <table_name> to ....

The post is long because I am trying to demonstrate it with steps and examples. Otherwise its simple few steps.

Demo Scenario

```<code>Experiment table: pgvpd
Experiment schema: demo_schema
Admin User(full privilege on expriment table): postgres
General user (restricted access on necessary column): demo_user.
</code>```

Table

```<code>select current_user;
create table demo_schema.pgvpd(txt varchar(10),createat date,updateat date);
insert into demo_schema.pgvpd values('one',current_date,current_date);
select * from demo_schema.pgvpd;
</code>```

Output:

```<code>postgres=# select current_user;
 current_user
--------------
 postgres
(1 row)
postgres=# create table demo_schema.pgvpd(txt varchar(10),createat date,updateat date);
CREATE TABLE
postgres=# insert into demo_schema.pgvpd values('one',current_date,current_date);
INSERT 0 1
postgres=# select * from demo_schema.pgvpd;
 txt |  createat  |  updateat
-----+------------+------------
 one | 2022-02-06 | 2022-02-06
(1 row)
</code>```

General User

```<code>create user demo_user password 'demo_user' valid until 'infinity';
</code>```

Output:

```<code>postgres=# create user demo_user password 'demo_user' valid until 'infinity';
CREATE ROLE
</code>```

Revoke the table from general availability and verify

```<code>revoke all on demo_schema.pgvpd from public;
set session authorization demo_user;
select current_user;
select * from demo_schema.pgvpd;
</code>```

Output:

```<code>postgres=# revoke all on demo_schema.pgvpd from public;
REVOKE
postgres=# set session authorization demo_user;
SET
postgres=> select current_user;
 current_user
--------------
 demo_user
(1 row)
postgres=> select * from demo_schema.pgvpd;
ERROR:  permission denied for schema demo_schema
LINE 1: select * from demo_schema.pgvpd;
</code>```

Create two security groups one for Admin (all privilege) and one for the needed restriction. Note: the all important piece ...update(txt) -> update is allowed only on 'txt' column, not on the date columns.

```<code>create group general_users;
grant usage on schema demo_schema to group general_users;
grant select,delete,insert,update(txt) on demo_schema.pgvpd to group general_users;
alter group general_users add user demo_user;

create group admin_users;
grant usage on schema demo_schema to group admin_users;
grant all on demo_schema.pgvpd to admin_users;
alter group admin_users add user postgres;
</code>```

Output:

```<code>postgres=# create group general_users;
CREATE ROLE
postgres=# grant usage on schema demo_schema to group general_users;
GRANT
postgres=# grant select,delete,insert,update(txt) on demo_schema.pgvpd to group general_users;
GRANT
postgres=# alter group general_users add user demo_user;
ALTER ROLE

postgres=# create group admin_users;
CREATE ROLE
postgres=# grant usage on schema demo_schema to group admin_users;
GRANT
postgres=# grant all on demo_schema.pgvpd to admin_users;
GRANT
postgres=# alter group admin_users add user postgres;
ALTER ROLE
</code>```

Verify the update on the column that needs protection is NOT ALLOWED for the general user but allowed for admin user.

For General User:

```<code>set session authorization demo_user;
select current_user;
select * from demo_schema.pgvpd;
insert into demo_schema.pgvpd values('two',current_date,current_date);
select * from demo_schema.pgvpd;
update  demo_schema.pgvpd set txt = 'two again' where txt='two';
select * from demo_schema.pgvpd;
update  demo_schema.pgvpd set createat = current_date where txt='two';
</code>```

Output:

```<code>select current_user;
create table demo_schema.pgvpd(txt varchar(10),createat date,updateat date);
insert into demo_schema.pgvpd values('one',current_date,current_date);
select * from demo_schema.pgvpd;
</code>```0

For admin user:

```<code>select current_user;
create table demo_schema.pgvpd(txt varchar(10),createat date,updateat date);
insert into demo_schema.pgvpd values('one',current_date,current_date);
select * from demo_schema.pgvpd;
</code>```1

Advice: Keep the number of Triggers as low as possible on production tables and also perfectly tuned for performance. Triggers are overhead on production tables for every DML that executes on it.

Edit: 7th February 2022 Demonstration through Row Level Security Policy.

Step 1: Create & populate the table with test data.

```<code>select current_user;
create table demo_schema.pgvpd(txt varchar(10),createat date,updateat date);
insert into demo_schema.pgvpd values('one',current_date,current_date);
select * from demo_schema.pgvpd;
</code>```2

Step 2: Enable row level security policy.

```<code>select current_user;
create table demo_schema.pgvpd(txt varchar(10),createat date,updateat date);
insert into demo_schema.pgvpd values('one',current_date,current_date);
select * from demo_schema.pgvpd;
</code>```3

Step 3: Create a permissive policy for SELECT,INSERT,DELETE.

```<code>select current_user;
create table demo_schema.pgvpd(txt varchar(10),createat date,updateat date);
insert into demo_schema.pgvpd values('one',current_date,current_date);
select * from demo_schema.pgvpd;
</code>```4

Step 4: Create the function that returns TRUE or FALSE for the permissive policy for UPDATE.

```<code>select current_user;
create table demo_schema.pgvpd(txt varchar(10),createat date,updateat date);
insert into demo_schema.pgvpd values('one',current_date,current_date);
select * from demo_schema.pgvpd;
</code>```5

Step 5: Create the final all important permission policy for UPDATE.

```<code>select current_user;
create table demo_schema.pgvpd(txt varchar(10),createat date,updateat date);
insert into demo_schema.pgvpd values('one',current_date,current_date);
select * from demo_schema.pgvpd;
</code>```6

Step 6: Run test as non-owner of the table.

```<code>select current_user;
create table demo_schema.pgvpd(txt varchar(10),createat date,updateat date);
insert into demo_schema.pgvpd values('one',current_date,current_date);
select * from demo_schema.pgvpd;
</code>```7

Trail:

```<code>select current_user;
create table demo_schema.pgvpd(txt varchar(10),createat date,updateat date);
insert into demo_schema.pgvpd values('one',current_date,current_date);
select * from demo_schema.pgvpd;
</code>```8

Edit 2: 7th February 2022 , demonstrating the impact of triggers.

Set up:
Identical tables

Posts - have security rules

Posts_1 - have triggers

Both freshly created tables with identical rows.

posts:

```<code>select current_user;
create table demo_schema.pgvpd(txt varchar(10),createat date,updateat date);
insert into demo_schema.pgvpd values('one',current_date,current_date);
select * from demo_schema.pgvpd;
</code>```9

posts_1:

```<code>postgres=# select current_user;
 current_user
--------------
 postgres
(1 row)
postgres=# create table demo_schema.pgvpd(txt varchar(10),createat date,updateat date);
CREATE TABLE
postgres=# insert into demo_schema.pgvpd values('one',current_date,current_date);
INSERT 0 1
postgres=# select * from demo_schema.pgvpd;
 txt |  createat  |  updateat
-----+------------+------------
 one | 2022-02-06 | 2022-02-06
(1 row)
</code>```0

Performance Comparison on posts and posts_1

posts (policy based)

```<code>postgres=# select current_user;
 current_user
--------------
 postgres
(1 row)
postgres=# create table demo_schema.pgvpd(txt varchar(10),createat date,updateat date);
CREATE TABLE
postgres=# insert into demo_schema.pgvpd values('one',current_date,current_date);
INSERT 0 1
postgres=# select * from demo_schema.pgvpd;
 txt |  createat  |  updateat
-----+------------+------------
 one | 2022-02-06 | 2022-02-06
(1 row)
</code>```1

posts_1 (trigger based)

```<code>postgres=# select current_user;
 current_user
--------------
 postgres
(1 row)
postgres=# create table demo_schema.pgvpd(txt varchar(10),createat date,updateat date);
CREATE TABLE
postgres=# insert into demo_schema.pgvpd values('one',current_date,current_date);
INSERT 0 1
postgres=# select * from demo_schema.pgvpd;
 txt |  createat  |  updateat
-----+------------+------------
 one | 2022-02-06 | 2022-02-06
(1 row)
</code>```2

The difference in the execution plan is the extra line for the trigger.

```<code>Trigger on_posts_1_update: time=0.033 calls=1
</code>```

I believe even the policy has to execute code but it appears triggers are more costly.
However, trade-off can be ignored if the amount of updates and the latency introduced through trigger is acceptable. You can really discern it through benchmarking.

Body:
Let's say I have:

posts

id
created_at
updated_at
...

The default value for created_at is now(), and I have a trigger for updated_at like so:

create trigger posts_updated_at before update on posts
for each row execute procedure moddatetime (updated_at);

How do I prevent everyone from updating the dates manually?

created_at

updated_at

I imagine there is a standard way to protect these field (column level security maybe)?

Something like this...

CREATE POLICY no_date_change ON posts
    FOR UPDATE
    USING (created_at === created_at);

Either created_at does not change or created_at before = created_at after?

What is the standard way to protect these fields?

J

Body:
Best way to implement this is to use column privilege and security group together.

GRANT ... update(<column_name>..) on <table_name> to ....

The post is long because I am trying to demonstrate it with steps and examples. Otherwise its simple few steps.

Demo Scenario

Experiment table: pgvpd
Experiment schema: demo_schema
Admin User(full privilege on expriment table): postgres
General user (restricted access on necessary column): demo_user.

Table

select current_user;
create table demo_schema.pgvpd(txt varchar(10),createat date,updateat date);
insert into demo_schema.pgvpd values('one',current_date,current_date);
select * from demo_schema.pgvpd;

Output:

postgres=# select current_user;
 current_user
--------------
 postgres
(1 row)
postgres=# create table demo_schema.pgvpd(txt varchar(10),createat date,updateat date);
CREATE TABLE
postgres=# insert into demo_schema.pgvpd values('one',current_date,current_date);
INSERT 0 1
postgres=# select * from demo_schema.pgvpd;
 txt |  createat  |  updateat
-----+------------+------------
 one | 2022-02-06 | 2022-02-06
(1 row)

General User

create user demo_user password 'demo_user' valid until 'infinity';

Output:

postgres=# create user demo_user password 'demo_user' valid until 'infinity';
CREATE ROLE

Revoke the table from general availability and verify

revoke all on demo_schema.pgvpd from public;
set session authorization demo_user;
select current_user;
select * from demo_schema.pgvpd;

Output:

postgres=# revoke all on demo_schema.pgvpd from public;
REVOKE
postgres=# set session authorization demo_user;
SET
postgres=> select current_user;
 current_user
--------------
 demo_user
(1 row)
postgres=> select * from demo_schema.pgvpd;
ERROR:  permission denied for schema demo_schema
LINE 1: select * from demo_schema.pgvpd;

Create two security groups one for Admin (all privilege) and one for the needed restriction. Note: the all important piece ...update(txt) -> update is allowed only on 'txt' column, not on the date columns.

create group general_users;
grant usage on schema demo_schema to group general_users;
grant select,delete,insert,update(txt) on demo_schema.pgvpd to group general_users;
alter group general_users add user demo_user;

create group admin_users;
grant usage on schema demo_schema to group admin_users;
grant all on demo_schema.pgvpd to admin_users;
alter group admin_users add user postgres;

Output:

postgres=# create group general_users;
CREATE ROLE
postgres=# grant usage on schema demo_schema to group general_users;
GRANT
postgres=# grant select,delete,insert,update(txt) on demo_schema.pgvpd to group general_users;
GRANT
postgres=# alter group general_users add user demo_user;
ALTER ROLE

postgres=# create group admin_users;
CREATE ROLE
postgres=# grant usage on schema demo_schema to group admin_users;
GRANT
postgres=# grant all on demo_schema.pgvpd to admin_users;
GRANT
postgres=# alter group admin_users add user postgres;
ALTER ROLE

Verify the update on the column that needs protection is NOT ALLOWED for the general user but allowed for admin user.

For General User:

set session authorization demo_user;
select current_user;
select * from demo_schema.pgvpd;
insert into demo_schema.pgvpd values('two',current_date,current_date);
select * from demo_schema.pgvpd;
update  demo_schema.pgvpd set txt = 'two again' where txt='two';
select * from demo_schema.pgvpd;
update  demo_schema.pgvpd set createat = current_date where txt='two';

Output:

postgres=# set session authorization demo_user;
SET
postgres=> select current_user;
 current_user
--------------
 demo_user
(1 row)

postgres=> select * from demo_schema.pgvpd;
 txt |  createat  |  updateat
-----+------------+------------
 one | 2022-02-06 | 2022-02-06
(1 row)

postgres=> insert into demo_schema.pgvpd values('two',current_date,current_date);
INSERT 0 1
postgres=> select * from demo_schema.pgvpd;
 txt |  createat  |  updateat
-----+------------+------------
 one | 2022-02-06 | 2022-02-06
 two | 2022-02-06 | 2022-02-06
(2 rows)

postgres=> update  demo_schema.pgvpd set txt = 'two again' where txt='two';
UPDATE 1
postgres=> select * from demo_schema.pgvpd;
    txt    |  createat  |  updateat
-----------+------------+------------
 one       | 2022-02-06 | 2022-02-06
 two again | 2022-02-06 | 2022-02-06
(2 rows)

postgres=> update  demo_schema.pgvpd set createat = current_date where txt='two';
ERROR:  permission denied for table pgvpd

For admin user:

postgres=> set session authorization postgres;
SET
postgres=# select current_user;
 current_user
--------------
 postgres
(1 row)
postgres=# update  demo_schema.pgvpd set createat = current_date where txt='two again';
UPDATE 1

Advice: Keep the number of Triggers as low as possible on production tables and also perfectly tuned for performance. Triggers are overhead on production tables for every DML that executes on it.

Edit: 7th February 2022 Demonstration through Row Level Security Policy.

Step 1: Create & populate the table with test data.

create table posts
(
 id serial primary key,
 created_at timestamp,
 updated_at timestamp
);
grant all on posts to public;
grant all on posts_id_seq to public;

insert into posts(created_at,updated_at) values(current_timestamp,current_timestamp);
select pg_catalog.pg_sleep(10);
insert into posts(created_at,updated_at) values(current_timestamp,current_timestamp);

Step 2: Enable row level security policy.

alter table posts enable row level security;

Step 3: Create a permissive policy for SELECT,INSERT,DELETE.

create policy posts_insert on posts for insert with check(true);
create policy posts_delete on posts for delete using(true);
create policy posts_select on posts for select using(true);

Step 4: Create the function that returns TRUE or FALSE for the permissive policy for UPDATE.

create or replace function posts_update_check(id_new int,updated_at_new timestamp, created_at_new timestamp)
returns boolean
language plpgsql
as
$$
declare
    row_variable posts%rowtype;
    flag boolean;
begin
    flag := true;
    select * from posts into row_variable where id=id_new;
    if (row_variable.updated_at != updated_at_new or row_variable.created_at != created_at_new)
        then flag := false;
    end if;
    return flag;
end; $$;

Step 5: Create the final all important permission policy for UPDATE.

create policy posts_update on posts for update using(true) with check(posts_update_check(id,updated_at,created_at));

Step 6: Run test as non-owner of the table.

set session authorization demo_user;
select current_user;
select * from posts;
insert into posts(created_at,updated_at) values(current_timestamp,current_timestamp);
select pg_catalog.pg_sleep(5);
insert into posts(created_at,updated_at) values(current_timestamp,current_timestamp);
select * from posts;
delete from posts where id= 1;
update posts set id=1 where id=2;
update posts set created_at = current_timestamp where id=1;
update posts set updated_at = current_timestamp where id=1;

Trail:

postgres=# create table posts
postgres-# (
postgres(#  id serial primary key,
postgres(#  created_at timestamp,
postgres(#  updated_at timestamp
postgres(# );
CREATE TABLE
postgres=# grant all on posts to public;
GRANT
postgres=# grant all on posts_id_seq to public;
GRANT
postgres=#
postgres=#
postgres=# insert into posts(created_at,updated_at) values(current_timestamp,current_timestamp);
INSERT 0 1
postgres=# select pg_catalog.pg_sleep(10);
 pg_sleep
----------

(1 row)

postgres=# insert into posts(created_at,updated_at) values(current_timestamp,current_timestamp);
INSERT 0 1
postgres=#
postgres=#
postgres=#
postgres=#
postgres=#
postgres=# alter table posts enable row level security;
ALTER TABLE
postgres=#
postgres=#
postgres=#
postgres=# create policy posts_insert on posts for insert with check(true);
CREATE POLICY
postgres=# create policy posts_delete on posts for delete using(true);
CREATE POLICY
postgres=# create policy posts_select on posts for select using(true);
CREATE POLICY
postgres=#
postgres=#
postgres=#
postgres=#
postgres=#
postgres=# create or replace function posts_update_check(id_new int,updated_at_new timestamp, created_at_new timestamp)
postgres-# returns boolean
postgres-# language plpgsql
postgres-# as
postgres-# $$
postgres$# declare
postgres$# row_variable posts%rowtype;
postgres$# flag boolean;
postgres$# begin
postgres$# flag := true;
postgres$# select * from posts into row_variable where id=id_new;
postgres$# if (row_variable.updated_at != updated_at_new or row_variable.created_at != created_at_new)
postgres$#

postgres$# then flag := false;
postgres$# end if;
postgres$# return flag;
postgres$# end; $$;
CREATE FUNCTION
postgres=#
postgres=#
postgres=#
postgres=#
postgres=#
postgres=#
postgres=#
postgres=#
postgres=#
postgres=# create policy posts_update on posts for update using(true) with check(posts_update_check(id,updated_at,created_at));
CREATE POLICY
postgres=#
postgres=#
postgres=#
postgres=#
postgres=#
postgres=#
postgres=#
postgres=# set session authorization demo_user;
SET
postgres=> select current_user;
 current_user
--------------
 demo_user
(1 row)

postgres=> select * from posts;
 id |         created_at         |         updated_at
----+----------------------------+----------------------------
  1 | 2022-02-08 08:32:41.527004 | 2022-02-08 08:32:41.527004
  2 | 2022-02-08 08:32:51.536821 | 2022-02-08 08:32:51.536821
(2 rows)

postgres=> insert into posts(created_at,updated_at) values(current_timestamp,current_timestamp);
INSERT 0 1
postgres=> select pg_catalog.pg_sleep(5);
 pg_sleep
----------

(1 row)

postgres=> insert into posts(created_at,updated_at) values(current_timestamp,current_timestamp);
INSERT 0 1
postgres=> select * from posts;
 id |         created_at         |         updated_at
----+----------------------------+----------------------------
  1 | 2022-02-08 08:32:41.527004 | 2022-02-08 08:32:41.527004
  2 | 2022-02-08 08:32:51.536821 | 2022-02-08 08:32:51.536821
  3 | 2022-02-08 08:33:41.400015 | 2022-02-08 08:33:41.400015
  4 | 2022-02-08 08:33:46.411654 | 2022-02-08 08:33:46.411654
(4 rows)

postgres=> delete from posts where id= 1;
DELETE 1
postgres=> update posts set id=1 where id=2;
UPDATE 1
postgres=> update posts set created_at = current_timestamp where id=1;
ERROR:  new row violates row-level security policy for table "posts"
postgres=> update posts set updated_at = current_timestamp where id=1;
ERROR:  new row violates row-level security policy for table "posts"
postgres=>

Edit 2: 7th February 2022 , demonstrating the impact of triggers.

Set up:
Identical tables

Posts - have security rules

Posts_1 - have triggers

Both freshly created tables with identical rows.

posts:

postgres=> \d posts
                                        Table "public.posts"
   Column   |            Type             | Collation | Nullable |              Default
------------+-----------------------------+-----------+----------+-----------------------------------
 id         | integer                     |           | not null | nextval('posts_id_seq'::regclass)
 created_at | timestamp without time zone |           |          |
 updated_at | timestamp without time zone |           |          |
Indexes:
    "posts_pkey" PRIMARY KEY, btree (id)
Policies (forced row security enabled):
    POLICY "posts_delete" FOR DELETE
      USING (true)
    POLICY "posts_insert" FOR INSERT
      WITH CHECK (true)
    POLICY "posts_select" FOR SELECT
      USING (true)
    POLICY "posts_update" FOR UPDATE
      USING (true)
      WITH CHECK (posts_update_check(id, updated_at, created_at))
  postgres=> select * from posts;
 id |         created_at         |         updated_at
----+----------------------------+----------------------------
  8 | 2022-02-08 16:23:20.48457  | 2022-02-08 16:23:20.48457
  9 | 2022-02-08 16:23:30.501669 | 2022-02-08 16:23:30.501669
(2 rows)

posts_1:

postgres=> \d posts_1
                                        Table "public.posts_1"
   Column   |            Type             | Collation | Nullable |               Default
------------+-----------------------------+-----------+----------+-------------------------------------
 id         | integer                     |           | not null | nextval('posts_1_id_seq'::regclass)
 created_at | timestamp without time zone |           |          |
 updated_at | timestamp without time zone |           |          |
Indexes:
    "posts_1_pkey" PRIMARY KEY, btree (id)
Triggers:
    on_posts_1_update BEFORE UPDATE ON posts_1 FOR EACH ROW EXECUTE FUNCTION posts_1_created_at()

postgres=> select * from posts_1;
 id |         created_at         |         updated_at
----+----------------------------+----------------------------
  3 | 2022-02-08 16:17:11.792555 | 2022-02-08 16:17:11.792555
  4 | 2022-02-08 16:17:21.800956 | 2022-02-08 16:17:21.800956
(2 rows)

Performance Comparison on posts and posts_1

posts (policy based)

postgres=> explain (analyze,timing,buffers)   update posts_1 set id=80 where id=8;
                                               QUERY PLAN
--------------------------------------------------------------------------------------------------------
 Update on posts_1  (cost=0.00..1.02 rows=1 width=26) (actual time=0.017..0.020 rows=0 loops=1)
   Buffers: shared hit=1
   ->  Seq Scan on posts_1  (cost=0.00..1.02 rows=1 width=26) (actual time=0.014..0.015 rows=0 loops=1)
         Filter: (id = 8)
         Rows Removed by Filter: 2
         Buffers: shared hit=1
 Planning Time: 0.076 ms
 Execution Time: 0.054 ms
(8 rows)

posts_1 (trigger based)

postgres=> explain (analyze,timing,buffers)   update posts_1 set id=40 where id=4;
                                               QUERY PLAN
--------------------------------------------------------------------------------------------------------
 Update on posts_1  (cost=0.00..1.02 rows=1 width=26) (actual time=0.112..0.115 rows=0 loops=1)
   Buffers: shared hit=3 read=1 dirtied=2
   ->  Seq Scan on posts_1  (cost=0.00..1.02 rows=1 width=26) (actual time=0.015..0.017 rows=1 loops=1)
         Filter: (id = 4)
         Rows Removed by Filter: 1
         Buffers: shared hit=1
 Planning Time: 0.075 ms
 Trigger on_posts_1_update: time=0.033 calls=1
 Execution Time: 0.150 ms
(9 rows)

The difference in the execution plan is the extra line for the trigger.

Trigger on_posts_1_update: time=0.033 calls=1

I believe even the policy has to execute code but it appears triggers are more costly.
However, trade-off can be ignored if the amount of updates and the latency introduced through trigger is acceptable. You can really discern it through benchmarking.


问:
BASHRC PS1 show datetime but plus 3 hours
Every of us set own convenience working with Linux shell, for example I use
/root/.bashrc

```<code>PS1='[\h:\w] \D{%F %T}\n\$ '
</code>```

to show servername + current server datetime + newline for command - so it looks like

```<code>[servername217:~] 2022-02-06 00:55:02
#
</code>```

But I met a stumbling block with syntax trying to set not server time, but my home, for example plus 3 hours. It's easy to make with regular BASH

```<code>date -d '+ 3 hour' '+%F %T'
</code>```

but when I try to use, for example,

```<code>PS1='[\h:\w] [date -d '+ 3 hour' '+%F %T']\n\$ '
</code>```

I always get an error. It seems PS1 understands only

```<code>\D{%F %T}
</code>```

but how to add 3 hours to %T under this format ? Or there is an another way ?

答:
For bash v4.2 or higher, you can use the printf date format specifier. This should be more efficient than forking a new date(1) process at each prompt:

```<code>PS1='[\h:\w] $(printf "%(%F %T)T" "$((\D{%s} + 60*60*3))")\n\$ '
</code>```

Personally, instead of a command substitution in PS1, I prefer to set a variable with PROMPT_COMMAND (a string which executed before each prompt), and use that in PS1. This makes it easy for example to unset PROMPT_COMMAND if the command is causing trouble.

That can be done like this (bash 4.3 or higher required for printf "%(%s)T" to print the current date):

```<code>PROMPT_COMMAND='
ps1_date=$(printf "%(%F %T)T" \
"$(($(printf "%(%s)T") + 60*60*3))"
)'
</code>```

Or this (bash 4.4 or higher required for ${ps1_date@P}):

```<code>PROMPT_COMMAND='
    ps1_date="\D{%s}"
    ps1_date=${ps1_date@P}
    ps1_date=$(printf "%(%F %T)T" "$((ps1_date+60*60*3))")'
</code>```

Then just use that variable here:

```<code>PS1='[\h:\w] ${ps1_date}n\$ '
</code>```

Body:
Every of us set own convenience working with Linux shell, for example I use
/root/.bashrc

PS1='[\h:\w] \D{%F %T}\n\$ '

to show servername + current server datetime + newline for command - so it looks like

[servername217:~] 2022-02-06 00:55:02
#

But I met a stumbling block with syntax trying to set not server time, but my home, for example plus 3 hours. It's easy to make with regular BASH

date -d '+ 3 hour' '+%F %T'

but when I try to use, for example,

PS1='[\h:\w] [date -d '+ 3 hour' '+%F %T']\n\$ '

I always get an error. It seems PS1 understands only

\D{%F %T}

but how to add 3 hours to %T under this format ? Or there is an another way ?

Body:
For bash v4.2 or higher, you can use the printf date format specifier. This should be more efficient than forking a new date(1) process at each prompt:

PS1='[\h:\w] $(printf "%(%F %T)T" "$((\D{%s} + 60*60*3))")\n\$ '

Personally, instead of a command substitution in PS1, I prefer to set a variable with PROMPT_COMMAND (a string which executed before each prompt), and use that in PS1. This makes it easy for example to unset PROMPT_COMMAND if the command is causing trouble.

That can be done like this (bash 4.3 or higher required for printf "%(%s)T" to print the current date):

PROMPT_COMMAND='
ps1_date=$(printf "%(%F %T)T" \
"$(($(printf "%(%s)T") + 60*60*3))"
)'

Or this (bash 4.4 or higher required for ${ps1_date@P}):

PROMPT_COMMAND='
    ps1_date="\D{%s}"
    ps1_date=${ps1_date@P}
    ps1_date=$(printf "%(%F %T)T" "$((ps1_date+60*60*3))")'

Then just use that variable here:

PS1='[\h:\w] ${ps1_date}n\$ '


问:
Im trying to run an app but im getting an error which says "could not find translocated node" in Xcode
[default] LSPrefs: could not find untranslocated node for <FSNode 0x600003002ae0> { isDir = ?, path = '/private/var/folders/k7/zdtfstr13gxcrwg98wc0k1dm0000gn/X/14ADFEAC-68C8-59CF-AC5B-21F464164A42/d/Wrapper/Dicee-iOS13.app' }, proceeding on the assumption it is not translocated: Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"</p>

答:
I am getting similar messages in the console when running an iOS app from XCode on the target myMac (Designed for iPad).
However, as far as I am concerned, this is just a warning that does not prevent the app from running.

More information on translocation here: https://eclecticlight.co/2021/04/19/ios-apps-are-translocated-when-run-in-macos/


问:
WebStorm 2018.1.4 + ESLint: TypeError: this.CliEngine is not a constructor
My configuration is this.

WebStorm 2018.1.4; ESLint 6.4;  Node 12.8; npm 6.10.2; Windows 8.1.

How do I eliminate the error in the thread title?

Here's a code sample.

```<code>import {
  GET_DAILY_SUCCESS,
  GET_HOURLY_SUCCESS,
  GET_MINUTE_SUCCESS
} from './types';
import {
  getDailyToUsd,
  getHourlyToUsd,
  getMinuteToUsd
} from '../api/cryptocompare';
import { setError } from './error';

export const getDaily = (fsym = 'BTC') => async dispatch => {
  try {
    const list = await getDailyToUsd(fsym);

    dispatch({
      type: GET_DAILY_SUCCESS,
      currency: fsym,
      list
    });
  } catch(err) {
    dispatch(setError(err.Message));
  }
};
</code>```

答:
In additional to Dabrule answer:

For eslint v8 replace this line:

```<code>this.cliEngineCtor = requireInContext(eslintPackagePath + "lib/api", state.packageJsonPath).CLIEngine;
</code>```

to that:

```<code>this.cliEngineCtor = requireInContext(eslintPackagePath + "lib/cli-engine").CLIEngine;
</code>```

File location, for example, RubyMine (WebStorm should be similar):

RubyMine-2021.1.3/plugins/JavaScriptLanguage/languageService/eslint/bin/eslint-plugin.js

Body:
My configuration is this.

WebStorm 2018.1.4; ESLint 6.4;  Node 12.8; npm 6.10.2; Windows 8.1.

How do I eliminate the error in the thread title?

Here's a code sample.

import {
  GET_DAILY_SUCCESS,
  GET_HOURLY_SUCCESS,
  GET_MINUTE_SUCCESS
} from './types';
import {
  getDailyToUsd,
  getHourlyToUsd,
  getMinuteToUsd
} from '../api/cryptocompare';
import { setError } from './error';

export const getDaily = (fsym = 'BTC') => async dispatch => {
  try {
    const list = await getDailyToUsd(fsym);

    dispatch({
      type: GET_DAILY_SUCCESS,
      currency: fsym,
      list
    });
  } catch(err) {
    dispatch(setError(err.Message));
  }
};

Body:
In additional to Dabrule answer:

For eslint v8 replace this line:

this.cliEngineCtor = requireInContext(eslintPackagePath + "lib/api", state.packageJsonPath).CLIEngine;

to that:

this.cliEngineCtor = requireInContext(eslintPackagePath + "lib/cli-engine").CLIEngine;

File location, for example, RubyMine (WebStorm should be similar):

RubyMine-2021.1.3/plugins/JavaScriptLanguage/languageService/eslint/bin/eslint-plugin.js


问:
How to create gRPC streaming interceptors using C#?
I have figured out how to create unary RPC interceptors but I can't figure out how to make streaming RPC interceptors.
This is what I have thus far:

```<code>public override async Task<TResponse> ClientStreamingServerHandler<TRequest, TResponse>(
        IAsyncStreamReader<TRequest> requestStream, ServerCallContext context,
        ClientStreamingServerMethod<TRequest, TResponse> continuation)
    {
        Console.WriteLine("ClientStreaming");
        var response = await base.ClientStreamingServerHandler(requestStream, context, continuation);
        return response;
    }
</code>```

This code snipped Console logs every time a Client stream is initiated, I just can't figure out how to console log every incoming client message.

Kind Regards Jesse

答:
Also you can check GRPC examples - https://github.com/grpc/grpc-dotnet/tree/master/examples

There are a lot of gRPC scenarios in Github

Body:
I have figured out how to create unary RPC interceptors but I can't figure out how to make streaming RPC interceptors.
This is what I have thus far:

public override async Task<TResponse> ClientStreamingServerHandler<TRequest, TResponse>(
        IAsyncStreamReader<TRequest> requestStream, ServerCallContext context,
        ClientStreamingServerMethod<TRequest, TResponse> continuation)
    {
        Console.WriteLine("ClientStreaming");
        var response = await base.ClientStreamingServerHandler(requestStream, context, continuation);
        return response;
    }

This code snipped Console logs every time a Client stream is initiated, I just can't figure out how to console log every incoming client message.

Kind Regards Jesse


问:
How to change home page url in wordpress
I am going to change home page in wordpress. so I created new page and I am going to change the homepage to new page. but I can't change it.
How to solve its problem?</p>

答: You only have to choose page in settings -> writting (I think this is in english) and choose you cover page


问:
Why did "None" came as the second output for my one line code in python?
print(print("Hello World!"))

and the output is :

Hello World!
None

答:
The print function has no return value, i.e. it returns None.

(What did you expect to get with the second print?)


问:
Are function arguments not evaluated left to right? How are side effects on the same variable ordered?
Consider the following program.

```<code>#include<iostream>
using namespace std;

void fn(int a, int b)
{
    cout << a;
    cout << b;
}

int main()
{
    int a = 10;
    fn(a++, --a);
    fn(a--, ++a);
    return 0;
}

</code>```

I don't understand the output I get (gcc 11.2):

9101110

Shouldn't a++ be evaluated first? How can fn then get a 9? Is this undefined behavior or simply "indeterminate"? Did C++17 change in this respect?

答:
This is undefined behavior. The order of parameter evaluation is unspecified.

See here.

So this question is irrelevant and code like this should never be used.

The output can be 9 10 11 10 on one compiler, and a totally different value on another compiler (while both compilers remain standard-complaint).

Body:
Consider the following program.

#include<iostream>
using namespace std;

void fn(int a, int b)
{
    cout << a;
    cout << b;
}

int main()
{
    int a = 10;
    fn(a++, --a);
    fn(a--, ++a);
    return 0;
}

I don't understand the output I get (gcc 11.2):

9101110

Shouldn't a++ be evaluated first? How can fn then get a 9? Is this undefined behavior or simply "indeterminate"? Did C++17 change in this respect?


问:
I'm not getting any error, then why is not my data persisting into the database?
Greetings my folks I'm using JPA 2.0 and so far I'm not really getting any kind of error from anywhwere in the project, however the data is not persiting into the database at all, this is my persistence.xml (just the pu) file as it looks right now:

```<code><persistence-unit name="auto-core-pu" transaction-type="RESOURCE_LOCAL">
        <description>Auto Core Persistence Unit</description>
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <class>com.auto.core.model.Cars</class>
        <class>com.auto.core.model.Client</class>
        <properties>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/auto_core"/>
            <property name="javax.persistence.jdbc.user" value="root"/>
            <property name="javax.persistence.jdbc.password" value="123456"/>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
        </properties>
    </persistence-unit>
</persistence>
</code>```

This is my EntityManagerClient.class

```<code>package com.auto.core.persistence;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import com.auto.core.model.Cars;

public class EntityManagerClient {
 public static void main(String[] args){
    EntityManager em = Persistence.createEntityManagerFactory("auto-core-pu").createEntityManager();
    EntityTransaction t = em.getTransaction();

    t.begin();

    Cars cr = new Cars();
    cr.setBrand("Toyota");
    cr.setModel("Camry");
    cr.setEngine("V6");
    cr.setDoors(5);
    cr.setType("Jeepeta");
    cr.setYear(123);
    cr.setDescription("Auto usado del año 123 D.C.");

    t.commit();

 }

 public static void getData(){
     EntityManager em = Persistence.createEntityManagerFactory("auto-core-pu").createEntityManager();
     EntityTransaction g = em.getTransaction();

     g.begin();

     Cars cr = em.createNamedQuery("Cars.FindbyId", Cars.class).setParameter("id", 1L).getSingleResult();
     System.out.println(cr.getBrand());

 }

}
</code>```

and lass an example of how I did the annotations in other classes:

```<code>@Entity
@Table(schema="auto_core" , name="client")
public class Client {

    @Id
    @GeneratedValue
    long id;
    @Column(name="name")
    String name;
    @Column(name="lastname")
    String lastname;
    @Column(name="email")
    String email;
    @Column(name="address")
    String address;
    @Column(name="address2")
    String address2;
    @Column(name="zip")
    String zip;
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
</code>```

Again, I'm not getting any kind of error, is just that I can't persist data, or query data that I put manually into the database, that's all.

答:
It's because you're getting the EntityManager, opening the transaction, and creating the object but you don't persist it. You have to invoke:

```<code>em.persist(cr);
</code>```

before

```<code>t.commit();
</code>```

Until you persist it, it's just a POJO in memory.

Body:
Greetings my folks I'm using JPA 2.0 and so far I'm not really getting any kind of error from anywhwere in the project, however the data is not persiting into the database at all, this is my persistence.xml (just the pu) file as it looks right now:

<persistence-unit name="auto-core-pu" transaction-type="RESOURCE_LOCAL">
        <description>Auto Core Persistence Unit</description>
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <class>com.auto.core.model.Cars</class>
        <class>com.auto.core.model.Client</class>
        <properties>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/auto_core"/>
            <property name="javax.persistence.jdbc.user" value="root"/>
            <property name="javax.persistence.jdbc.password" value="123456"/>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
        </properties>
    </persistence-unit>
</persistence>

This is my EntityManagerClient.class

package com.auto.core.persistence;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import com.auto.core.model.Cars;

public class EntityManagerClient {
 public static void main(String[] args){
    EntityManager em = Persistence.createEntityManagerFactory("auto-core-pu").createEntityManager();
    EntityTransaction t = em.getTransaction();

    t.begin();

    Cars cr = new Cars();
    cr.setBrand("Toyota");
    cr.setModel("Camry");
    cr.setEngine("V6");
    cr.setDoors(5);
    cr.setType("Jeepeta");
    cr.setYear(123);
    cr.setDescription("Auto usado del año 123 D.C.");

    t.commit();

 }

 public static void getData(){
     EntityManager em = Persistence.createEntityManagerFactory("auto-core-pu").createEntityManager();
     EntityTransaction g = em.getTransaction();

     g.begin();

     Cars cr = em.createNamedQuery("Cars.FindbyId", Cars.class).setParameter("id", 1L).getSingleResult();
     System.out.println(cr.getBrand());

 }

}

and lass an example of how I did the annotations in other classes:

@Entity
@Table(schema="auto_core" , name="client")
public class Client {

    @Id
    @GeneratedValue
    long id;
    @Column(name="name")
    String name;
    @Column(name="lastname")
    String lastname;
    @Column(name="email")
    String email;
    @Column(name="address")
    String address;
    @Column(name="address2")
    String address2;
    @Column(name="zip")
    String zip;
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

Again, I'm not getting any kind of error, is just that I can't persist data, or query data that I put manually into the database, that's all.

Body:
It's because you're getting the EntityManager, opening the transaction, and creating the object but you don't persist it. You have to invoke:

em.persist(cr);

before

t.commit();

Until you persist it, it's just a POJO in memory.


问:
how to index a numeric value to return a string
I have this enum

```<code>enum CombatType_t
{
    COMBAT_ICEDAMAGE    = 1 << 9, // 512
    COMBAT_HOLYDAMAGE   = 1 << 10, // 1024
    COMBAT_DEATHDAMAGE  = 1 << 11, // 2048
};
</code>```

Basically, im trying to make a new array/list to be able to index an string by using a specific number to index CombatType_t

Something as the following:

```<code>enum AbsorbType_t
{
    "elementIce" = 512,
    "elementHoly" = 1024,
    "elementDeath" = 2048
}
</code>```

In Lua, for example I could make an associative table

```<code>local t = {
    [512] = "elementIce";
}
</code>```

And then, to index i could simply do t[512] which returns "elementIce"

How can I do this in C++?

答:
In C++, the standard way to make an associative table is std::map:

```<code>#include<iostream>
#include<map>
#include<string>
...

   std::map<unsigned, std::string> absorbType = {
      {512, "elementIce"},
      {1024, "elementHoly"},
      {2048, "elementDeath"}
   };

   // Access by index
   std::cout << "512->" << absorbType[512] << std::endl;
</code>```

Body:
I have this enum

enum CombatType_t
{
    COMBAT_ICEDAMAGE    = 1 << 9, // 512
    COMBAT_HOLYDAMAGE   = 1 << 10, // 1024
    COMBAT_DEATHDAMAGE  = 1 << 11, // 2048
};

Basically, im trying to make a new array/list to be able to index an string by using a specific number to index CombatType_t

Something as the following:

enum AbsorbType_t
{
    "elementIce" = 512,
    "elementHoly" = 1024,
    "elementDeath" = 2048
}

In Lua, for example I could make an associative table

local t = {
    [512] = "elementIce";
}

And then, to index i could simply do t[512] which returns "elementIce"

How can I do this in C++?

Body:
In C++, the standard way to make an associative table is std::map:

#include<iostream>
#include<map>
#include<string>
...

   std::map<unsigned, std::string> absorbType = {
      {512, "elementIce"},
      {1024, "elementHoly"},
      {2048, "elementDeath"}
   };

   // Access by index
   std::cout << "512->" << absorbType[512] << std::endl;


问:
HTML5 make empty div full viewport size
I’m trying to create an EMPTY div that takes up 100% of the viewport and that moves with the viewport (or position: fixed).
It also needs to be at top: 0, left 0 of the viewport. This is for a browser extension so I need this div to be added over any page.

The background reason for this is so I can use the div as a full page tooltip that shows the mouse x and y positions and the tooltip follows the mouse.

How can this full page div be achieved? My many attempts have failed to create a div with any height.

I am away from my pc but can add what I’ve tried already soon.

答:
Try this</p>
```<code>{
position:absolute;
inset:0;
width:100vw;
height:100vh;
}
</code>```

Title: HTML5 make empty div full viewport size

Body:
Try this

{
position:absolute;
inset:0;
width:100vw;
height:100vh;
}


问:
How to print certain amount of numbers in one line and then again in other?
Im looking for an output that will print numbers from 100 to 200 with 15 numbers in one line

100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115

116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130,
131

.....

what i have right now is this:

```<code>for number in range(100,200):
   print(number, end = ", ")
</code>```

what do i need to add ?

答:
Use enumerate to get the number position, then use condition  to whether print a comma or go nextline

```<code>per_line = 15
for idx, number in enumerate(range(100, 200), 1):
    if idx % per_line != 0:
        print(number, end=", ")
    else:
        print(number)
</code>```

Can be inlined in

```<code>for idx, number in enumerate(range(100, 200), 1):
    print(number, end=", " if idx % per_line != 0 else "\n")
</code>```

Body:
Im looking for an output that will print numbers from 100 to 200 with 15 numbers in one line

100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115

116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130,
131

.....

what i have right now is this:

for number in range(100,200):
   print(number, end = ", ")

what do i need to add ?

Body:
Use enumerate to get the number position, then use condition  to whether print a comma or go nextline

per_line = 15
for idx, number in enumerate(range(100, 200), 1):
    if idx % per_line != 0:
        print(number, end=", ")
    else:
        print(number)

Can be inlined in

for idx, number in enumerate(range(100, 200), 1):
    print(number, end=", " if idx % per_line != 0 else "\n")