问:
PHP | if stament always false
I have a small problem with an if loop, I am building an appointment booking area, the directives are:

Appointments can be made from Monday to Friday

Appointment times: 11:00 - 13:00 and 15:00 - 18:00

the variables that take the value from the datepicker and timepicker are:

datepicker:

```<code>$app_to_data = $connessione->real_escape_string($_POST['data']);
</code>```

timepicker:

```<code>$app_to_orario = $connessione->real_escape_string($_POST['orario']);
</code>```

no problem to prevent the chosen day from being confirmed when the user chooses to book an appointment on Saturday or Sunday:

```<code>if(date('w', strtotime($app_to_data)) == 6 || date('w', strtotime($app_to_data)) == 0) {
    ?>
    <script type="text/javascript">
        var errore_appto = "<?php echo $id_pa ?>";
        window.location = "prendi_appto_errore.php?errore_appto=" + errore_appto;
    </script>
<?php
exit;
}
</code>```

the problem now comes when I have to initiate if cycles to check the time slot chosen for the appointment:

```<code>   /*VERIFICA CHE L' APPUNTAMENTO NON VENGA PRESO PRIMA DELLE ORE 11:00*/
    if($app_to_orario < '11:00'){
    ?>
        <script type="text/javascript">
            var errore_appto = "<?php echo $id_pa ?>";
            window.location = "prendi_appto_errore.php?errore_appto=" + errore_appto;
        </script>
    <?php
    exit;
    }

    /*VERIFICA CHE L' APPUNTAMENTO NON VENGA PRESO DOPO LE ORE 13:00*/
    elseif($app_to_orario > '13:00'){
    ?>
        <script type="text/javascript">
            var errore_appto = "<?php echo $id_pa ?>";
            window.location = "prendi_appto_errore.php?errore_appto=" + errore_appto;
        </script>
    <?php
    exit;
    }

    /*VERIFICA CHE L' APPUNTAMENTO NON VENGA PRESO PRIMA DELLE ORE 15:00*/
    elseif($app_to_orario < '15:00'){
    ?>
        <script type="text/javascript">
            var errore_appto = "<?php echo $id_pa ?>";
            window.location = "prendi_appto_errore.php?errore_appto=" + errore_appto;
        </script>
    <?php
    exit;
    }

    /*VERIFICA CHE L' APPUNTAMENTO NON VENGA PRESO DOPO LE ORE 18:00*/
    elseif($app_to_orario > '18:00'){
    ?>
        <script type="text/javascript">
            var errore_appto = "<?php echo $id_pa ?>";
            window.location = "prendi_appto_errore.php?errore_appto=" + errore_appto;
        </script>
    <?php
    exit;
    }
</code>```

the problem I have is that if for example the user chooses to book an appointment for 16:00, the chosen time is correct, but I always get an error because for example in the second cycle 16:00 it is greater than 13:00 even if it falls correctly in the remaining 3 control cycles, so how do I perform a time check allowing the appointment in the time slots indicated in the question, without always running into a false result?

答:
Please try below code:</p>

```<code>if (str_replace(":", "", $app_to_orario) > str_replace(":", "", "11:00"))
{
}
</code>```

Title: PHP | if stament always false

Body:
I have a small problem with an if loop, I am building an appointment booking area, the directives are:

Appointments can be made from Monday to Friday

Appointment times: 11:00 - 13:00 and 15:00 - 18:00

the variables that take the value from the datepicker and timepicker are:

datepicker:

$app_to_data = $connessione->real_escape_string($_POST['data']);

timepicker:

$app_to_orario = $connessione->real_escape_string($_POST['orario']);

no problem to prevent the chosen day from being confirmed when the user chooses to book an appointment on Saturday or Sunday:

if(date('w', strtotime($app_to_data)) == 6 || date('w', strtotime($app_to_data)) == 0) {
    ?>

<?php
exit;
}

the problem now comes when I have to initiate if cycles to check the time slot chosen for the appointment:

   /*VERIFICA CHE L' APPUNTAMENTO NON VENGA PRESO PRIMA DELLE ORE 11:00*/
    if($app_to_orario < '11:00'){
    ?>

    <?php
    exit;
    }

    /*VERIFICA CHE L' APPUNTAMENTO NON VENGA PRESO DOPO LE ORE 13:00*/
    elseif($app_to_orario > '13:00'){
    ?>

    <?php
    exit;
    }

    /*VERIFICA CHE L' APPUNTAMENTO NON VENGA PRESO PRIMA DELLE ORE 15:00*/
    elseif($app_to_orario < '15:00'){
    ?>

    <?php
    exit;
    }

    /*VERIFICA CHE L' APPUNTAMENTO NON VENGA PRESO DOPO LE ORE 18:00*/
    elseif($app_to_orario > '18:00'){
    ?>

    <?php
    exit;
    }

the problem I have is that if for example the user chooses to book an appointment for 16:00, the chosen time is correct, but I always get an error because for example in the second cycle 16:00 it is greater than 13:00 even if it falls correctly in the remaining 3 control cycles, so how do I perform a time check allowing the appointment in the time slots indicated in the question, without always running into a false result?

Body:
Please try below code:

if (str_replace(":", "", $app_to_orario) > str_replace(":", "", "11:00"))
{
}


来源: stackexchange

问:
[JavaScript]What is the relationship between a task and a macro task in an EventLoop?
When I was studying EventLoop, neither the HTML standard nor the MDN mentioned the macrotask concept (just tasks and microtasks), but I saw them in some blogs.I wonder where the macro task comes from?And what is the relationship between the task and the macro task?

HTML Standard: https://html.spec.whatwg.org/multipage/webappapis.html#event-loops

MDN: https://developer.mozilla.org/zh-CN/docs/Web/API/HTML_DOM_API/Microtask_guide/In_depth

https://developer.mozilla.org/zh-CN/docs/Web/API/HTML_DOM_API/Microtask_guide

Can you help me? I'd better attach the relevant documents.Thank you very much!

答:
Indeed there is no concept of macro-task anywhere in the HTML specs.

Though it's often used in informal texts (even among the specs issues) as a mean to distinguish clearly when we talk about tasks and not about microtasks.

Since microtasks are a subset of task, it can sometimes help to clearly distinguish.

So "macro-task" --> "task" but not "microtask".

ContentLicense: CC BY-SA 4.0


问:
Clang vs G++ lvalue to rvalue conversion
The question related to this  one. By tracing slt_pair. h and move. h, it's seems that the difference between Clang and G++ is internally. I have tried to simulate the assignment of the object (pair.first) as same as the implementation of std_pair.h, the output is same as Clang output it's reasonable output, but why when using pairs it's changes.

```<code>#include <iostream>

struct Foo {
  Foo() {
    std::cout << "default" << std::endl;
  }
  Foo(Foo& f2) {
    std::cout << "non-const" << std::endl;
  }
  Foo(const Foo& f2) {
    std::cout << "const" << std::endl;
  }
};

// static_cast Foo lvalue to rvalue
Foo cast1(Foo foo){

    return static_cast<Foo&&>(foo);
}

// same : check weather foo and Foo are the same type
Foo cast2(Foo foo){
     return static_cast<typename std::remove_reference<Foo>::type&&>(foo);
}

int main() {

        Foo T1; // pair Foo object

        std::cout<<"Start"<<std::endl;
        std::cout<<std::endl;

        // (&&) rvalue casting
        T1 = cast2(Foo()); // First pair object

        std::cout << std::endl;

        Foo const foo = T1;// Second pair object

}
</code>```

How Clang deals with conversion lvalue to rvalue and what the real reason for these different outputs.

Any opinion is highly appreciated, Thanks.

Update: I have got a satisfying answers on the comments section of the accepted one.

答:
I think not everything in your example does what you think it does. The static_cast in the returns is meaningless, the result of cast1 and cast2 will automatically be an rvalue since you return by value. Further, cast1 and cast2 are also internally identical since std::remove_reference_t<Foo> is just Foo. You would need remove_reference if you had some templating going on.

Furthermore, you are mixing assignments with constructions. In T1 = cast2(Foo()); the following happens:

A unnamed temporary is constructed by Foo(). This outputs default

This temporary is copied to the foo argument of cast2. This outputs const, since we try to construct a Foo object from a temporary, and only const Foo&, not Foo&, can bind to a temporary.

The static_cast does pretty much nothing.

foo is returned. By return value optimization, the constructor that should be called, is not called.

We assign the returned value by using the default (and implicit) assignment operator T1.operator=(const Foo&). Nothing gets printed.

In Foo const foo = T1 you call a constructor. Since T1 is an lvalue, you will call the constructor Foo(Foo&) and non-const is printed.

Body:
The question related to this  one. By tracing slt_pair. h and move. h, it's seems that the difference between Clang and G++ is internally. I have tried to simulate the assignment of the object (pair.first) as same as the implementation of std_pair.h, the output is same as Clang output it's reasonable output, but why when using pairs it's changes.

#include <iostream>

struct Foo {
  Foo() {
    std::cout << "default" << std::endl;
  }
  Foo(Foo& f2) {
    std::cout << "non-const" << std::endl;
  }
  Foo(const Foo& f2) {
    std::cout << "const" << std::endl;
  }
};

// static_cast Foo lvalue to rvalue
Foo cast1(Foo foo){

    return static_cast<Foo&&>(foo);
}

// same : check weather foo and Foo are the same type
Foo cast2(Foo foo){
     return static_cast<typename std::remove_reference<Foo>::type&&>(foo);
}

int main() {

        Foo T1; // pair Foo object

        std::cout<<"Start"<<std::endl;
        std::cout<<std::endl;

        // (&&) rvalue casting
        T1 = cast2(Foo()); // First pair object

        std::cout << std::endl;

        Foo const foo = T1;// Second pair object

}

How Clang deals with conversion lvalue to rvalue and what the real reason for these different outputs.

Any opinion is highly appreciated, Thanks.

Update: I have got a satisfying answers on the comments section of the accepted one.


问:
Is there any way to force django run some finishing code before exit?
I am running a server program with django,
I want to run some code before and after the server running.
Where can I put those code?

```<code><run function a here>
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
^C
<run function b here>
</code>```

I have tried to a print('hello') in app/__init__.py, but found that it runs for twice. Why?

答:
I do think it's not a good idea to run Django app with runserver or similar.
So your question can be "How to quit Django App gracefully".

Commonly we run Django in production environment with gunicorn or similar WSGI apps. You will not know when and how it quits.

So we may catch signal SIG_INT and SIG_TERM for gracefully quiting.
e.g.

import signal

def quit_gracefully():
   print('quit')

signal.signal(signal.SIGINT, quit_gracefully)
signal.signal(signal.SIGTERM, quit_gracefully)
```

ref to this doc: https://docs.python.org/3/library/signal.html

Body:
I am running a server program with django,
I want to run some code before and after the server running.
Where can I put those code?

<run function a here>
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
^C
<run function b here>

I have tried to a print('hello') in app/__init__.py, but found that it runs for twice. Why?

Body:
I do think it's not a good idea to run Django app with runserver or similar.
So your question can be "How to quit Django App gracefully".

Commonly we run Django in production environment with gunicorn or similar WSGI apps. You will not know when and how it quits.

So we may catch signal SIG_INT and SIG_TERM for gracefully quiting.
e.g.

import signal

def quit_gracefully():
   print('quit')

signal.signal(signal.SIGINT, quit_gracefully)
signal.signal(signal.SIGTERM, quit_gracefully)

ref to this doc: https://docs.python.org/3/library/signal.html


问:
Why would CURL time out in 1000ms when I have set up timeout upto 3000ms?
In one of my script I have set up curl time out, CURLOPT_CONNECTTIMEOUT_MS, to 3000ms, but curl time outs much before than that, at an average of 1000ms. Why would it time out so early? </p>

答:
I believe the timeout you are seeing is a CURL operation timeout, rather than a connection timeout. These two are different.

CURLOPT_TIMEOUT (and CURLOPT_TIMEOUT_MS for millisecond values) control the timeout for the work CURL does after it's connected. CUROPT_CONNECTTIMEOUT (and CUROPT_CONNECTTIMEOUT_MS) control the timeout for the initial connection (DNS lookup, establishing the connection, etc.)

If I'm right, then if you set CURLOPT_TIMEOUT higher than 1, you should find that your timeout doesn't trip at 1000ms any more.

ContentLicense: CC BY-SA 3.0


问:
Typescript Object is possibly 'null' focusing using ref in react
typescript is still giving me error

Object is possibly 'null'.ts(2531)

even though I do this

```<code>myRef && myRef.current && myRef.current.focus();
</code>```

if I use

```<code>myRef?.current?.focus();
</code>```

I got

```<code>Property 'focus' does not exist on type 'never'.ts(2339)
</code>```

答:
To make typescript silent and tell typescript you know what you are doing.
you can use exclamation mark(!) before the variable you know that it can be null.
Like in existing scenario if "current" can be null in some scenarios and you want that
typescript do not show error on it.

```<code>myRef.!current.focus()
</code>```

Body:
typescript is still giving me error

Object is possibly 'null'.ts(2531)

even though I do this

myRef && myRef.current && myRef.current.focus();

if I use

myRef?.current?.focus();

I got

Property 'focus' does not exist on type 'never'.ts(2339)

Body:
To make typescript silent and tell typescript you know what you are doing.
you can use exclamation mark(!) before the variable you know that it can be null.
Like in existing scenario if "current" can be null in some scenarios and you want that
typescript do not show error on it.

myRef.!current.focus()


问:
Converting Image to Bytes and back
I know there is a lot of help already about this subject, but using this help I ran into a problem: I have an image list with icons that I display in a tree view on a windows form and that works.

Now I want to take these icons, put them in a table, clear the image list and then load the image list from the table.  This is to test if I can use a table to maintain the icons.

The problem is that the icons display a black background using this method. I use BytesFromImage to write to an Image column in the table and ImageFromStream and StreamFromBytes to read the data back to an image.

What am I missing?

```<code>public static byte[] BytesFromImage(Image TheImage)
{
    MemoryStream ms = new MemoryStream();
    TheImage.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
    return ms.ToArray();
}

public static Stream StreamFromBytes(byte[] DataBytes)
{
    MemoryStream stream = new MemoryStream();
    stream.Write(DataBytes, 0, DataBytes.Length);
    stream.Seek(0, SeekOrigin.Begin);
    return stream;
}

public static Image ImageFromStream(Stream DataStream)
{
    return Bitmap.FromStream(DataStream);
}
</code>```

答:
The black background is caused by converting the icons into the format GIF. Better use PNG, this should respect transparent backgrounds:

```<code>public static byte[] BytesFromImage(Image TheImage)
{
    MemoryStream ms = new MemoryStream();
    TheImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
    return ms.ToArray();
}
</code>```

Title: Converting Image to Bytes and back

Body:
I know there is a lot of help already about this subject, but using this help I ran into a problem: I have an image list with icons that I display in a tree view on a windows form and that works.

Now I want to take these icons, put them in a table, clear the image list and then load the image list from the table.  This is to test if I can use a table to maintain the icons.

The problem is that the icons display a black background using this method. I use BytesFromImage to write to an Image column in the table and ImageFromStream and StreamFromBytes to read the data back to an image.

What am I missing?

public static byte[] BytesFromImage(Image TheImage)
{
    MemoryStream ms = new MemoryStream();
    TheImage.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
    return ms.ToArray();
}

public static Stream StreamFromBytes(byte[] DataBytes)
{
    MemoryStream stream = new MemoryStream();
    stream.Write(DataBytes, 0, DataBytes.Length);
    stream.Seek(0, SeekOrigin.Begin);
    return stream;
}

public static Image ImageFromStream(Stream DataStream)
{
    return Bitmap.FromStream(DataStream);
}

Body:
The black background is caused by converting the icons into the format GIF. Better use PNG, this should respect transparent backgrounds:

public static byte[] BytesFromImage(Image TheImage)
{
    MemoryStream ms = new MemoryStream();
    TheImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
    return ms.ToArray();
}


问:
jQuery stop function from being called when its already being called by other event
I'm trying to call a function in two ways: either way, when the function is called it should not allow the other one to call the method

Here renameFolder is called in two places: first on focus out and second when enter is being pressed.

The problem is that when enter is pressed it calls the function 2 times 1 for enter being pressed and second for focus out as well.

Following is my jsfiddle example : https://jsfiddle.net/tzx0ojLk/12/

and following is my code:

```<code>$('#rename').click(function () {

        //delete previous popup-menu if exists
        removeMenu();

        var folder = e.target.id;
        var folderId = $("#" + folder).attr("id");
        var folderName = $('#' + folder).parent().parent().children('.bd-title').text().trim();

        $('#' + folder).parent().parent().children('.bd-title').replaceWith('<textarea class="bd-folder-title-input" oninput="this.style.height = `1px`;this.style.height = (10+this.scrollHeight)+`px`;"  onfocusout="renameFolder()" maxlength="50" cols="10">' + folderName + '</textarea>');
        $('textarea').focus();
        $('textarea').select();
        $("textarea").keypress(function (e) {
            if (e.which == 13 && !e.shiftKey) {
                // alert(e);
                // $('textarea').trigger( "focusout" );
                // console.log(e);
                // e.trigger('focusout');
                // $('#' + folder).parent().parent().children('.bd-folder-title-input').trigger( "focusout" );
                $('body').focus();
                // console.log($(e.currentTarget));
                $('.bd-folder-title-input').trigger('focusout');
            }
        });

    });
</code>```

答:
Just add focusout listner after you call focus and select:

```<code>$('#rename').click(function() {

  //delete previous popup-menu if exists

  var folder = 1;
  //alert(folder);
  var folderId = $("#" + folder).attr("id");
  var folderName = $('#' + folder).parent().parent().children('.bd-title').text().trim();

  $('#' + folder).parent().parent().children('.bd-title').replaceWith('<textarea class="bd-folder-title-input" oninput="this.style.height = `1px`;this.style.height = (10+this.scrollHeight)+`px`;" maxlength="50" cols="10">' + folderName + '</textarea>');
  $('textarea').focus();
  $('textarea').select();
  $('textarea').on('focusout', function(event) {
    renameFolder()
  });
  $("textarea").keypress(function(e) {
    if (e.which == 13 && !e.shiftKey) {
      renameFolder();
    }
  });

});
</code>```

See in playground: https://jsfiddle.net/denisstukalov/espvc8t4/1/#&togetherjs=5mdJ3oeu1y

Body:
I'm trying to call a function in two ways: either way, when the function is called it should not allow the other one to call the method

Here renameFolder is called in two places: first on focus out and second when enter is being pressed.

The problem is that when enter is pressed it calls the function 2 times 1 for enter being pressed and second for focus out as well.

Following is my jsfiddle example : https://jsfiddle.net/tzx0ojLk/12/

and following is my code:

$('#rename').click(function () {

        //delete previous popup-menu if exists
        removeMenu();

        var folder = e.target.id;
        var folderId = $("#" + folder).attr("id");
        var folderName = $('#' + folder).parent().parent().children('.bd-title').text().trim();

        $('#' + folder).parent().parent().children('.bd-title').replaceWith('<textarea class="bd-folder-title-input" oninput="this.style.height = `1px`;this.style.height = (10+this.scrollHeight)+`px`;"  onfocusout="renameFolder()" maxlength="50" cols="10">' + folderName + '</textarea>');
        $('textarea').focus();
        $('textarea').select();
        $("textarea").keypress(function (e) {
            if (e.which == 13 && !e.shiftKey) {
                // alert(e);
                // $('textarea').trigger( "focusout" );
                // console.log(e);
                // e.trigger('focusout');
                // $('#' + folder).parent().parent().children('.bd-folder-title-input').trigger( "focusout" );
                $('body').focus();
                // console.log($(e.currentTarget));
                $('.bd-folder-title-input').trigger('focusout');
            }
        });

    });

Body:
Just add focusout listner after you call focus and select:

$('#rename').click(function() {

  //delete previous popup-menu if exists

  var folder = 1;
  //alert(folder);
  var folderId = $("#" + folder).attr("id");
  var folderName = $('#' + folder).parent().parent().children('.bd-title').text().trim();

  $('#' + folder).parent().parent().children('.bd-title').replaceWith('<textarea class="bd-folder-title-input" oninput="this.style.height = `1px`;this.style.height = (10+this.scrollHeight)+`px`;" maxlength="50" cols="10">' + folderName + '</textarea>');
  $('textarea').focus();
  $('textarea').select();
  $('textarea').on('focusout', function(event) {
    renameFolder()
  });
  $("textarea").keypress(function(e) {
    if (e.which == 13 && !e.shiftKey) {
      renameFolder();
    }
  });

});

See in playground: https://jsfiddle.net/denisstukalov/espvc8t4/1/#&togetherjs=5mdJ3oeu1y


问:
Reg Performance : Data Transformation using Stored procedure
I tried transforming only 3M records in snowflake using XL warehouse.The transformation rules are attached.
The error records are written into an error table and success records are written into the clean table.
The warehouse used is XL and the time taken for processing is 1hr5mins.
It seems the time taken is quite high as compared to the number of records and the transformation rules.
Could anyone please take a look into the stored procedure and suggest if the code has to be modified to improve performance.
Thanks

```<code>create or replace procedure clean_transform_table(UPLOAD_DATE_IN VARCHAR)
returns varchar not null
  language javascript
  as
$$

//-------------define function to check valid date format
function isValidDate(datevalue) {
    var pattern = /^\d{4}-\d{1,2}-\d{1,2}$/;
    return datevalue.match(pattern);
}

//--------define function to check valid email
function isvalidEmail(email) {
    var pattern = /\S+@\S+\.com$/;
    return email.match(pattern);
}

//------------define function to insert error records
function insertErrorRecords(errorDetails){
if (errorDetails.length > 0){
        var errorDetails = errorDetails.toString();
        var cmd = "insert into error_records_log values"+errorDetails;
        var stmt = snowflake.createStatement(
            {
                sqlText: cmd
            }
        );
        stmt.execute();
}

}

//-------function to check valid birth date
function birthDateCheck(row_num, person_id, birth_date,recordStatus) {

    if (birth_date == null || birth_date.trim() == '' || isValidDate(birth_date.trim().toString()) == null) {
        var arr = [row_num,person_id,tableName,birthDateVar,"Value is null or empty or invalid",update_date,birth_date];
        var arr = "'" + arr.join("','") + "'";
        errorDetails.push( "("+arr+")" );
        return 1;

    } else {
        return recordStatus;
    }

}

//------function to check valid gender value
function genderCheck(row_num, person_id, gender,recordStatus) {

    if (gender == null || !['M', 'F'].includes(gender.trim())) {
        var arr = [row_num,person_id,tableName,genderVar,"Value is null or other in [M,F]",update_date,gender];
        var arr = "'" + arr.join("','") + "'";
        errorDetails.push( "("+arr+")" );
       return 1;
    } else {
        return recordStatus;
    }

}

//--------function to check valid country value
function countryCheck(row_num, person_id, country,country_of_Birth,recordStatus) {

    if (country != country_of_Birth) {
       var arr = [row_num,person_id,tableName,countryVar,"Value is not same as country_of_Birth",update_date,country];
       var arr = "'" + arr.join("','") + "'";
       errorDetails.push( "("+arr+")" );
       return 1;
    } else {
        return recordStatus;
    }

}

//-------function to check valid loan amount
function loanCheck(row_num, person_id, loan_amount,recordStatus) {

    if (loan_amount != null && loan_amount.trim() != '' && loan_amount.trim() < 0) {
       var arr = [row_num,person_id,tableName,loanVar,"Value is negative number",update_date,loan_amount];
       var arr = "'" + arr.join("','") + "'";
       errorDetails.push( "("+arr+")" );
       return 1;
    } else {
        return recordStatus;
    }

}

//------function to validate email
function emailCheck(row_num, person_id, email,recordStatus) {
    if (email != null && isvalidEmail(email) == null){

       var arr = [row_num,person_id,tableName,emailVar,"value is invalid email",update_date,email];
       var arr = "'" + arr.join("','") + "'";
       errorDetails.push( "("+arr+")" );
       return 1;
    } else {
        return recordStatus;
    }

}

//----------function extract all data, validate and trace errors
function validateAllDataTraceErrors(){
var cmd = "select * from SF_STRUCT_STAGE_RAW where upload_date = to_date(:1,'YYYY-MM-DD')";
var stmt = snowflake.createStatement(
    {
        sqlText: cmd
        ,binds:[UPLOAD_DATE_IN]
    }
);
var resultSet = stmt.execute();

//----loop thru all the data
while (resultSet.next()) {

    var recordStatus = 0;
    var row_num = resultSet.getColumnValueAsString('ROW_NUM');
    var person_id = resultSet.getColumnValueAsString('PERSON_ID');
    var birth_date = resultSet.getColumnValueAsString('BIRTH_DATE');
    var gender = resultSet.getColumnValueAsString('GENDER');
    var country = resultSet.getColumnValueAsString('COUNTRY');
    var country_of_Birth = resultSet.getColumnValueAsString('COUNTRY_OF_BIRTH');
    var loan_amount = resultSet.getColumnValueAsString('LOAN_AMOUNT');
    var email = resultSet.getColumnValueAsString('EMAIL');

    //----birth date check
    var recordStatus = birthDateCheck(row_num, person_id, birth_date,errorDetails,recordStatus);

    //------gender check
    var recordStatus = genderCheck(row_num, person_id, gender,recordStatus);

    //------country and country of birth check
    var recordStatus = countryCheck(row_num, person_id, country,country_of_Birth,recordStatus);

    //------email check
    var recordStatus = emailCheck(row_num, person_id, email,recordStatus);

    //------Loan amount negative check
    var recordStatus = loanCheck(row_num, person_id, loan_amount,recordStatus);

    //------Update error Rownum's in variable
    if (recordStatus == 1) {
        errorRowNum.push(row_num)
    }
}

}

//------function to transfer valid records to clean table
function transfer_valid_records(errorRowNum) {
var condition = "";

if (errorRowNum.length > 0){
condition = "where upload_date = to_date(:1,'YYYY-MM-DD') and raw.row_num not in ("+ errorRowNum.toString()+");";
}else{
condition = "where upload_date = to_date(:1,'YYYY-MM-DD');";
}

if (errorRowNum.length == 0){
errorRowNum = '';
}
var cmd = `insert into SF_STRUCT_CLEAN
select
seq1.nextval,
raw.Person_id,
reverse(raw.Given_Name),
reverse(raw.Family_Name),
raw.Title,
raw.BIRTH_DATE,
lkp_gen.description,
raw.Mobile_Phone,
raw.Email,
raw.Address_Line_1,
raw.Postcode,
raw.State,
raw.Country,
raw.Country_of_Birth,
raw.loan_amount,
current_date()
from SF_STRUCT_STAGE_RAW raw
left join lkp_gender lkp_gen
on raw.Gender = lkp_gen.code `+condition;

var stmt = snowflake.createStatement(
        {
            sqlText: cmd,
            binds:[UPLOAD_DATE_IN]
        }
    );
    stmt.execute();
}

//----------------------call main functions
try{

//-------------define variables
var birthDateVar = 'BIRTH_DATE';
var genderVar = 'GENDER';
var countryVar = 'COUNTRY';
var loanVar = 'LOAN_AMOUNT';
var emailVar = 'EMAIL';
var tableName = 'SF_STRUCT_STAGE_RAW';
var errorRowNum = [];
var errorDetails = [];
var currentDate =  new Date();
var update_date = currentDate.getFullYear()+'-'+(currentDate.getMonth()+1)+'-'+currentDate.getDate();

validateAllDataTraceErrors();

insertErrorRecords(errorDetails);

transfer_valid_records(errorRowNum);

result = 'Success';
}
catch (err){
result =  "Failed: Code: " + err.code + "\n  State: " + err.state;
result += "\n  Message: " + err.message;
result += "\nStack Trace:\n" + err.stackTraceTxt;
}

return result;
$$
  ;
</code>```

The raw table has following schema
Columns Data Type
ROW_NUM NUMBER(38,0)
PERSON_ID   NUMBER(38,0)
GIVEN_NAME  VARCHAR(100)
FAMILY_NAME VARCHAR(100)
TITLE   VARCHAR(100)
BIRTH_DATE  VARCHAR(100)
GENDER  VARCHAR(100)
MOBILE_PHONE    VARCHAR(100)
EMAIL   VARCHAR(100)
ADDRESS_LINE_1  VARCHAR(100)
POSTCODE    VARCHAR(100)
STATE   VARCHAR(100)
COUNTRY VARCHAR(100)
COUNTRY_OF_BIRTH    VARCHAR(100)
LOAN_AMOUNT VARCHAR(50)
FILE_NAME   VARCHAR(100)
UPLOAD_DATE DATE

The transformation rules are very basic as below

答:
1) You are processing rows one by one. I see that you use regular expressions, so it should be possible to convert this stored procedure to pure SQL (or at least process the rows as a set).

https://docs.snowflake.com/en/sql-reference/functions-regexp.html

2) It holds failed row numbers in JavaScript objects, you may have memory issues in case there are huge number of rows fail.

Body:
I tried transforming only 3M records in snowflake using XL warehouse.The transformation rules are attached.
The error records are written into an error table and success records are written into the clean table.
The warehouse used is XL and the time taken for processing is 1hr5mins.
It seems the time taken is quite high as compared to the number of records and the transformation rules.
Could anyone please take a look into the stored procedure and suggest if the code has to be modified to improve performance.
Thanks

create or replace procedure clean_transform_table(UPLOAD_DATE_IN VARCHAR)
returns varchar not null
  language javascript
  as
$$

//-------------define function to check valid date format
function isValidDate(datevalue) {
    var pattern = /^\d{4}-\d{1,2}-\d{1,2}$/;
    return datevalue.match(pattern);
}

//--------define function to check valid email
function isvalidEmail(email) {
    var pattern = /\S+@\S+\.com$/;
    return email.match(pattern);
}

//------------define function to insert error records
function insertErrorRecords(errorDetails){
if (errorDetails.length > 0){
        var errorDetails = errorDetails.toString();
        var cmd = "insert into error_records_log values"+errorDetails;
        var stmt = snowflake.createStatement(
            {
                sqlText: cmd
            }
        );
        stmt.execute();
}

}

//-------function to check valid birth date
function birthDateCheck(row_num, person_id, birth_date,recordStatus) {

    if (birth_date == null || birth_date.trim() == '' || isValidDate(birth_date.trim().toString()) == null) {
        var arr = [row_num,person_id,tableName,birthDateVar,"Value is null or empty or invalid",update_date,birth_date];
        var arr = "'" + arr.join("','") + "'";
        errorDetails.push( "("+arr+")" );
        return 1;

    } else {
        return recordStatus;
    }

}

//------function to check valid gender value
function genderCheck(row_num, person_id, gender,recordStatus) {

    if (gender == null || !['M', 'F'].includes(gender.trim())) {
        var arr = [row_num,person_id,tableName,genderVar,"Value is null or other in [M,F]",update_date,gender];
        var arr = "'" + arr.join("','") + "'";
        errorDetails.push( "("+arr+")" );
       return 1;
    } else {
        return recordStatus;
    }

}

//--------function to check valid country value
function countryCheck(row_num, person_id, country,country_of_Birth,recordStatus) {

    if (country != country_of_Birth) {
       var arr = [row_num,person_id,tableName,countryVar,"Value is not same as country_of_Birth",update_date,country];
       var arr = "'" + arr.join("','") + "'";
       errorDetails.push( "("+arr+")" );
       return 1;
    } else {
        return recordStatus;
    }

}

//-------function to check valid loan amount
function loanCheck(row_num, person_id, loan_amount,recordStatus) {

    if (loan_amount != null && loan_amount.trim() != '' && loan_amount.trim() < 0) {
       var arr = [row_num,person_id,tableName,loanVar,"Value is negative number",update_date,loan_amount];
       var arr = "'" + arr.join("','") + "'";
       errorDetails.push( "("+arr+")" );
       return 1;
    } else {
        return recordStatus;
    }

}

//------function to validate email
function emailCheck(row_num, person_id, email,recordStatus) {
    if (email != null && isvalidEmail(email) == null){

       var arr = [row_num,person_id,tableName,emailVar,"value is invalid email",update_date,email];
       var arr = "'" + arr.join("','") + "'";
       errorDetails.push( "("+arr+")" );
       return 1;
    } else {
        return recordStatus;
    }

}

//----------function extract all data, validate and trace errors
function validateAllDataTraceErrors(){
var cmd = "select * from SF_STRUCT_STAGE_RAW where upload_date = to_date(:1,'YYYY-MM-DD')";
var stmt = snowflake.createStatement(
    {
        sqlText: cmd
        ,binds:[UPLOAD_DATE_IN]
    }
);
var resultSet = stmt.execute();

//----loop thru all the data
while (resultSet.next()) {

    var recordStatus = 0;
    var row_num = resultSet.getColumnValueAsString('ROW_NUM');
    var person_id = resultSet.getColumnValueAsString('PERSON_ID');
    var birth_date = resultSet.getColumnValueAsString('BIRTH_DATE');
    var gender = resultSet.getColumnValueAsString('GENDER');
    var country = resultSet.getColumnValueAsString('COUNTRY');
    var country_of_Birth = resultSet.getColumnValueAsString('COUNTRY_OF_BIRTH');
    var loan_amount = resultSet.getColumnValueAsString('LOAN_AMOUNT');
    var email = resultSet.getColumnValueAsString('EMAIL');

    //----birth date check
    var recordStatus = birthDateCheck(row_num, person_id, birth_date,errorDetails,recordStatus);

    //------gender check
    var recordStatus = genderCheck(row_num, person_id, gender,recordStatus);

    //------country and country of birth check
    var recordStatus = countryCheck(row_num, person_id, country,country_of_Birth,recordStatus);

    //------email check
    var recordStatus = emailCheck(row_num, person_id, email,recordStatus);

    //------Loan amount negative check
    var recordStatus = loanCheck(row_num, person_id, loan_amount,recordStatus);

    //------Update error Rownum's in variable
    if (recordStatus == 1) {
        errorRowNum.push(row_num)
    }
}

}

//------function to transfer valid records to clean table
function transfer_valid_records(errorRowNum) {
var condition = "";

if (errorRowNum.length > 0){
condition = "where upload_date = to_date(:1,'YYYY-MM-DD') and raw.row_num not in ("+ errorRowNum.toString()+");";
}else{
condition = "where upload_date = to_date(:1,'YYYY-MM-DD');";
}

if (errorRowNum.length == 0){
errorRowNum = '';
}
var cmd = `insert into SF_STRUCT_CLEAN
select
seq1.nextval,
raw.Person_id,
reverse(raw.Given_Name),
reverse(raw.Family_Name),
raw.Title,
raw.BIRTH_DATE,
lkp_gen.description,
raw.Mobile_Phone,
raw.Email,
raw.Address_Line_1,
raw.Postcode,
raw.State,
raw.Country,
raw.Country_of_Birth,
raw.loan_amount,
current_date()
from SF_STRUCT_STAGE_RAW raw
left join lkp_gender lkp_gen
on raw.Gender = lkp_gen.code `+condition;

var stmt = snowflake.createStatement(
        {
            sqlText: cmd,
            binds:[UPLOAD_DATE_IN]
        }
    );
    stmt.execute();
}

//----------------------call main functions
try{

//-------------define variables
var birthDateVar = 'BIRTH_DATE';
var genderVar = 'GENDER';
var countryVar = 'COUNTRY';
var loanVar = 'LOAN_AMOUNT';
var emailVar = 'EMAIL';
var tableName = 'SF_STRUCT_STAGE_RAW';
var errorRowNum = [];
var errorDetails = [];
var currentDate =  new Date();
var update_date = currentDate.getFullYear()+'-'+(currentDate.getMonth()+1)+'-'+currentDate.getDate();

validateAllDataTraceErrors();

insertErrorRecords(errorDetails);

transfer_valid_records(errorRowNum);

result = 'Success';
}
catch (err){
result =  "Failed: Code: " + err.code + "\n  State: " + err.state;
result += "\n  Message: " + err.message;
result += "\nStack Trace:\n" + err.stackTraceTxt;
}

return result;
$$
  ;

The raw table has following schema
Columns Data Type
ROW_NUM NUMBER(38,0)
PERSON_ID   NUMBER(38,0)
GIVEN_NAME  VARCHAR(100)
FAMILY_NAME VARCHAR(100)
TITLE   VARCHAR(100)
BIRTH_DATE  VARCHAR(100)
GENDER  VARCHAR(100)
MOBILE_PHONE    VARCHAR(100)
EMAIL   VARCHAR(100)
ADDRESS_LINE_1  VARCHAR(100)
POSTCODE    VARCHAR(100)
STATE   VARCHAR(100)
COUNTRY VARCHAR(100)
COUNTRY_OF_BIRTH    VARCHAR(100)
LOAN_AMOUNT VARCHAR(50)
FILE_NAME   VARCHAR(100)
UPLOAD_DATE DATE

The transformation rules are very basic as below


问:
Python Pandas: Simple example of calculating RMSE from data frame
Need a simple example of calculating RMSE with Pandas DataFrame. Providing there is function that returns in cycle true and predicted value:

```<code>def fun (data):
   ...
   return trueVal, predVal

for data in set:
   fun(data)
</code>```

And then some code puts these results in the following data frame where x is a real value and p is a predicted value:

```<code>In [20]: d
Out[20]: {'p': [1, 10, 4, 5, 5], 'x': [1, 2, 3, 4, 5]}

In [21]: df = pd.DataFrame(d)

In [22]: df
Out[22]:
    p  x
0   1  1
1  10  2
2   4  3
3   5  4
4   5  5
</code>```

Questions:

1) How to put results from fun function in df data frame?

2) How to calculate RMSE using df data frame?

答:
Question 1

I understand you already have a dataframe df. To add the new values in new rows do the following:

```<code>for data in set:

    trueVal, predVal = fun(data)

    auxDf = pd.DataFrame([[predVal, trueVal]], columns = ['p', 'x'])

    df.append(auxDf, ignore_index = True)
</code>```

Question 2

To calculate RMSE using df, I recommend you to use the scikit learn function.

```<code>from sklearn.metrics import mean_squared_error
realVals = df.x
predictedVals = df.p
mse = mean_squared_error(realVals, predictedVals)
# If you want the root mean squared error
# rmse = mean_squared_error(realVals, predictedVals, squared = False)
</code>```

It's very important that you don't have null values in the columns, otherwise it won't work

Body:
Need a simple example of calculating RMSE with Pandas DataFrame. Providing there is function that returns in cycle true and predicted value:

def fun (data):
   ...
   return trueVal, predVal

for data in set:
   fun(data)

And then some code puts these results in the following data frame where x is a real value and p is a predicted value:

In [20]: d
Out[20]: {'p': [1, 10, 4, 5, 5], 'x': [1, 2, 3, 4, 5]}

In [21]: df = pd.DataFrame(d)

In [22]: df
Out[22]:
    p  x
0   1  1
1  10  2
2   4  3
3   5  4
4   5  5

Questions:

1) How to put results from fun function in df data frame?

2) How to calculate RMSE using df data frame?

Body:
Question 1

I understand you already have a dataframe df. To add the new values in new rows do the following:

for data in set:

    trueVal, predVal = fun(data)

    auxDf = pd.DataFrame([[predVal, trueVal]], columns = ['p', 'x'])

    df.append(auxDf, ignore_index = True)

Question 2

To calculate RMSE using df, I recommend you to use the scikit learn function.

from sklearn.metrics import mean_squared_error
realVals = df.x
predictedVals = df.p
mse = mean_squared_error(realVals, predictedVals)
# If you want the root mean squared error
# rmse = mean_squared_error(realVals, predictedVals, squared = False)

It's very important that you don't have null values in the columns, otherwise it won't work


问:
groupBy multiple fields in Kotlin and sum values
Assume that I have data looks like the following

```<code>data class Student(val name: String, val room: Int, val sex: String, val height: Int, val weight: Double){}
</code>```

and I have a list of students

```<code>val students = listOf(
     Student("Max", 1, "M", 165, 56.8),
     Student("Mint", 1, "F", 155, 53.2),
     Student("Moss", 1, "M", 165, 67.3),
     Student("Michael", 2, "M", 168, 65.6),
     Student("Minnie", 2, "F", 155, 48.9),
     Student("Mickey", 1, "M", 165, 54.1),
     Student("Mind", 2, "F", 155, 51.2),
     Student("May", 1, "F", 155, 53.6))
</code>```

My goal is to group the students with the same room, sex and height and sum their weight

The final list should be like this

```<code>{
Student(_, 1, "M", 165, <sum of weight of male students who is in 1st room with height 165>),
Student(_, 1, "F", 155, <sum of weight of female students who is in 1st room with height 155>),
...
}
</code>```

(The students' name can be omitted)

I already looked at Nested groupBy in Kotlin but it did not answer my question.

答:
When you need to group by several fields you can use Pair, Triple or your custom data class as a key for grouping

```<code>val result = students
    .groupingBy { Triple(it.room, it.sex, it.height) }
    .reduce { _, acc, element ->
        acc.copy(name = "_", weight = acc.weight + element.weight)
    }
    .values.toList()
</code>```

Body:
Assume that I have data looks like the following

data class Student(val name: String, val room: Int, val sex: String, val height: Int, val weight: Double){}

and I have a list of students

val students = listOf(
     Student("Max", 1, "M", 165, 56.8),
     Student("Mint", 1, "F", 155, 53.2),
     Student("Moss", 1, "M", 165, 67.3),
     Student("Michael", 2, "M", 168, 65.6),
     Student("Minnie", 2, "F", 155, 48.9),
     Student("Mickey", 1, "M", 165, 54.1),
     Student("Mind", 2, "F", 155, 51.2),
     Student("May", 1, "F", 155, 53.6))

My goal is to group the students with the same room, sex and height and sum their weight

The final list should be like this

{
Student(_, 1, "M", 165, <sum of weight of male students who is in 1st room with height 165>),
Student(_, 1, "F", 155, <sum of weight of female students who is in 1st room with height 155>),
...
}

(The students' name can be omitted)

I already looked at Nested groupBy in Kotlin but it did not answer my question.

Body:
When you need to group by several fields you can use Pair, Triple or your custom data class as a key for grouping

val result = students
    .groupingBy { Triple(it.room, it.sex, it.height) }
    .reduce { _, acc, element ->
        acc.copy(name = "_", weight = acc.weight + element.weight)
    }
    .values.toList()


问:
How to unit test a EntityCollectionServiceBase in @ngrx/data?
I have a dummy service:

```<code>export class PatientService extends EntityCollectionServiceBase<Patient> {
  constructor(serviceElementsFactory: EntityCollectionServiceElementsFactory) {
    super('Patient', serviceElementsFactory);
  }
}
</code>```

I have the following test:

```<code>describe('PatientService', () => {
  let service: PatientService;

  beforeEach(() => {
    TestBed.configureTestingModule({});
    service = TestBed.inject(PatientService);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });
});
</code>```

And it gives me:

NullInjectorError: No provider for EntityCollectionServiceElementsFactory

So I updated as follows:

```<code>describe('PatientService', () => {
  let service: PatientService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [EntityDataModuleWithoutEffects.forRoot(entityConfig)],
      providers: [provideMockStore()],
    });
    service = TestBed.inject(PatientService);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });
});
</code>```

But now it gives me:

NullInjectorError: No provider for ScannedActionsSubject!

How can I properly fix my test?

答:
Updated 2022-08-06

Because of changes in the latest version of ngrx, you need to import an empty store modules and HttpClientTestingModule.

Please check the example below:

describe('PatientService', () => {
  let service: PatientService;

  beforeEach(() => {

    TestBed.configureTestingModule({
      providers: [
        PatientService, // <- your entity collection service

        // a way to mock the store selectors
        provideMockStore(),
      ],
      imports: [
        EntityDataModule.forRoot({
          entityMetadata: {
            Patient: {}, // <- change to your entity
          },
          pluralNames: {
            Patient: 'Patients',  // <- change to your entity
          },
        }),

        // can be kept as it is if there are no more dependencies
        StoreModule.forRoot({}),
        EffectsModule.forRoot([]),
        HttpClientTestingModule,
      ],
    });
    service = TestBed.inject(PatientService);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });
});
```
<h2>Original answer</h2>
<p>Yep, you are very close, do like that. You need to provide in testbed everything what is required for the configuration.</p>
<p>In our case it means that <code>PatientService</code> should be provided as the testing unit and <code>EntityCollectionServiceElementsFactory</code> should be provided as its dependency.</p>
<p>But <code>EntityCollectionServiceElementsFactory</code> has own dependencies: <code>EntityDispatcherFactory</code>, <code>EntityDefinitionService</code>, <code>EntitySelectorsFactory</code> and <code>EntitySelectors$Factory</code>. Which we don't want to provide because they might have own dependencies making our live worse.</p>
<p>To fix it let's simply sub <code>EntityCollectionServiceElementsFactory</code>.</p>
<pre class="lang-js prettyprint-override"><code>describe('PatientService', () => {
  let service: PatientService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        PatientService,
        {
          provide: EntityCollectionServiceElementsFactory,
          // our stub
          useValue: {
            methodsToFake: jasmine.createSpy(),
            // ....
          },
        },
      ],
    });
    service = TestBed.inject(PatientService);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });
});
</code>```

Also to avoid the pain of mocking dependencies and its methods in future you can use ng-mocks. Then the test could looks like that:

describe('PatientService', () => {
  let service: PatientService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        PatientService,
        {
          provide: EntityCollectionServiceElementsFactory,
          useValue: MockService(EntityCollectionServiceElementsFactory),
        },
      ],
    });
    service = TestBed.inject(PatientService);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });
});
```

Body:
I have a dummy service:

export class PatientService extends EntityCollectionServiceBase<Patient> {
  constructor(serviceElementsFactory: EntityCollectionServiceElementsFactory) {
    super('Patient', serviceElementsFactory);
  }
}

I have the following test:

describe('PatientService', () => {
  let service: PatientService;

  beforeEach(() => {
    TestBed.configureTestingModule({});
    service = TestBed.inject(PatientService);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });
});

And it gives me:

NullInjectorError: No provider for EntityCollectionServiceElementsFactory

So I updated as follows:

describe('PatientService', () => {
  let service: PatientService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [EntityDataModuleWithoutEffects.forRoot(entityConfig)],
      providers: [provideMockStore()],
    });
    service = TestBed.inject(PatientService);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });
});

But now it gives me:

NullInjectorError: No provider for ScannedActionsSubject!

How can I properly fix my test?

Body:
Updated 2022-08-06

Because of changes in the latest version of ngrx, you need to import an empty store modules and HttpClientTestingModule.

Please check the example below:

describe('PatientService', () => {
  let service: PatientService;

  beforeEach(() => {

    TestBed.configureTestingModule({
      providers: [
        PatientService, // <- your entity collection service

        // a way to mock the store selectors
        provideMockStore(),
      ],
      imports: [
        EntityDataModule.forRoot({
          entityMetadata: {
            Patient: {}, // <- change to your entity
          },
          pluralNames: {
            Patient: 'Patients',  // <- change to your entity
          },
        }),

        // can be kept as it is if there are no more dependencies
        StoreModule.forRoot({}),
        EffectsModule.forRoot([]),
        HttpClientTestingModule,
      ],
    });
    service = TestBed.inject(PatientService);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });
});

Original answer

Yep, you are very close, do like that. You need to provide in testbed everything what is required for the configuration.

In our case it means that PatientService should be provided as the testing unit and EntityCollectionServiceElementsFactory should be provided as its dependency.

But EntityCollectionServiceElementsFactory has own dependencies: EntityDispatcherFactory, EntityDefinitionService, EntitySelectorsFactory and EntitySelectors$Factory. Which we don't want to provide because they might have own dependencies making our live worse.

To fix it let's simply sub EntityCollectionServiceElementsFactory.

describe('PatientService', () => {
  let service: PatientService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        PatientService,
        {
          provide: EntityCollectionServiceElementsFactory,
          // our stub
          useValue: {
            methodsToFake: jasmine.createSpy(),
            // ....
          },
        },
      ],
    });
    service = TestBed.inject(PatientService);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });
});

Also to avoid the pain of mocking dependencies and its methods in future you can use ng-mocks. Then the test could looks like that:

describe('PatientService', () => {
  let service: PatientService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        PatientService,
        {
          provide: EntityCollectionServiceElementsFactory,
          useValue: MockService(EntityCollectionServiceElementsFactory),
        },
      ],
    });
    service = TestBed.inject(PatientService);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });
});


问:
Unable to save the docker image from jenkins
I am using Jenkins freestyle build job and my shell basically doing a simple job of pulling script from bitbucket and make the docker image but at the end, while I wanted to save the docker image in a .tar file .........that part is not working .....

am using following code:

```<code>#!/bin/bash

cd /var/lib/jenkins/workspace/component/image
c=`ls -lrt | tail -n1 |  awk -F'.' '{print $4}' | grep -o '[0-9]\+'`

TAG=`expr $c + 1`

cd ..

sed -i.bak s#__release__#$TAG# component.yaml

printf "Current tag - $TAG \n"
echo "Switching directory to COMPONENT"
pwd
ls -l
git branch -l
if [ -f $WORKSPACE/../CLEAN_BUILD_BFF ]; then
        echo "Doing a clean build"
        docker build --no-cache -t product:component.6.0.hotfix$TAG .

else
        echo "Doing a normal build"
        docker build -tproduct:component.6.0.hotfix$TAG .

fi

cd images

sudo -S docker save -o /home/ubuntu/test/scripts/images/dockerimage-name.tar dockerimage-name
</code>```

but the last part where I want to save the docker image is not working, the script is unable to save the image in a .tar format

getting the following error :

/tmp/jenkins5681348791736054100.sh: line 31: cd: images: No such file or directory
Finished: SUCCESS

答:
On the top, you are doing , where it's mentioned as image in the end

```<code>cd /var/lib/jenkins/workspace/component/image
</code>```

and in the end, you are doing , where it's images.

```<code>cd images
</code>```

Could be a typo mistake. If not, then please try the below way to save the image in tar format. And there are couple of other typos as well in the script.

```<code>if [ -f $WORKSPACE/../CLEAN_BUILD_BFF ]; then
        echo "Doing a clean build"
        docker build --no-cache -t product:component.6.0.hotfix$TAG .
        docker save product:component.6.0.hotfix$TAG > product:component.6.0.hotfix$TAG.tar

else
        echo "Doing a normal build"
        docker build -t product:component.6.0.hotfix$TAG .  #Typo changed
        docker save product:component.6.0.hotfix$TAG > product:component.6.0.hotfix$TAG.tar

fi

</code>```

Body:
I am using Jenkins freestyle build job and my shell basically doing a simple job of pulling script from bitbucket and make the docker image but at the end, while I wanted to save the docker image in a .tar file .........that part is not working .....

am using following code:

#!/bin/bash

cd /var/lib/jenkins/workspace/component/image
c=`ls -lrt | tail -n1 |  awk -F'.' '{print $4}' | grep -o '[0-9]\+'`

TAG=`expr $c + 1`

cd ..

sed -i.bak s#__release__#$TAG# component.yaml

printf "Current tag - $TAG \n"
echo "Switching directory to COMPONENT"
pwd
ls -l
git branch -l
if [ -f $WORKSPACE/../CLEAN_BUILD_BFF ]; then
        echo "Doing a clean build"
        docker build --no-cache -t product:component.6.0.hotfix$TAG .

else
        echo "Doing a normal build"
        docker build -tproduct:component.6.0.hotfix$TAG .

fi

cd images

sudo -S docker save -o /home/ubuntu/test/scripts/images/dockerimage-name.tar dockerimage-name

but the last part where I want to save the docker image is not working, the script is unable to save the image in a .tar format

getting the following error :

/tmp/jenkins5681348791736054100.sh: line 31: cd: images: No such file or directory
Finished: SUCCESS

Body:
On the top, you are doing , where it's mentioned as image in the end

cd /var/lib/jenkins/workspace/component/image

and in the end, you are doing , where it's images.

cd images

Could be a typo mistake. If not, then please try the below way to save the image in tar format. And there are couple of other typos as well in the script.

if [ -f $WORKSPACE/../CLEAN_BUILD_BFF ]; then
        echo "Doing a clean build"
        docker build --no-cache -t product:component.6.0.hotfix$TAG .
        docker save product:component.6.0.hotfix$TAG > product:component.6.0.hotfix$TAG.tar

else
        echo "Doing a normal build"
        docker build -t product:component.6.0.hotfix$TAG .  #Typo changed
        docker save product:component.6.0.hotfix$TAG > product:component.6.0.hotfix$TAG.tar

fi


问:
How to use elasticsearch library on python with elastic cloud?
Newbie to Rest API and elastic cloud here trying to post my json file in the elasticsearch so I can then index and see it in the kibana. So I read online of the library of elasticsearch and I followed its example basically to the letter. But yet I am getting a connection error when I try and run the thing. Now, the tutorial is refering to on-prem elastic and not cloud so I am guessing the authentication isn't the same for cloud and I should add the user and password somehow to this? Can anyone help me with that?

Do note,  when I try to use get I actually get the code 200 so communications should be fine

```<code>es = Elasticsearch([{'host': 'https:/cloudhosturl', 'port': 9243}])
    for i,line in enumerate(emails):
        for match in re.finditer(from_pat, line):
            ioc.append(match.group(1))
            es.index(index='senders', doc_type='addresses', id=k, body=json.dumps(match.group(1)))
</code>```

elasticsearch.exceptions.ConnectionError:
  ConnectionError(: Failed to establish a new connection: [Errno 11001]
  getaddrinfo failed) caused by:
  NewConnectionError(: Failed to establish a new connection: [Errno 11001]
  getaddrinfo failed)

答:
I'm using the snippet from https://elasticsearch-py.readthedocs.io/en/master/ it works for elastic cloud cluster.
It requires pip install elasticsearch

example:

```<code>es = Elasticsearch(
['https:/cloudhosturl'],
http_auth=('USERNAME', 'PASSWORD'),
scheme="https", port=443,)
</code>```

Body:
Newbie to Rest API and elastic cloud here trying to post my json file in the elasticsearch so I can then index and see it in the kibana. So I read online of the library of elasticsearch and I followed its example basically to the letter. But yet I am getting a connection error when I try and run the thing. Now, the tutorial is refering to on-prem elastic and not cloud so I am guessing the authentication isn't the same for cloud and I should add the user and password somehow to this? Can anyone help me with that?

Do note,  when I try to use get I actually get the code 200 so communications should be fine

es = Elasticsearch([{'host': 'https:/cloudhosturl', 'port': 9243}])
    for i,line in enumerate(emails):
        for match in re.finditer(from_pat, line):
            ioc.append(match.group(1))
            es.index(index='senders', doc_type='addresses', id=k, body=json.dumps(match.group(1)))

elasticsearch.exceptions.ConnectionError:
  ConnectionError(: Failed to establish a new connection: [Errno 11001]
  getaddrinfo failed) caused by:
  NewConnectionError(: Failed to establish a new connection: [Errno 11001]
  getaddrinfo failed)

Body:
I'm using the snippet from https://elasticsearch-py.readthedocs.io/en/master/ it works for elastic cloud cluster.
It requires pip install elasticsearch

example:

es = Elasticsearch(
['https:/cloudhosturl'],
http_auth=('USERNAME', 'PASSWORD'),
scheme="https", port=443,)


问:
Large json, store two fields in an array
I have a large json file that needs to have to "fields" merged in to an array in order to store to firestore.

Here a screenshot to show what I mean. What i have:

What I need:

As you can see GRP1D and GRP2D where merged in to an array. The json has 15000 entries so doing it manually is not an option

答:
Here is small code snippet using the spread operator</p>

```<code>const your_data = require("./your_data/ file/path");
const prepare_func = (your_data)=>{
  let temp = {...your_data,"GRP1D":[your_data["GRP1D"],your_data["GRP2D"]]};
  return temp;
}
let new_data = prepare_func(your_data);
</code>```

Body:
Here is small code snippet using the spread operator

const your_data = require("./your_data/ file/path");
const prepare_func = (your_data)=>{
  let temp = {...your_data,"GRP1D":[your_data["GRP1D"],your_data["GRP2D"]]};
  return temp;
}
let new_data = prepare_func(your_data);


问:
Trying to keep the same type after saving a dataframe in a csv file
When I try to get my dataframe out of the csv file the type of the data changed. Is there a way I can avoid this?

答:
csv files does not have a datatype definition header or something similar.
So when your read a csv pandas tries to guess the types and this can change the datatypes.
You have two possibile solutions:

Provide the datatype list when you do read_csv with dtype and parse_dates keywords (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html)

Use a different file format that store data with a schema (ex parquet)

for example:

```<code>import pandas as pd
date = pd.to_datetime('01-01-2020')

df=pd.DataFrame({'col1':[1,2,3,4],'col2':['a','b','b','d'],'col3':[date,date,date,date]})

print('original \n',df.dtypes)

df.to_csv('testtype.csv',index=False)
df_csv = pd.read_csv('testtype.csv')
print('simple csv read \n',df_csv.dtypes)

df_csv = pd.read_csv('testtype.csv')
print('csv datatypes \n',df_csv.dtypes)

df_csv = pd.read_csv('testtype.csv',parse_dates=[2])
print('csv with parse dates \n',df_csv.dtypes)

df.to_parquet('testtype.pqt')
df_pqt=pd.read_parquet('testtype.pqt')

print('parquet  \n',df_pqt.dtypes)
</code>```

that output:

```<code>original
 col1             int64
col2            object
col3    datetime64[ns]
dtype: object

simple csv read
 col1     int64
col2    object
col3    object
dtype: object

csv datatypes
 col1     int64
col2    object
col3    object
dtype: object

csv with parse dates
 col1             int64
col2            object
col3    datetime64[ns]
dtype: object

parquet
 col1             int64
col2            object
col3    datetime64[ns]
dtype: object
</code>```

Body:
csv files does not have a datatype definition header or something similar.
So when your read a csv pandas tries to guess the types and this can change the datatypes.
You have two possibile solutions:

Provide the datatype list when you do read_csv with dtype and parse_dates keywords (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html)

Use a different file format that store data with a schema (ex parquet)

for example:

import pandas as pd
date = pd.to_datetime('01-01-2020')

df=pd.DataFrame({'col1':[1,2,3,4],'col2':['a','b','b','d'],'col3':[date,date,date,date]})

print('original \n',df.dtypes)

df.to_csv('testtype.csv',index=False)
df_csv = pd.read_csv('testtype.csv')
print('simple csv read \n',df_csv.dtypes)

df_csv = pd.read_csv('testtype.csv')
print('csv datatypes \n',df_csv.dtypes)

df_csv = pd.read_csv('testtype.csv',parse_dates=[2])
print('csv with parse dates \n',df_csv.dtypes)

df.to_parquet('testtype.pqt')
df_pqt=pd.read_parquet('testtype.pqt')

print('parquet  \n',df_pqt.dtypes)

that output:

original
 col1             int64
col2            object
col3    datetime64[ns]
dtype: object

simple csv read
 col1     int64
col2    object
col3    object
dtype: object

csv datatypes
 col1     int64
col2    object
col3    object
dtype: object

csv with parse dates
 col1             int64
col2            object
col3    datetime64[ns]
dtype: object

parquet
 col1             int64
col2            object
col3    datetime64[ns]
dtype: object


问:
WPF- How to apply Style to Multiple controls within a Panel
I need to apply style to different controls within  a Stack Panel. They are all of different type i.e. TreeView,Listview,ComboBox etc.
Is there a way I can apply a style at StackPanel level to be applicable for these controls.
I don't want to apply style individually to these controls.
Is there any way to accomplish this?

Thanks..

答:
You can do it like this by declaring the Styles withing the StackPanel Resources. You have to declare each Style without a key for them to be automatically applied to every target control within the StackPanel.

<StackPanel>
     <StackPanel.Resources>

     </StackPanel.Resources>

     <TreeView />
</StackPanel>
```

Body:
You can do it like this by declaring the Styles withing the StackPanel Resources. You have to declare each Style without a key for them to be automatically applied to every target control within the StackPanel.

<StackPanel>
     <StackPanel.Resources>
      <!-- Styles declared here will be scoped to the content of the stackpanel  -->

      <!-- This is the example of style declared without a key, it will be applied to every TreeView. Of course you'll have to add Setters etc -->
      <Style TargetType="TreeView">
      </Style>
     </StackPanel.Resources>

     <!-- Content -->

     <!-- This treeview will have the style declared within the StackPanel Resources applied to it-->
     <TreeView />
</StackPanel>


问:
where to locate android emulator.zip downloaded by browser?
Im having problems downloading Android Studio for 32 bit (AS version 3.6.3). It stopped in:

```<code>  Preparing "Install Android Emulator (revision: 28.0.25)".
  Downloading https://dl.google.com/android/repository/emulator-windows-5395263.zip
  JavaexceptionSomething....
</code>```

Then I decided to paste that url in chrome browser and it downloaded it. I have it now in download files in my laptop. I downloaded the next .zip

```<code>   https://dl.google.com/android/repository/emulator-windows-5395263.zip
</code>```

I want to know...where Im supposed to paste that .zip file in order to make work Android Studio? Otherwise it appears an alert

```<code>Your Android SDK is missing, out of date or corrupted.
</code>```

then when trying to follow some tutorials,

```<code>  Open SDK Manager > Android SDK > Edit > Next > Next... it doesnt download this same zip file. It keep me awaiting indefinitely...
</code>```

Where should I paste this file in order to make Android Studio work?

thank you.

答:
I have now successfully installed Android Studio 3.6.3 32-bit in a 32-bit Windows 10 virtual machine. Apart from needing to increase the disk-size that I had initially allocated, I had no installation problems other than that the Intel HAXM component refused to install (probably because it does not like a 32-bit system). The emulator also installed successfully, so I could not reproduce your problem. I can only think that you do not have enough disk space. In my experience, Android Studio with a couple of emulators needs several 10's GB of free space.

I suggest that you check how much free space you have and then try removing and reinstalling Android Studio.

When it comes to which emulator to use, you should use an ARM emulator and not an -86 emulator (they do not seem to work in a 32-bit environment).

I do not know how old your computer is, but you should seriously consider upgrading to a 64-bit operating system. Everything is now targeted to 64-bit architectures.

Body:
Im having problems downloading Android Studio for 32 bit (AS version 3.6.3). It stopped in:

  Preparing "Install Android Emulator (revision: 28.0.25)".
  Downloading https://dl.google.com/android/repository/emulator-windows-5395263.zip
  JavaexceptionSomething....

Then I decided to paste that url in chrome browser and it downloaded it. I have it now in download files in my laptop. I downloaded the next .zip

   https://dl.google.com/android/repository/emulator-windows-5395263.zip

I want to know...where Im supposed to paste that .zip file in order to make work Android Studio? Otherwise it appears an alert

Your Android SDK is missing, out of date or corrupted.

then when trying to follow some tutorials,

  Open SDK Manager > Android SDK > Edit > Next > Next... it doesnt download this same zip file. It keep me awaiting indefinitely...

Where should I paste this file in order to make Android Studio work?

thank you.


问:
TypeError: Cannot read property 'state' of undefined, even though already binded
im trying to print a state in my reactjs web page, i already bind the function just like the other answer says but it still gave me the same error, here is my code

```<code>export class Tambah extends React.Component{
  constructor(){
    super();
    this.add = this.add.bind(this);
  }

  add(event){
    this.setState({company: event.target.value})
  }
}

function FormTambah(){
  return(
    <div className="konten container-sm">
    <br></br><br></br>
    <div className="tabel card rounded">
      <div className="card-body">
      <p className="head panel-body">Add User</p>
      <br/><br/>
      <form>
        <p>Email*</p>
        <input type="text" value={this.state.company} onChange={this.add} className="email form-control col-sm-6"/>
        <br/>
        <p>Full Name*</p>
        <input type="text" className="email form-control col-sm-7" placeholder="Enter Fullname" onChange={this.FullName}></input>
        <br/>
        <div className="stat custom-control custom-switch">
          <input type="checkbox" className="custom-control-input switch-lg" id="customSwitch1"/>
          <label className="custom-control-label" for="customSwitch1">Active Status</label>
        </div>
        <br/>
        <button type="submit" className="submit btn col-sm-1">Save</button>
      </form>
    </div>
      </div>
    </div>
  )
}
</code>```

the error happens right here :

```<code><input type="text" value={this.state.company} onChange={this.add} className="email form-control col-sm-6"/>
</code>```

i already bind the add method after i saw the other question but it still gave me the same error, thanks before, any help will be appreciated

答:
state is available in class components not function components.

also beside react, what you're doing is not legal in JS, you're defining state in one class and try to use it in a different function that is not belong to that class.

what you want to do is move the code in FormTambah function to render function in the class component

```<code>export class Tambah extends React.Component{
  constructor(){
    super();
    this.add = this.add.bind(this);
  }

  add(event){
    this.setState({company: event.target.value})
  }

  render(){
  return(
    <div className="konten container-sm">
    <br></br><br></br>
    <div className="tabel card rounded">
      <div className="card-body">
      <p className="head panel-body">Add User</p>
      <br/><br/>
      <form>
        <p>Email*</p>
        <input type="text" value={this.state.company} onChange={this.add} className="email form-control col-sm-6"/>
        <br/>
        <p>Full Name*</p>
        <input type="text" className="email form-control col-sm-7" placeholder="Enter Fullname" onChange={this.FullName}></input>
        <br/>
        <div className="stat custom-control custom-switch">
          <input type="checkbox" className="custom-control-input switch-lg" id="customSwitch1"/>
          <label className="custom-control-label" for="customSwitch1">Active Status</label>
        </div>
        <br/>
        <button type="submit" className="submit btn col-sm-1">Save</button>
      </form>
    </div>
      </div>
    </div>
  )
  }

}
</code>```

Body:
im trying to print a state in my reactjs web page, i already bind the function just like the other answer says but it still gave me the same error, here is my code

export class Tambah extends React.Component{
  constructor(){
    super();
    this.add = this.add.bind(this);
  }

  add(event){
    this.setState({company: event.target.value})
  }
}

function FormTambah(){
  return(

Add User

      <form>

Email*

        <input type="text" value={this.state.company} onChange={this.add} className="email form-control col-sm-6"/>

Full Name*

        <input type="text" className="email form-control col-sm-7" placeholder="Enter Fullname" onChange={this.FullName}></input>

          <input type="checkbox" className="custom-control-input switch-lg" id="customSwitch1"/>
          Active Status

        <button type="submit" className="submit btn col-sm-1">Save</button>
      </form>

  )
}

the error happens right here :

<input type="text" value={this.state.company} onChange={this.add} className="email form-control col-sm-6"/>

i already bind the add method after i saw the other question but it still gave me the same error, thanks before, any help will be appreciated

Body:
state is available in class components not function components.

also beside react, what you're doing is not legal in JS, you're defining state in one class and try to use it in a different function that is not belong to that class.

what you want to do is move the code in FormTambah function to render function in the class component

export class Tambah extends React.Component{
  constructor(){
    super();
    this.add = this.add.bind(this);
  }

  add(event){
    this.setState({company: event.target.value})
  }

  render(){
  return(
    <div className="konten container-sm">
    <br></br><br></br>
    <div className="tabel card rounded">
      <div className="card-body">
      <p className="head panel-body">Add User</p>
      <br/><br/>
      <form>
        <p>Email*</p>
        <input type="text" value={this.state.company} onChange={this.add} className="email form-control col-sm-6"/>
        <br/>
        <p>Full Name*</p>
        <input type="text" className="email form-control col-sm-7" placeholder="Enter Fullname" onChange={this.FullName}></input>
        <br/>
        <div className="stat custom-control custom-switch">
          <input type="checkbox" className="custom-control-input switch-lg" id="customSwitch1"/>
          <label className="custom-control-label" for="customSwitch1">Active Status</label>
        </div>
        <br/>
        <button type="submit" className="submit btn col-sm-1">Save</button>
      </form>
    </div>
      </div>
    </div>
  )
  }

}


问:
How to get IntelliSense to reliably work in Visual Studio 2008
Does anyone know how to get IntelliSense to work reliably when working in C/C++ projects? It seems to work for about 1 in 10 files. Visual Studio 2005 seems to be a lot better than 2008.

Edit: Whilst not necessarily a solution, the work-around provided here:

How to get IntelliSense to reliably work in Visual Studio 2008

Is probably the best bet if I want a decent IntelliSense system.

答:
I had a very annoying problem, intellisense was working only in some files, without any evident reason... it took me a couple of hours of digging through google, but I finally understood that the reason was indeed recursive reference!
I was using the:

```<code>#ifndef CLASS_H
#define CLASS_H
...
#endif
</code>```

to avoid redefinition of symbols, and this sometimes breaks intellisense in big projects.

But it is enough to comment the ifndef-define-endif and put a:

```<code>#pragma once
</code>```

at the beginning of the header files to still avoid redefinitions and have Intellisense working again =)=)

At least, this worked for me, hope it's useful...

Cheers
Francesco

OwnerDisplayName: Mark Ingram

LastEditorDisplayName: hop

Body:
I had a very annoying problem, intellisense was working only in some files, without any evident reason... it took me a couple of hours of digging through google, but I finally understood that the reason was indeed recursive reference!
I was using the:

#ifndef CLASS_H
#define CLASS_H
...
#endif

to avoid redefinition of symbols, and this sometimes breaks intellisense in big projects.

But it is enough to comment the ifndef-define-endif and put a:

#pragma once

at the beginning of the header files to still avoid redefinitions and have Intellisense working again =)=)

At least, this worked for me, hope it's useful...

Cheers
Francesco


答: I played around and changing the format to png solved the problem.  Sorry for the unnecessary post.</p>

Title: Converting Image to Bytes and back

Body:
I know there is a lot of help already about this subject, but using this help I ran into a problem: I have an image list with icons that I display in a tree view on a windows form and that works.

Now I want to take these icons, put them in a table, clear the image list and then load the image list from the table.  This is to test if I can use a table to maintain the icons.

The problem is that the icons display a black background using this method. I use BytesFromImage to write to an Image column in the table and ImageFromStream and StreamFromBytes to read the data back to an image.

What am I missing?

public static byte[] BytesFromImage(Image TheImage)
{
    MemoryStream ms = new MemoryStream();
    TheImage.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
    return ms.ToArray();
}

public static Stream StreamFromBytes(byte[] DataBytes)
{
    MemoryStream stream = new MemoryStream();
    stream.Write(DataBytes, 0, DataBytes.Length);
    stream.Seek(0, SeekOrigin.Begin);
    return stream;
}

public static Image ImageFromStream(Stream DataStream)
{
    return Bitmap.FromStream(DataStream);
}


问:
How to Save set image of PickedFile type to a image in Flutter?
I want to set get image from the camera and set it to the following code:

```<code>image: DecorationImage(image: FileImage(file),
</code>```

So I did this:

```<code>File file = await ImagePicker.pickImage(
  source: ImageSource.camera,
);
</code>```

Now above code works fine for now, but 'pickImage' is deprecated and we should use imagePicker.getImage() method instead.

So I used imagePicker.getImage() instead:

```<code>PickedFile file = await ImagePicker().getImage(
  source: ImageSource.camera,
);
</code>```

But when I try to set this file to the following image type, it doesn't work

```<code>image: DecorationImage(image: FileImage(file),)
</code>```

How to solve this issue?

答:
You need to use path property of picked file    </p>

```<code>image: DecorationImage(image: FileImage(File(file.path)),)
</code>```

Body:
I want to set get image from the camera and set it to the following code:

image: DecorationImage(image: FileImage(file),

So I did this:

File file = await ImagePicker.pickImage(
  source: ImageSource.camera,
);

Now above code works fine for now, but 'pickImage' is deprecated and we should use imagePicker.getImage() method instead.

So I used imagePicker.getImage() instead:

PickedFile file = await ImagePicker().getImage(
  source: ImageSource.camera,
);

But when I try to set this file to the following image type, it doesn't work

image: DecorationImage(image: FileImage(file),)

How to solve this issue?

Body:
You need to use path property of picked file

image: DecorationImage(image: FileImage(File(file.path)),)


问:
Looking for a way to check all possible combinations of four dice in python
I have a single list (or iterable, I'm quite new to Python so I don't know what the difference is) that contains four integer elements, each element ranging from 1 to 6, including 6. My program is essentially a dice game that checks for a lot of different conditions and I'm not entirely sure if all of them work correctly.

I want to check for every possible combination of dice in order to debug the program.

Example: first loop [1, 1, 1, 1] -> second loop [1, 1, 1, 2] ---> seventh loop [1, 1, 2, 1]

答:
You may use itertools.product

You already have the list of values

```<code>values = [list(range(1, 7)) for _ in range(4)]
res = product(*values) # * to flatten and pass the 4 dices as separate parameters
print(list(res))
</code>```

Directly pass one dice values, and specify that you have 4 dices

```<code>res = product(range(1, 7), repeat=4)
print(list(res))
</code>```

Both will give you

```<code>[(1, 1, 1, 1), (1, 1, 1, 2), (1, 1, 1, 3), (1, 1, 1, 4), (1, 1, 1, 5), (1, 1, 1, 6),
 (1, 1, 2, 1), (1, 1, 2, 2), ...
 (6, 6, 6, 1), (6, 6, 6, 2), (6, 6, 6, 3), (6, 6, 6, 4), (6, 6, 6, 5), (6, 6, 6, 6)]
</code>```

Body:
You may use itertools.product

You already have the list of values

values = [list(range(1, 7)) for _ in range(4)]
res = product(*values) # * to flatten and pass the 4 dices as separate parameters
print(list(res))

Directly pass one dice values, and specify that you have 4 dices

res = product(range(1, 7), repeat=4)
print(list(res))

Both will give you

[(1, 1, 1, 1), (1, 1, 1, 2), (1, 1, 1, 3), (1, 1, 1, 4), (1, 1, 1, 5), (1, 1, 1, 6),
 (1, 1, 2, 1), (1, 1, 2, 2), ...
 (6, 6, 6, 1), (6, 6, 6, 2), (6, 6, 6, 3), (6, 6, 6, 4), (6, 6, 6, 5), (6, 6, 6, 6)]


问:
Efficient ways for whitelisting more tables in Debezium Mysql Connector
Are there any best practices that are followed for whitelisting a new table to the debezium mysql connector ?

We are using debezium mysql connector for our CDC flows and a use case has arised to whitelist more tables to the connector configuration. Here are the version details of the debezium being used and the

```<code>{
    "class": "io.debezium.connector.mysql.MySqlConnector",
    "version": "0.8.0.Final",
    "snapshot.mode": "schema_only"
}

</code>```

There is a debezium ticket https://issues.redhat.com/browse/DBZ-906 which indicates to run the connector in

```<code>"snapshot.mode": "schema_only_recover"
</code>```

mode and to recreate the history topic before restarting the connector. I had a couple of questions regarding this approach

 Is this option available for the above mentioned version as well ?

 How can I get the updates to the new table made before the table was whitelisted ?

答:
first of all, pleas eupgrade Debezium as version 0.8.0 is very old.

Generally there are multiple approaches to solving your issue but if you can afford a pause in streaming than I'd recommend to
1) Stop the current connector
2) Start a new connector with whitelisted new table to execute the snapshot on it
3) When snapshot is completed then start the original connector with updated whitelist table list

See for example https://groups.google.com/forum/?fromgroups=#!msg/debezium/Iw4BgLZ8Mq4/SZBLGwEaAQAJ;context-place=forum/debezium for exact details

If you cannot afford the downtime then please check the experimental approach introduced in DBZ-175

Body:
Are there any best practices that are followed for whitelisting a new table to the debezium mysql connector ?

We are using debezium mysql connector for our CDC flows and a use case has arised to whitelist more tables to the connector configuration. Here are the version details of the debezium being used and the

{
    "class": "io.debezium.connector.mysql.MySqlConnector",
    "version": "0.8.0.Final",
    "snapshot.mode": "schema_only"
}

There is a debezium ticket https://issues.redhat.com/browse/DBZ-906 which indicates to run the connector in

"snapshot.mode": "schema_only_recover"

mode and to recreate the history topic before restarting the connector. I had a couple of questions regarding this approach

 Is this option available for the above mentioned version as well ?

 How can I get the updates to the new table made before the table was whitelisted ?


问:
PIL.UnidentifiedImageError: cannot identify image file 'image-playground/.DS_Store'
```<code>**The error says**
  "cannot identify image file %r" % (filename if filename else fp)
PIL.UnidentifiedImageError: cannot identify image file 'image-playground/.DS_Store'
</code>```

The above error constantly shows up when i run this code, please help with the solution

```<code>**while running the code**
import sys
import os
from PIL import Image

image_folder = sys.argv[1]
output_folder = sys.argv[2]

if not os.path.exists(output_folder):
    os.makedirs(output_folder)

for filename in os.listdir(image_folder):
    img= Image.open(f'{image_folder}{filename}')
    img.save(f'{output_folder}{filename}', 'png')
    print ('all done!')
</code>```

答:
The error is because you are trying to open a non-image file with Image.open().

If your goal is to move the file from one folder to another then I would suggest you use

```<code>os.rename(SourceFileName,TargetFileName)
</code>```

If not, consider filtering your input file before calling Image.open to specific extensions that you would like to access, say like:-

```<code>ext=['jpg','png','gif']
for filename in os.listdir(image_folder):
    if filename[-3:] in ext:
        img= Image.open(f'{image_folder}{filename}')
        img.save(f'{output_folder}{filename}', 'png')
    print ('all done!')
</code>```

Hope that helps

Body:
**The error says**
  "cannot identify image file %r" % (filename if filename else fp)
PIL.UnidentifiedImageError: cannot identify image file 'image-playground/.DS_Store'

The above error constantly shows up when i run this code, please help with the solution

**while running the code**
import sys
import os
from PIL import Image

image_folder = sys.argv[1]
output_folder = sys.argv[2]

if not os.path.exists(output_folder):
    os.makedirs(output_folder)

for filename in os.listdir(image_folder):
    img= Image.open(f'{image_folder}{filename}')
    img.save(f'{output_folder}{filename}', 'png')
    print ('all done!')

Body:
The error is because you are trying to open a non-image file with Image.open().

If your goal is to move the file from one folder to another then I would suggest you use

os.rename(SourceFileName,TargetFileName)

If not, consider filtering your input file before calling Image.open to specific extensions that you would like to access, say like:-

ext=['jpg','png','gif']
for filename in os.listdir(image_folder):
    if filename[-3:] in ext:
        img= Image.open(f'{image_folder}{filename}')
        img.save(f'{output_folder}{filename}', 'png')
    print ('all done!')

Hope that helps


问:
Android : Border only on corners
In my android app, I need border only on four corners as shown in fig (white colored).

```<code>    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="6">
        <VideoView
            android:id="@+id/video1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_gravity="center" />
        <View
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:layout_centerInParent="true"
            android:background="@drawable/cornerbg" />
    </RelativeLayout>
</code>```

cornerbg.xml

```<code>        <?xml version="1.0" encoding="utf-8"?>
        <layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

        <item>
            <shape android:shape="rectangle" >
                <solid android:color="@color/transparent" />
                <stroke
                    android:width="1dp"
                    android:color="@color/btn_border"
                    android:dashWidth="50dp" // I tried this but not getting expected
                    android:dashGap="60dp"/>

            </shape>
        </item>
        </layer-list>
</code>```

How can I write xml for this?

Please help,
Thanks

答:
Below is the drawable that doesn't depends on the width and height of the rectangle, you can use this drawable for portrait and landscape. Please adjust the width and height of the border : </p>

```<code><layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:width="8dp"
        android:height="48dp"
        android:gravity="top|left">
        <shape android:shape="rectangle">
            <solid android:color="#FFFFFF" />
        </shape>
    </item>
    <item
        android:width="48dp"
        android:height="8dp"
        android:gravity="top|left">
        <shape android:shape="rectangle">
            <solid android:color="#FFFFFF" />
        </shape>
    </item>
    <item
        android:width="8dp"
        android:height="48dp"
        android:gravity="top|right">
        <shape android:shape="rectangle">
            <solid android:color="#FFFFFF" />
        </shape>
    </item>
    <item
        android:width="48dp"
        android:height="8dp"
        android:gravity="top|right">
        <shape android:shape="rectangle">
            <solid android:color="#FFFFFF" />
        </shape>
    </item>
    <item
        android:width="8dp"
        android:height="48dp"
        android:gravity="bottom|left">
        <shape android:shape="rectangle">
            <solid android:color="#FFFFFF" />
        </shape>
    </item>
    <item
        android:width="48dp"
        android:height="8dp"
        android:gravity="bottom|left">
        <shape android:shape="rectangle">
            <solid android:color="#FFFFFF" />
        </shape>
    </item>
    <item
        android:width="8dp"
        android:height="48dp"
        android:gravity="bottom|right">
        <shape android:shape="rectangle">
            <solid android:color="#FFFFFF" />
        </shape>
    </item>
    <item
        android:width="48dp"
        android:height="8dp"
        android:gravity="bottom|right">
        <shape android:shape="rectangle">
            <solid android:color="#FFFFFF" />
        </shape>
    </item>
</layer-list>
</code>```

Title: Android : Border only on corners

Body:
In my android app, I need border only on four corners as shown in fig (white colored).

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="6">
        <VideoView
            android:id="@+id/video1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_gravity="center" />
        <View
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:layout_centerInParent="true"
            android:background="@drawable/cornerbg" />
    </RelativeLayout>

cornerbg.xml

        <?xml version="1.0" encoding="utf-8"?>
        <layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

        <item>
            <shape android:shape="rectangle" >
                <solid android:color="@color/transparent" />
                <stroke
                    android:width="1dp"
                    android:color="@color/btn_border"
                    android:dashWidth="50dp" // I tried this but not getting expected
                    android:dashGap="60dp"/>

            </shape>
        </item>
        </layer-list>

How can I write xml for this?

Please help,
Thanks

Body:
Below is the drawable that doesn't depends on the width and height of the rectangle, you can use this drawable for portrait and landscape. Please adjust the width and height of the border :

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:width="8dp"
        android:height="48dp"
        android:gravity="top|left">
        <shape android:shape="rectangle">
            <solid android:color="#FFFFFF" />
        </shape>
    </item>
    <item
        android:width="48dp"
        android:height="8dp"
        android:gravity="top|left">
        <shape android:shape="rectangle">
            <solid android:color="#FFFFFF" />
        </shape>
    </item>
    <item
        android:width="8dp"
        android:height="48dp"
        android:gravity="top|right">
        <shape android:shape="rectangle">
            <solid android:color="#FFFFFF" />
        </shape>
    </item>
    <item
        android:width="48dp"
        android:height="8dp"
        android:gravity="top|right">
        <shape android:shape="rectangle">
            <solid android:color="#FFFFFF" />
        </shape>
    </item>
    <item
        android:width="8dp"
        android:height="48dp"
        android:gravity="bottom|left">
        <shape android:shape="rectangle">
            <solid android:color="#FFFFFF" />
        </shape>
    </item>
    <item
        android:width="48dp"
        android:height="8dp"
        android:gravity="bottom|left">
        <shape android:shape="rectangle">
            <solid android:color="#FFFFFF" />
        </shape>
    </item>
    <item
        android:width="8dp"
        android:height="48dp"
        android:gravity="bottom|right">
        <shape android:shape="rectangle">
            <solid android:color="#FFFFFF" />
        </shape>
    </item>
    <item
        android:width="48dp"
        android:height="8dp"
        android:gravity="bottom|right">
        <shape android:shape="rectangle">
            <solid android:color="#FFFFFF" />
        </shape>
    </item>
</layer-list>


问:
How to create a column 'mapping' that still works in SQL queries?
I have a very simple model as below:

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), index=True)
    role = db.Column(db.String(64))
```

<p>and then a simple query that I'm using in my view to filter users by roles:</p>

```roles = list(map(str, query_params.get('roles', [])))
User.query.filter(User.role.in_(roles))
```

<p>Roles start with a capital letter ('Director', 'Manager', etc...) and I want to add a mapping to the column which returns it in lower case.
I thought <code>column_property()</code> or <code>@hybrid_property</code> would do the job but I'm either wrong, or I'm making a mistake in the implementation.</p>

<p>I tried these changes:</p>

```@hybrid_property
def role_tag(self):
    return self.role.lower()

User.query.filter(User.role_tag.in_(roles))
```

<p>The property indeed returns the lower case value, but it doesn't work in the query raising this exception:</p>

<p><code>AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with User.profile_role has an attribute 'lower'</code></p>

<p>I then tried to change the model as such:</p>

```role_tag = column_property(role.lower())
```

which instead raise another exception on the Model directly.

AttributeError: Neither 'Column' object nor 'Comparator' object has an attribute 'lower'

I understand the issue is related to how they operate, if at class or instance level... But in the end I haven't been able to find the correct implementation for my use case.

答:
The solution is to define the behaviour separately for instance and class context, or Python and SQL context:</p>

```<code>class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), index=True)
    role = db.Column(db.String(64))

    @hybrid_property
    def role_tag(self):
        return self.role.lower()

    @role_tag.expression
    def role_tag(cls):
        return db.func.lower(cls.role)
</code>```

Body:
I have a very simple model as below:

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), index=True)
    role = db.Column(db.String(64))

and then a simple query that I'm using in my view to filter users by roles:

roles = list(map(str, query_params.get('roles', [])))
User.query.filter(User.role.in_(roles))

Roles start with a capital letter ('Director', 'Manager', etc...) and I want to add a mapping to the column which returns it in lower case.
I thought column_property() or @hybrid_property would do the job but I'm either wrong, or I'm making a mistake in the implementation.

I tried these changes:

@hybrid_property
def role_tag(self):
    return self.role.lower()

User.query.filter(User.role_tag.in_(roles))

The property indeed returns the lower case value, but it doesn't work in the query raising this exception:

AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with User.profile_role has an attribute 'lower'

I then tried to change the model as such:

role_tag = column_property(role.lower())

which instead raise another exception on the Model directly.

AttributeError: Neither 'Column' object nor 'Comparator' object has an attribute 'lower'

I understand the issue is related to how they operate, if at class or instance level... But in the end I haven't been able to find the correct implementation for my use case.

Body:
The solution is to define the behaviour separately for instance and class context, or Python and SQL context:

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), index=True)
    role = db.Column(db.String(64))

    @hybrid_property
    def role_tag(self):
        return self.role.lower()

    @role_tag.expression
    def role_tag(cls):
        return db.func.lower(cls.role)