问:
Google Sheets: ArrayFormula Conditional Calculations across Rows
struggling to find a way to perform a calculation taking a look at a previous row in an Arrayformula. Perhaps it isn't possible the way I'm attempting to do it?

Sample Columns:

Time/Date Conversion
In/Out
Hours

February 9, 2022 11:57PM
In

February 10, 2022 07:47AM
Out

February 10, 2022 11:28PM
In

February 11, 2022 08:40AM
Out

I'm able to use an arrayformula to determine if the row shows "Out"; and I know how to calculate the time difference between the date/times; but I can't seem to do the two in combo.

Resulting hours would appear in the Hours column when the In/Out row shows "Out."

BTW - Yes, this would be much easier if the In and the Out times were in the same row, but the software that auto-adds these to the spreadsheet doesn't do that (and doesn't even add them as a real date and time, so I had to use some funky regex to accomplish that. Good times!)

Thanks for your ideas, as always!

CTO

答:
solution:

Try in C1 (format duration)

```<code>={"Hours";ARRAYFORMULA(if(B2:B="In",,if(A2:A="",,mmult(-1*(ROW(A2:A)=TRANSPOSE(ROW(A2:A)+1))+1*(ROW(A2:A)=TRANSPOSE(ROW(A2:A))),if(A2:A="",0,A2:A)))))}
</code>```

reference:

mmult

explanation:

mmult between a matrix of -1/0/1 as follows and the data

```<code>=arrayformula(-1*(ROW(A2:A9)=TRANSPOSE(ROW(A2:A9)+1))+1*(ROW(A2:A9)=TRANSPOSE(ROW(A2:A9))))
</code>```

Body:
solution:

Try in C1 (format duration)

={"Hours";ARRAYFORMULA(if(B2:B="In",,if(A2:A="",,mmult(-1*(ROW(A2:A)=TRANSPOSE(ROW(A2:A)+1))+1*(ROW(A2:A)=TRANSPOSE(ROW(A2:A))),if(A2:A="",0,A2:A)))))}

reference:

mmult

explanation:

mmult between a matrix of -1/0/1 as follows and the data

=arrayformula(-1*(ROW(A2:A9)=TRANSPOSE(ROW(A2:A9)+1))+1*(ROW(A2:A9)=TRANSPOSE(ROW(A2:A9))))


来源: stackexchange

问:
Edit Text doesn't wrap around content in Android Studio
I've this simple bit of xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/cost_of_service"
        android:layout_width="160dp"
        android:layout_height="wrap_content"
        android:inputType="numberDecimal"

        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

It seems that the EditText does not wrap itself horizontally even though the layout_height is set to "wrap content". Could anybody tell me why this is occurring? Sorry if this might seem like a dumb question, I'm quite new to android.

答:
I think that you want the edit text to adjust its size according to the text given by the user, in the code you have set the width to be fixed and you have used plain text not multiline so if the users input the text and the length of the text crosses 16d0dp so the text will start moving behind and you don't want this that is why you set the height to wrap content,
just use multiline text instead. Your problem will be solved.</p>

ContentLicense: CC BY-SA 4.0

Body:
I've this simple bit of xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/cost_of_service"
        android:layout_width="160dp"
        android:layout_height="wrap_content"
        android:inputType="numberDecimal"

        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

It seems that the EditText does not wrap itself horizontally even though the layout_height is set to "wrap content". Could anybody tell me why this is occurring? Sorry if this might seem like a dumb question, I'm quite new to android.


问:
Subtract hour using "Singapore Standard Time" timezone
```<code>select (convert(datetime ,SWITCHOFFSET(CONVERT(datetimeoffset, '2022-02-11 11:15:00.000'),
   (select current_utc_offset FROM sys.time_zone_info where name ='Singapore Standard Time')
))) CurrentTime
</code>```

How can I achieve below expected result ?

Current Result:

```<code>CurrentTime
-----------------------
2022-02-11 19:15:00.000
</code>```

Expecting Result:

```<code>CurrentTime
-----------------------
2022-02-11 03:15:00.000
</code>```

PS: I can't use -8 or -08:00 in the script.

答:
The offsets in sys.time_zone_info are those to switch from UTC+00:00 to another timezone.

So for "Singapore Standard Time" that's +08:00

But the sign can be changed if it needs to switch to UTC timezone.

```<code>SELECT (CONVERT(DATETIME,
           SWITCHOFFSET(CONVERT(DATETIME, '2022-02-11 11:15:00.000'),
             (SELECT TRANSLATE(CURRENT_UTC_OFFSET,'+-','-+') FROM sys.time_zone_info WHERE name ='Singapore Standard Time')
     ))) AS CurrentTime
</code>```

Better is to use the AT TIME ZONE syntax :

```<code>SELECT
  CONVERT(DATETIME, (CONVERT(DATETIME, '2022-02-11 11:15:00.000')
          AT TIME ZONE 'Singapore Standard Time'
          AT TIME ZONE 'UTC')) AS CurrentTime
</code>```

Both methods will return the same :

CurrentTime

2022-02-11 03:15:00.000

Body:
select (convert(datetime ,SWITCHOFFSET(CONVERT(datetimeoffset, '2022-02-11 11:15:00.000'),
   (select current_utc_offset FROM sys.time_zone_info where name ='Singapore Standard Time')
))) CurrentTime

How can I achieve below expected result ?

Current Result:

CurrentTime
-----------------------
2022-02-11 19:15:00.000

Expecting Result:

CurrentTime
-----------------------
2022-02-11 03:15:00.000

PS: I can't use -8 or -08:00 in the script.

Body:
The offsets in sys.time_zone_info are those to switch from UTC+00:00 to another timezone.

So for "Singapore Standard Time" that's +08:00

But the sign can be changed if it needs to switch to UTC timezone.

SELECT (CONVERT(DATETIME,
           SWITCHOFFSET(CONVERT(DATETIME, '2022-02-11 11:15:00.000'),
             (SELECT TRANSLATE(CURRENT_UTC_OFFSET,'+-','-+') FROM sys.time_zone_info WHERE name ='Singapore Standard Time')
     ))) AS CurrentTime

Better is to use the AT TIME ZONE syntax :

SELECT
  CONVERT(DATETIME, (CONVERT(DATETIME, '2022-02-11 11:15:00.000')
          AT TIME ZONE 'Singapore Standard Time'
          AT TIME ZONE 'UTC')) AS CurrentTime

Both methods will return the same :

CurrentTime

2022-02-11 03:15:00.000


问:
c++ test if random number is positive or negative
I have school work with C++ and Im new to it. I have to generate 17 random numbers and then test if they are positive/negative/equal to zero. I can't seem to find a way to take the random generated number from the for loop to test it in the if/else if loop. Heeeeelp please :D (The b variable is just there from tests)</p>
```<code>#include <ctime>
using namespace std;
int main() {

    srand(
          (unsigned) time(0)
    );

    int a;
    int b;
    int num;

    for(int a = 0; a<17; a++) {
        cout << "Skaitlis: " << rand()% 20 + -10 << "\n";

        if(b > 0){
            cout << b << " is a positive number." << endl;
        }
        else if (b == 0){
            cout << b << " is equal to zero." << endl;
        }
        else {
            cout << b << " is a negative number." << endl;
        }
   }
}
</code>```

答:
Easy enough, first assign the value to b, so you can then compare it. The current cout just outputs it.</p>
```<code>b = rand()% 20 - 10;
cout << "Skaitlis: " << b << "\n";
</code>```

Body:
I have school work with C++ and Im new to it. I have to generate 17 random numbers and then test if they are positive/negative/equal to zero. I can't seem to find a way to take the random generated number from the for loop to test it in the if/else if loop. Heeeeelp please :D (The b variable is just there from tests)

#include <ctime>
using namespace std;
int main() {

    srand(
          (unsigned) time(0)
    );

    int a;
    int b;
    int num;

    for(int a = 0; a<17; a++) {
        cout << "Skaitlis: " << rand()% 20 + -10 << "\n";

        if(b > 0){
            cout << b << " is a positive number." << endl;
        }
        else if (b == 0){
            cout << b << " is equal to zero." << endl;
        }
        else {
            cout << b << " is a negative number." << endl;
        }
   }
}

Body:
Easy enough, first assign the value to b, so you can then compare it. The current cout just outputs it.

b = rand()% 20 - 10;
cout << "Skaitlis: " << b << "\n";


问:
Is possible to get the last string of an url as a param?
I cant get it with javascript URLSearchParams  function because it needs the "?" before.

Its possible to get the last string after last slash of an URL?

```<code>For ex:
mydomain.com/hello
mydomain.com/otherExample
</code>```

I need that "hello" be the param and stay in the index of my domain with the "param" value assigned to a var? Note that the "hello" page or directory doesn't exists.

Maybe is possible to manage it with the 404 error redirection?

答:
You should be able to retrieve it with the following Javascript:</p>
```<code>let parts = window.location.pathname.split('/');
let path = parts[parts.length - 1];
</code>```

Body:
I cant get it with javascript URLSearchParams  function because it needs the "?" before.

Its possible to get the last string after last slash of an URL?

For ex:
mydomain.com/hello
mydomain.com/otherExample

I need that "hello" be the param and stay in the index of my domain with the "param" value assigned to a var? Note that the "hello" page or directory doesn't exists.

Maybe is possible to manage it with the 404 error redirection?

Body:
You should be able to retrieve it with the following Javascript:

let parts = window.location.pathname.split('/');
let path = parts[parts.length - 1];


问:
How we can filter the listview when typing in EditText?
I have a ListView and a EditText. I want to be search the name from listview when I type the name in EditText.

Please tell me.

Thanx in advance...!!!

答: You can listen for text changes in EditText and run search on every change (I suggest to set a timeout)</p>

ContentLicense: CC BY-SA 3.0


问:
How to restrict two dots in flutter?
I need to restrict when the user types 1.. like this. i'm using text input form field. I need input like 1.23 with decimal input text formatter</p>

答:
you can also try decimal validation on form submit.</p>
```<code>bool isValidDecimal(String value){
    String regex = r'^[0-9]+[.]{1}[0-9]+$';
    RegExp regExp = RegExp(regex);
    return regExp.hasMatch(value);
  }
</code>```

Title: How to restrict two dots in flutter?

Body:
you can also try decimal validation on form submit.

bool isValidDecimal(String value){
    String regex = r'^[0-9]+[.]{1}[0-9]+$';
    RegExp regExp = RegExp(regex);
    return regExp.hasMatch(value);
  }


答:
You can use:</p>
```<code>#include <random>
void function(){
std::random_device rd; // obtain a random number from hardware
std::mt19937 gen(rd()); // seed the generator
std::uniform_int_distribution<> distr(-100, 100); // define the range
int randomNumber = distr(gen);
if(randomNumber > 0)
    // bigger than 0
else if(randomNumber == 0)
    // equals 0
else
    // less than 0
}
</code>```

Title: c++ test if random number is positive or negative

Body:
You can use:

#include <random>
void function(){
std::random_device rd; // obtain a random number from hardware
std::mt19937 gen(rd()); // seed the generator
std::uniform_int_distribution<> distr(-100, 100); // define the range
int randomNumber = distr(gen);
if(randomNumber > 0)
    // bigger than 0
else if(randomNumber == 0)
    // equals 0
else
    // less than 0
}


问:
Preventing jQuery mobile from setting document.title?
It looks like jQuery mobile sets document.title to the text content of data-role="header", example:

```<code><div data-position="fixed" data-role="header">
    <h1>This text</h1>
</div>
</code>```

I have a hack workaround to prevent this as such:

$('div[data-role="page"]').bind('pageshow',function(){document.title = "My title"});

Is there a better/more semantic way to do this?

答:
Another solution would be to copy the original document title to the data-title attribute of each page:

```<code>$(":jqmData(role='page')").attr("data-title", document.title);
</code>```

The advantage of this approach over changing the title on pageshow is that it will prevent document title flicker during page transitions.

Body:
It looks like jQuery mobile sets document.title to the text content of data-role="header", example:

This text

I have a hack workaround to prevent this as such:

$('div[data-role="page"]').bind('pageshow',function(){document.title = "My title"});

Is there a better/more semantic way to do this?

Body:
Another solution would be to copy the original document title to the data-title attribute of each page:

$(":jqmData(role='page')").attr("data-title", document.title);

The advantage of this approach over changing the title on pageshow is that it will prevent document title flicker during page transitions.


问:
Run bash text scripts after docker run
I have django application, a test.sh script and dockerfile. I have built dockerfile and run it by docker run -d -p 80:80 IMAGE_NAME.
Dockerfile

```<code>FROM python:3.8-slim-buster

RUN apt-get install -y ca-certificates wget
RUN apt install gunicorn3 -y

COPY ./ ./

RUN pip3 install -r requirements.txt
RUN chmod +x ./test.sh

CMD ["sh", "test.sh"]
ENTRYPOINT ["gunicorn --bind 0.0.0.0:80 core.wsgi:application"]
</code>```

test.sh

```<code>#!/bin/bash
python manage.py test
</code>```

Gunicorn is running successfully. Now I want to run test.sh script with docker run -it --rm IMAGE_NAME test.sh. When i run that command the server runs but never executes test.sh but gunicorn server runs.
How can I run test.sh from docker run -it --rm IMAGE_NAME test.sh?

答: Since you trying to run a script on running container have you tried docker exec -it container_id bash < mylocal.sh?

Title: Run bash text scripts after docker run

Body:
I have django application, a test.sh script and dockerfile. I have built dockerfile and run it by docker run -d -p 80:80 IMAGE_NAME.
Dockerfile

FROM python:3.8-slim-buster

RUN apt-get install -y ca-certificates wget
RUN apt install gunicorn3 -y

COPY ./ ./

RUN pip3 install -r requirements.txt
RUN chmod +x ./test.sh

CMD ["sh", "test.sh"]
ENTRYPOINT ["gunicorn --bind 0.0.0.0:80 core.wsgi:application"]

test.sh

#!/bin/bash
python manage.py test

Gunicorn is running successfully. Now I want to run test.sh script with docker run -it --rm IMAGE_NAME test.sh. When i run that command the server runs but never executes test.sh but gunicorn server runs.
How can I run test.sh from docker run -it --rm IMAGE_NAME test.sh?


问:
Pass parameters to report definition using activity. Pega8.6
I have created a report definition under -Data layer and I have set parameter there as a filter.

Now, I want to call this report under work layer and pass the parameter using activity.

How can I do that ?

答:
Well best practice is to call that Report Definition through a parametrized Data Page if parameters are very few.

Any way you can still pass those parameters to any called Activity by using bellow steps.

Create one Property-Set method before calling report definition and set these parameters.

Param.pyReportName = "YourReportName"

```<code>Param.pyReportClass = "YourReportClass"

Param.pyPageName = "PageName"

Param.GradeParameter = "ValueOfGradeParameter"
</code>```

Now call the report calling activity(your 6th step) with Pass current parameter page check box checked. By checking this check box you can pass all the parameters to the called Activity which you set in the main Activity.

Body:
Well best practice is to call that Report Definition through a parametrized Data Page if parameters are very few.

Any way you can still pass those parameters to any called Activity by using bellow steps.

Create one Property-Set method before calling report definition and set these parameters.

Param.pyReportName = "YourReportName"

Param.pyReportClass = "YourReportClass"

Param.pyPageName = "PageName"

Param.GradeParameter = "ValueOfGradeParameter"

Now call the report calling activity(your 6th step) with Pass current parameter page check box checked. By checking this check box you can pass all the parameters to the called Activity which you set in the main Activity.


问:
expanding the image viewer example of pyqt or QT
im trying to expand the pyqt image veiwer example to have a feature of drawing over images

i added a couple of tested functions that takes mouse events and draw over image

in the image viewer example my i chosed my painter to paint over imageLabel's pixmap

```
def mousMoveEvent(self,event):<br>
    painter = QtGui.QPainter(self.imageLabel.pixmap())
    painter.setPen(QtGui.QPen     (self.chosenColor,self.chosenWidth,Qt.solidLine,Qt.RoundCap,Qt.RoundJoin))
    painter.drawLine(self.laspoint,event.pos())
```

.
.
.

the problem is : it's not drawing over pixmap at all.. it shows image ,, zoom , does everything but drawing is not working.. am i doing anything wrong? i've been trying for 3 days withought a result . does anyone have a better idea for it ?

thanks in advance

答:
I dunno if this is gonna help but I've managed to make a selection box show up an a widget using QLabel and QImage. Basically every time I made a change to the QImage I had to re-set it as the label's image:</p>

```<code>self.imgLabel.setPixmap( QPixmap.fromImage( self.image ) )
</code>```

Body:
im trying to expand the pyqt image veiwer example to have a feature of drawing over images

i added a couple of tested functions that takes mouse events and draw over image

in the image viewer example my i chosed my painter to paint over imageLabel's pixmap

def mousMoveEvent(self,event):

    painter = QtGui.QPainter(self.imageLabel.pixmap())
    painter.setPen(QtGui.QPen     (self.chosenColor,self.chosenWidth,Qt.solidLine,Qt.RoundCap,Qt.RoundJoin))
    painter.drawLine(self.laspoint,event.pos())

.
.
.

the problem is : it's not drawing over pixmap at all.. it shows image ,, zoom , does everything but drawing is not working.. am i doing anything wrong? i've been trying for 3 days withought a result . does anyone have a better idea for it ?

thanks in advance

Body:
I dunno if this is gonna help but I've managed to make a selection box show up an a widget using QLabel and QImage. Basically every time I made a change to the QImage I had to re-set it as the label's image:

self.imgLabel.setPixmap( QPixmap.fromImage( self.image ) )


问:
Linking error using 'idf.py build' on esp32s2
I am trying out a very simple case on my esp32s2. The build seems ok, but the linking not so much.

The aim of the code is to send a keystroke (esp32s2 as a USB device). It is as following:

```<code>#include "tinyusb.h"
#include "class/hid/hid_device.h"
#include "tusb.h"

enum {
ITF_KEYBOARD = 1,
ITF_MOUSE = 0
};

void app_main(void)
{
tusb_init();
tud_task(); // tinyusb device task

uint8_t keycode[6] = { 0 };
keycode[0] = 0x04 ; //HID_KEY_A;
tud_hid_n_keyboard_report(ITF_KEYBOARD, 0, 0, keycode);
}
</code>```

The CMakeLists.txt inside the main folder is like:

```<code>idf_component_register(SRCS main.c
INCLUDE_DIRS ".")
</code>```

The CMakeLists.txt ouside the main folder is like:

```<code>cmake_minimum_required(VERSION 3.5)

include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(test)
</code>```

And the makefile is like:

```<code>PROJECT_NAME := project_name

include $(IDF_PATH)/make/project.mk
</code>```

I also tryed to copy the lib hid_device.c/h inside my project, it works well, but the linking still not work.

When I build the project, I got the following error:

```<code>[ 99%] Linking C static library libmain.a
[ 99%] Built target __idf_main
[ 99%] Generating ld/sections.ld
[ 99%] Built target __ldgen_output_sections.ld
[ 99%] Linking CXX executable test.elf
/home/me/.espressif/tools/xtensa-esp32s2-elf/esp-2021r2-8.4.0/xtensa-esp32s2-elf/bin/../lib/gcc/xtensa-esp32s2-elf/8.4.0/../../../../xtensa-esp32s2-elf/bin/ld: esp-idf/main/libmain.a(main.c.obj):(.literal.app_main+0x0): undefined reference to `tud_hid_n_keyboard_report'
/home/me/.espressif/tools/xtensa-esp32s2-elf/esp-2021r2-8.4.0/xtensa-esp32s2-elf/bin/../lib/gcc/xtensa-esp32s2-elf/8.4.0/../../../../xtensa-esp32s2-elf/bin/ld: esp-idf/main/libmain.a(main.c.obj): in function `app_main':
/home/me/My_project/project_test_HID/main/main.c:37: undefined reference to `tud_hid_n_keyboard_report'
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/test.elf.dir/build.make:538 : test.elf] Erreur 1
make[1]: *** [CMakeFiles/Makefile2:2458 : CMakeFiles/test.elf.dir/all] Erreur 2
make: *** [Makefile:149 : all] Erreur 2
make failed with exit code 2
</code>```

If you have any idea, please let me know :)

Thanks

Regards

答:
You're including headers from an ESP-IDF component called "tinyusb" (that's the name of the directory in its source code: esp-idf/components/tinyusb). But if you're using a component, you must tell the build system about this - otherwise it will not pull in the implementation of this component and you get linker errors.

You can pull it in via your main CMakeLists.txt like so:

```<code>idf_component_register(SRCS main.c
INCLUDE_DIRS "."
REQUIRES "tinyusb")
</code>```

It's all explained more or less clearly in the ESP IDF build system documentation

Body:
I am trying out a very simple case on my esp32s2. The build seems ok, but the linking not so much.

The aim of the code is to send a keystroke (esp32s2 as a USB device). It is as following:

#include "tinyusb.h"
#include "class/hid/hid_device.h"
#include "tusb.h"

enum {
ITF_KEYBOARD = 1,
ITF_MOUSE = 0
};

void app_main(void)
{
tusb_init();
tud_task(); // tinyusb device task

uint8_t keycode[6] = { 0 };
keycode[0] = 0x04 ; //HID_KEY_A;
tud_hid_n_keyboard_report(ITF_KEYBOARD, 0, 0, keycode);
}

The CMakeLists.txt inside the main folder is like:

idf_component_register(SRCS main.c
INCLUDE_DIRS ".")

The CMakeLists.txt ouside the main folder is like:

cmake_minimum_required(VERSION 3.5)

include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(test)

And the makefile is like:

PROJECT_NAME := project_name

include $(IDF_PATH)/make/project.mk

I also tryed to copy the lib hid_device.c/h inside my project, it works well, but the linking still not work.

When I build the project, I got the following error:

[ 99%] Linking C static library libmain.a
[ 99%] Built target __idf_main
[ 99%] Generating ld/sections.ld
[ 99%] Built target __ldgen_output_sections.ld
[ 99%] Linking CXX executable test.elf
/home/me/.espressif/tools/xtensa-esp32s2-elf/esp-2021r2-8.4.0/xtensa-esp32s2-elf/bin/../lib/gcc/xtensa-esp32s2-elf/8.4.0/../../../../xtensa-esp32s2-elf/bin/ld: esp-idf/main/libmain.a(main.c.obj):(.literal.app_main+0x0): undefined reference to `tud_hid_n_keyboard_report'
/home/me/.espressif/tools/xtensa-esp32s2-elf/esp-2021r2-8.4.0/xtensa-esp32s2-elf/bin/../lib/gcc/xtensa-esp32s2-elf/8.4.0/../../../../xtensa-esp32s2-elf/bin/ld: esp-idf/main/libmain.a(main.c.obj): in function `app_main':
/home/me/My_project/project_test_HID/main/main.c:37: undefined reference to `tud_hid_n_keyboard_report'
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/test.elf.dir/build.make:538 : test.elf] Erreur 1
make[1]: *** [CMakeFiles/Makefile2:2458 : CMakeFiles/test.elf.dir/all] Erreur 2
make: *** [Makefile:149 : all] Erreur 2
make failed with exit code 2

If you have any idea, please let me know :)

Thanks

Regards

Body:
You're including headers from an ESP-IDF component called "tinyusb" (that's the name of the directory in its source code: esp-idf/components/tinyusb). But if you're using a component, you must tell the build system about this - otherwise it will not pull in the implementation of this component and you get linker errors.

You can pull it in via your main CMakeLists.txt like so:

idf_component_register(SRCS main.c
INCLUDE_DIRS "."
REQUIRES "tinyusb")

It's all explained more or less clearly in the ESP IDF build system documentation


问:
Avoid ngOnChanges until ngOnInit is completed in Angular
Scenario : I have two components Parent and Child. Both components have some API calls being done in ngOnInit. Child component has ngOnChanges lifecycle hook.
On page load based on certain conditions I'm triggering child's ngOnChanges from Parent component by changing the @Input parameter being passed to Child.

Issue : Child component's ngOnChanges is being triggered from Parent component before the Child component's ngOnInit is completed.

How to avoid this ??

答:
Try ngDoCheck() instead of ngOnChanges(). It could resolve your problem because it is triggered after ngOnInit().

Docs here: https://angular.io/guide/lifecycle-hooks#lifecycle-event-sequence


问:
(scilab) x = [-6,6] y = 1/(1+%e^-x) why it doesn't work?
I'm trying to draw sigmoid function using this code on scilab, but the result I got is not from the equation. what's wrong with my code?

x = -6:1:6;
y = 1/(1+%e^-x)

y  =

```<code>0.0021340
0.0007884
0.0002934
0.0001113
0.0000443
0.0000196
0.0000106
0.0000072
0.0000060
0.0000055
0.0000054
0.0000053
0.0000053
</code>```

http://en.wikipedia.org/wiki/Sigmoid_function

thank you so much

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to draw sigmoid function using this code on scilab, but the result I got is not from the equation. what's wrong with my code?

x = -6:1:6;
y = 1/(1+%e^-x)

y  =

0.0021340
0.0007884
0.0002934
0.0001113
0.0000443
0.0000196
0.0000106
0.0000072
0.0000060
0.0000055
0.0000054
0.0000053
0.0000053

http://en.wikipedia.org/wiki/Sigmoid_function

thank you so much

Body:
With Scilab ≥ 6.1.1, simply

x = (-6:1:6)';
plot(x, 1./(1+exp(-x)))


问:
Rendering an abstract class with italics (class diagram with mermaid)
Mermaid provides annotations as a means to differentiate abstract classes in UML class diagrams. This is not universally usable, for instance, if an abstract class implements interfaces.

Ideally, an abstract class would be rendered with its name in italics. I tried to do so with the following CSS file:

.abstract {
  font-style: italic;
}
```
<p>Which I applied to one of the examples:</p>
```class Animal:::abstract {
    -int sizeInFeet
    -canEat()
}
```

But as the style applies to the whole node, not only the class name is rendered in italics, properties and methods are so too:

Would there be another strategy to render an abstract class with its name in italics?

答:
You can use a more specific CSS selector:

.abstract .classTitle {
  font-style: italic;
}
```

Body:
Mermaid provides annotations as a means to differentiate abstract classes in UML class diagrams. This is not universally usable, for instance, if an abstract class implements interfaces.

Ideally, an abstract class would be rendered with its name in italics. I tried to do so with the following CSS file:

.abstract {
  font-style: italic;
}

Which I applied to one of the examples:

class Animal:::abstract {
    -int sizeInFeet
    -canEat()
}

But as the style applies to the whole node, not only the class name is rendered in italics, properties and methods are so too:

Would there be another strategy to render an abstract class with its name in italics?


问:
Issues with caching a dataframe in Streamlit
I am loading a pandas dataframe as .csv. I am using a @st.cache decorator to cache this dataframe. I want to predict a classification by using a predefined classification model (RandomForest, XGBoost).

Essentially a column will be added to the original dataframe and stored in a new variable.

However, I am having issues caching this new dataframe.

```<code>import pandas as pd
import numpy as np
from xgboost import XGBClassifier
import streamlit as st

def main():
    st.set_page_config(layout="wide")
    st.title('Classification Problem on Home Equity dataset')

if __name__ == '__main__':
    main()

#Load prediction data
    @st.cache
    def load_predict():
        data= pd.read_csv("hmeq_Predict_2.csv")  #Currently on my local machine
        return data
    df_predict = load_predict()

# Predict on data
    @st.cache
    def predictor_func():
        y_pred_nd = pd.Series(model.predict(df_predict),name='BAD')
        Predicted_X = pd.concat([df_predict,y_pred_nd],axis=1)
        #This is the Dataframe that I want cache
        return Predicted_X

#Run XGBoost classification , I have loaded X_train and y_train also, not shown in this example
    if classifier == "XGBoost":
        if st.sidebar.button("Run Classification", key="Classification"):
            model = XGBClassifier()
            model.fit(X_train,y_train)
           #I want this function to return the cached dataframe.
            Predicted_X=predictor_func()
# This command will correctly display the Dataframe, meaning that the predictor_func() ran correctly
            st.write(Predicted_X)

#However, when I want to display the dataframe, Predicted_X, only when I click this button
    if st.sidebar.button("Run Prediction on new Data", key="Prediction"):
        st.subheader('Check last column for prediction. ')
        st.write(Predicted_X)
</code>```

This is the error I get:

```<code>NameError: name 'Predicted_X' is not defined
Traceback: File "C:\Users\vchaubal\Anaconda3\envs\Jupyter_Project_2\lib\site-packages\streamlit\script_runner.py", line 379, in _run_script
    exec(code, module.__dict__) File "C:\Users\vchaubal\Downloads\Streamlit_project.py", line 328, in <module>
    st.write(Predicted_X)
</code>```

Am I missing a key concept here?
Also, is there a way to cache a model from sklearn?

答:
NameError: name 'Predicted_X' is not defined means that you are calling a variable Predicted_X that has not been instantiated (meaning, there is a Predicted_X = .... missing before.

In your code, at

```<code>    if st.sidebar.button("Run Prediction on new Data", key="Prediction"):
        st.subheader('Check last column for prediction. ')
        st.write(Predicted_X)
</code>```

there is no garanty that Predicted_X = ... from the previous lines have been executed.

Your code should look like this:

```<code>Predicted_X = None  # Instantiate Predicted_X

if classifier == "XGBoost":
    if st.sidebar.button("Run Classification", key="Classification"):
        model = XGBClassifier()
        model.fit(X_train, y_train)
        Predicted_X = predictor_func()
        st.write(Predicted_X)

if st.sidebar.button("Run Prediction on new Data", key="Prediction"):
    st.subheader('Check last column for prediction. ')
    # Show Predicted_X only if it has been computed
    if Predicted_X is None:
        st.write("Predicted_X has not been yet computed")
    else:
        st.write(Predicted_X)
</code>```

As for your other question

Also, is there a way to cache a model from sklearn?

There is a way:

```<code>@st.cache()
def load_xgboost_model():
    model = XGBClassifier()
    model.fit(X_train, y_train)
    return model

@st.cache():
def load_sklearn_model(path_to_sklearn_model):
    import pickle
    model = pickle.load(open(path_to_sklearn_model, "rb"))
    return model
</code>```

Body:
I am loading a pandas dataframe as .csv. I am using a @st.cache decorator to cache this dataframe. I want to predict a classification by using a predefined classification model (RandomForest, XGBoost).

Essentially a column will be added to the original dataframe and stored in a new variable.

However, I am having issues caching this new dataframe.

import pandas as pd
import numpy as np
from xgboost import XGBClassifier
import streamlit as st

def main():
    st.set_page_config(layout="wide")
    st.title('Classification Problem on Home Equity dataset')

if __name__ == '__main__':
    main()

#Load prediction data
    @st.cache
    def load_predict():
        data= pd.read_csv("hmeq_Predict_2.csv")  #Currently on my local machine
        return data
    df_predict = load_predict()

# Predict on data
    @st.cache
    def predictor_func():
        y_pred_nd = pd.Series(model.predict(df_predict),name='BAD')
        Predicted_X = pd.concat([df_predict,y_pred_nd],axis=1)
        #This is the Dataframe that I want cache
        return Predicted_X

#Run XGBoost classification , I have loaded X_train and y_train also, not shown in this example
    if classifier == "XGBoost":
        if st.sidebar.button("Run Classification", key="Classification"):
            model = XGBClassifier()
            model.fit(X_train,y_train)
           #I want this function to return the cached dataframe.
            Predicted_X=predictor_func()
# This command will correctly display the Dataframe, meaning that the predictor_func() ran correctly
            st.write(Predicted_X)

#However, when I want to display the dataframe, Predicted_X, only when I click this button
    if st.sidebar.button("Run Prediction on new Data", key="Prediction"):
        st.subheader('Check last column for prediction. ')
        st.write(Predicted_X)

This is the error I get:

NameError: name 'Predicted_X' is not defined
Traceback: File "C:\Users\vchaubal\Anaconda3\envs\Jupyter_Project_2\lib\site-packages\streamlit\script_runner.py", line 379, in _run_script
    exec(code, module.__dict__) File "C:\Users\vchaubal\Downloads\Streamlit_project.py", line 328, in <module>
    st.write(Predicted_X)

Am I missing a key concept here?
Also, is there a way to cache a model from sklearn?

Body:
NameError: name 'Predicted_X' is not defined means that you are calling a variable Predicted_X that has not been instantiated (meaning, there is a Predicted_X = .... missing before.

In your code, at

    if st.sidebar.button("Run Prediction on new Data", key="Prediction"):
        st.subheader('Check last column for prediction. ')
        st.write(Predicted_X)

there is no garanty that Predicted_X = ... from the previous lines have been executed.

Your code should look like this:

Predicted_X = None  # Instantiate Predicted_X

if classifier == "XGBoost":
    if st.sidebar.button("Run Classification", key="Classification"):
        model = XGBClassifier()
        model.fit(X_train, y_train)
        Predicted_X = predictor_func()
        st.write(Predicted_X)

if st.sidebar.button("Run Prediction on new Data", key="Prediction"):
    st.subheader('Check last column for prediction. ')
    # Show Predicted_X only if it has been computed
    if Predicted_X is None:
        st.write("Predicted_X has not been yet computed")
    else:
        st.write(Predicted_X)

As for your other question

Also, is there a way to cache a model from sklearn?

There is a way:

@st.cache()
def load_xgboost_model():
    model = XGBClassifier()
    model.fit(X_train, y_train)
    return model

@st.cache():
def load_sklearn_model(path_to_sklearn_model):
    import pickle
    model = pickle.load(open(path_to_sklearn_model, "rb"))
    return model


问:
Reading csv file row by column name
I have this csv file

```<code>id  title   link    description condition   price   availability    image_link  gtin    brand   mpn google_product_category product_type    item_group_id
438 Belkin 3m USB 2.0 Printer Extension Cable - Black   https://amazon.com/electronics/computers-components-and-accessories/printers-and-accessories/printers/belkin-3m-usb-2.0-printer-extension-cable-black/  Add length to your USB cables when they can't quite reach their destination with the USB A/B Extension Cable. Stop struggling with short cables while connecting your printer, scanner, or hard drive, thanks to this convenient extension cable. This USB 2.0 cable delivers error-free data transmissions at up to 480Mbps, letting you send jobs to external devices and transfer files to and from your computer quickly.Supports up to 127 devices on a daisy-chain configuration.3m cable.For connecting USB Cable.Manufacturer's limited lifetime guarantee.EAN: 722868246405.       11.00 GBP       https://amazon.com/images/thumbnails/590/590/detailed/9/3082276_R_Z001A.jpg                 Electronics > Computers, Components & Accessories > Printers & Accessories > Printers
6   Toshiba 32C120U 32" Class 720P HD LCD TV    https://amazon.com/electronics/home-cinema-tv-and-video/plasma-tvs/toshiba-32c120u-32-class-720p-hd-lcd-tv/ Think you need to break your budget to enjoy blockbuster HD entertainment? Not with Toshiba's 32" class C110U LCD HDTV. Featuring all-new design, this value-packed television looks great and works well in a living room, kitchen or bedroom. Increase detail and depth of the images on your screen with our impressive Dynalight technology.        329.99 GBP      https://amazon.com/images/thumbnails/590/590/detailed/0/lcd-tv-32C120-01.jpg        Toshiba         Electronics > Home Cinema, TV & Video > Plasma TVs
410 USB 2.0 A-Male to B-Male 1.8m Computer Cable    https://amazon.com/computers-and-accessories/usb-2.0-a-male-to-b-male-1.8m-computer-cable/  With the 1.8 meter cable, distance won't be an issue as you can link your scanner, printer or external hard drive to your computer even if they're far apart. As long as they are USB compatible, you can connect your devices with ease.The sturdy PVC housing and jacket means that your cable will be protected against wear and tear.1.8m cable.For connecting USB A/M TO USB B/M.Manufacturer's 1 year guarantee.      9.00 GBP        https://amazon.com/images/thumbnails/590/590/detailed/9/9214392_R_Z001A.jpg                 Computers & Accessories
</code>```

which is basically a csv with the following columns,

```<code>id  title   link    description condition   price   availability    image_link  gtin    brand   mpn google_product_category product_type    item_group_id
</code>```

I am trying to read the columns

```<code><?php
$row = 1;
if (($handle = fopen("google_base.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo '```';
            print_r($data);
            echo '```';
        }
    }
    fclose($handle);
}
</code>```

or

```<code><?php
$row = 1;
if (($handle = fopen("google_base.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    echo '```';
       print_r($data);
       echo '```';
    }
    fclose($handle);
}
</code>```

but the arrays produced do not produced well organised row data with their respective columns.

I can view the columns on this tool https://www.convertcsv.com/csv-viewer-editor.htm

How can i read a row by the column name?

答:
Used the tab delimiter to read the individual rows like this

```<code><?php
$row = 1;
if (($handle = fopen("google_base.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {
    echo '```';
       echo $data[0].'
';
       echo '```';
    }
    fclose($handle);
}
</code>```

Title: Reading csv file row by column name

Body:
I have this csv file

id  title   link    description condition   price   availability    image_link  gtin    brand   mpn google_product_category product_type    item_group_id
438 Belkin 3m USB 2.0 Printer Extension Cable - Black   https://amazon.com/electronics/computers-components-and-accessories/printers-and-accessories/printers/belkin-3m-usb-2.0-printer-extension-cable-black/  Add length to your USB cables when they can't quite reach their destination with the USB A/B Extension Cable. Stop struggling with short cables while connecting your printer, scanner, or hard drive, thanks to this convenient extension cable. This USB 2.0 cable delivers error-free data transmissions at up to 480Mbps, letting you send jobs to external devices and transfer files to and from your computer quickly.Supports up to 127 devices on a daisy-chain configuration.3m cable.For connecting USB Cable.Manufacturer's limited lifetime guarantee.EAN: 722868246405.       11.00 GBP       https://amazon.com/images/thumbnails/590/590/detailed/9/3082276_R_Z001A.jpg                 Electronics > Computers, Components & Accessories > Printers & Accessories > Printers
6   Toshiba 32C120U 32" Class 720P HD LCD TV    https://amazon.com/electronics/home-cinema-tv-and-video/plasma-tvs/toshiba-32c120u-32-class-720p-hd-lcd-tv/ Think you need to break your budget to enjoy blockbuster HD entertainment? Not with Toshiba's 32" class C110U LCD HDTV. Featuring all-new design, this value-packed television looks great and works well in a living room, kitchen or bedroom. Increase detail and depth of the images on your screen with our impressive Dynalight technology.        329.99 GBP      https://amazon.com/images/thumbnails/590/590/detailed/0/lcd-tv-32C120-01.jpg        Toshiba         Electronics > Home Cinema, TV & Video > Plasma TVs
410 USB 2.0 A-Male to B-Male 1.8m Computer Cable    https://amazon.com/computers-and-accessories/usb-2.0-a-male-to-b-male-1.8m-computer-cable/  With the 1.8 meter cable, distance won't be an issue as you can link your scanner, printer or external hard drive to your computer even if they're far apart. As long as they are USB compatible, you can connect your devices with ease.The sturdy PVC housing and jacket means that your cable will be protected against wear and tear.1.8m cable.For connecting USB A/M TO USB B/M.Manufacturer's 1 year guarantee.      9.00 GBP        https://amazon.com/images/thumbnails/590/590/detailed/9/9214392_R_Z001A.jpg                 Computers & Accessories

which is basically a csv with the following columns,

id  title   link    description condition   price   availability    image_link  gtin    brand   mpn google_product_category product_type    item_group_id

I am trying to read the columns

<?php
$row = 1;
if (($handle = fopen("google_base.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "
 $num fields in line $row:

\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo '
';
            print_r($data);
            echo '
';
        }
    }
    fclose($handle);
}

or

<?php
$row = 1;
if (($handle = fopen("google_base.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    echo '
';
       print_r($data);
       echo '
';
    }
    fclose($handle);
}

but the arrays produced do not produced well organised row data with their respective columns.

I can view the columns on this tool https://www.convertcsv.com/csv-viewer-editor.htm

How can i read a row by the column name?

Body:
Used the tab delimiter to read the individual rows like this

<?php
$row = 1;
if (($handle = fopen("google_base.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {
    echo '<pre>';
       echo $data[0].'</br>';
       echo '</pre>';
    }
    fclose($handle);
}


问:
configuration of readiness probe for my webapp
I am running a sample webapp python in Kubernetes.
I am not able to figure out how I make use of probes here.

I want app to recover from broken states by automatically restarting pods

Route the traffic to the healthy pods only.

Make sure the database is up and running before the application (which in my case is Redis).

I have understanding of probes but not sure how/what values exactly to look for

My definition file:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp-deployment
  labels:
     env: production
     app: frontend
spec:
  selector:
    matchLabels:
      env: production
      app: frontend
  replicas: 1
  template:
    metadata:
      name: myapp-pod
      labels:
        env: production
        app: frontend
    spec:
      containers:
      - name: myapp-container
        image: myimage:latest
        imagePullPolicy: Always
        ports:
        - containerPort: 5000
```
<p>Now I am doing something like this</p>
```        readinessProbe:
          httpGet:
            path: /
            port: 5000
          initialDelaySeconds: 20
          periodSeconds: 5
        livenessProbe:
        httpGet:
          path: /
          port: 5000
        intialDelaySeconds: 10
        periodSeconds: 5
```

答:
In Kubernetes you have three kind of probes:

Liveness - is my application still running? If this fails the application is restarted

Readiness - is my application ready to serve traffic? If this fails the current pod does not get traffic (e.g. via a service).

Startup (since 1.18) - this probe type was introduces for applications that need a long time to start. The other two probe types start after the startup probe reports success the first time.

So, in your case your application should provide one probe that checks if it still running and another if it can server traffic (also checking Redis). Be aware the liveness probes may be dangerous - maye start only with a readiness probe.

If your app provides the health check (incl. Redis) under /healthz, this is how you would define your readiness probe.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp-deployment
  labels:
     env: production
     app: frontend
spec:
  selector:
    matchLabels:
      env: production
      app: frontend
  replicas: 1
  template:
    metadata:
      name: myapp-pod
      labels:
        env: production
        app: frontend
    spec:
      containers:
      - name: myapp-container
        image: myimage:latest
        imagePullPolicy: Always
        ports:
        - containerPort: 5000
        readinessProbe:
          httpGet:
            path: /healthz
            port: 5000
          initialDelaySeconds: 3
          periodSeconds: 3
```

Body:
I am running a sample webapp python in Kubernetes.
I am not able to figure out how I make use of probes here.

I want app to recover from broken states by automatically restarting pods

Route the traffic to the healthy pods only.

Make sure the database is up and running before the application (which in my case is Redis).

I have understanding of probes but not sure how/what values exactly to look for

My definition file:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp-deployment
  labels:
     env: production
     app: frontend
spec:
  selector:
    matchLabels:
      env: production
      app: frontend
  replicas: 1
  template:
    metadata:
      name: myapp-pod
      labels:
        env: production
        app: frontend
    spec:
      containers:
      - name: myapp-container
        image: myimage:latest
        imagePullPolicy: Always
        ports:
        - containerPort: 5000

Now I am doing something like this

        readinessProbe:
          httpGet:
            path: /
            port: 5000
          initialDelaySeconds: 20
          periodSeconds: 5
        livenessProbe:
        httpGet:
          path: /
          port: 5000
        intialDelaySeconds: 10
        periodSeconds: 5


问:
Fetch all images at once and show 360 product view in Reactjs
I have already written a component that enables 360 product views for users. Users can interact with image (rotate to the right or left). This Component works well when images are from local files.

I want to fetch images from Cloudinary and render them. A product may have 100+ images so I want to show loader till all images are loaded. Once done image will render and when the user rotates new image is rendered. I was also looking for npm lib that takes care of loading and rendering images.

```<code>import React, { Component } from "react";
import "./styles.css";
import { Row, Space, Typography, Image } from "antd";
import { Md3DRotation } from "react-icons/md";
// You can play with this to adjust the sensitivity
// higher values make mouse less sensitive
const pixelsPerDegree = 1;

class React360 extends Component {
  static defaultProps = { dir: "puma", numImages: 83 };

  state = {
    dragging: false,
    imageIndex: 0,
    dragStartIndex: 0,
    images: [],
    show360: false,
    imgs:null
  };

  componentDidMount = () => {
    document.addEventListener("mousemove", this.handleMouseMove, false);
    document.addEventListener("mouseup", this.handleMouseUp, false);
    // document.addEventListener("touchstart", this.handleMouseMove, false);
    // document.addEventListener("touchend", this.handleMouseUp, false);

  };

  componentWillUnmount = () => {
    document.removeEventListener("mousemove", this.handleMouseMove, false);
    document.removeEventListener("mouseup", this.handleMouseUp, false);
    // document.removeEventListener("touchstart", this.handleMouseMove, false);
    // document.removeEventListener("touchend", this.handleMouseUp, false);
  };

  handleMouseDown = (e) => {
    //   console.log("e.screenX",Math.round(e?.touches?.[0]?.clientX))
    e.persist();
    this.setState((state) => ({
      dragging: true,
      dragStart: e.screenX || Math.round(e?.touches?.[0]?.clientX),
      dragStartIndex: state.imageIndex,
    }));
  };

  handleMouseUp = () => {
    this.setState({ dragging: false });
  };

  updateImageIndex = (currentPosition) => {
    let numImages = this.props.numImages;
    const pixelsPerImage = pixelsPerDegree * (360 / numImages);
    const { dragStart, imageIndex, dragStartIndex } = this.state;
    // pixels moved
    let dx = (currentPosition - dragStart) / pixelsPerImage;
    let index = Math.floor(dx) % numImages;

    if (index < 0) {
      index = numImages + index - 1;
    }
    index = (index + dragStartIndex) % numImages;
    // console.log(index, dragStartIndex, numImages)
    if (index !== imageIndex) {
      this.setState({ imageIndex: index === 0 ? 1 : index });
    }
  };

  handleMouseMove = (e) => {
    //   console.log("handleMouseMove",this.state.dragging)
    console.log("screenX", Math.round(e?.touches?.[0]?.clientX));
    if (this.state.dragging) {
      this.updateImageIndex(e.screenX || Math.round(e?.touches?.[0]?.clientX));
    }
  };

  preventDragHandler = (e) => {
    e.preventDefault();
  };

  renderImage = () => {
    const { imageIndex, images } = this.state;

    return (
      <>

        <div className="react360">
           <img

            alt=""
            src={
               require(`../../assets/puma_opti/IMG_00${
                 imageIndex > 9 ? imageIndex : "0" + imageIndex
               }.JPG`).default
             }

          />

        </div>
        <Row justify="center" style={{ marginTop: "1.5em" }}>
          <Space>
            <Md3DRotation size={25} color="#8C8C8C" />
            <Typography.Title
              level={5}
              type="secondary"
              style={{ fontFamily: "Gilroy" }}
              className="helptext-360"
            >
              Drag to view 360 degrees
            </Typography.Title>
          </Space>
        </Row>
      </>
    );
  };

  render = () => {
    return (
      <div
        className="react-360-img"
        onMouseDown={this.handleMouseDown}
        onDragStart={this.preventDragHandler}
        // onTouchStart={this.handleMouseMove}
        onTouchStart={this.handleMouseDown}
        onTouchMove={this.handleMouseMove}
        onTouchEnd={this.handleMouseUp}
      >
        {this.renderImage()}
      </div>
    );
  };
}
</code>```

答:
1.For library you can use React Loading Skeleton : https://www.npmjs.com/package/react-loading-skeleton
2.If you want to display loading when you get data you have to add condition to your jsx, for instance:

```<code>fetchData.loading?(
   return <Skeleton/>
  ):(
  <div className="react360">
   data.map(res=>{
    <img
      alt=""
      src={
      require(`../../assets/puma_opti/IMG_00${
       imageIndex > 9 ? imageIndex : "0" + imageIndex}.JPG`).default
      }
    />
  }))
 </div>
</code>```

N.B: fetchdata is the status of your API call (if is loading or successful), data is data obtained from API.

Body:
I have already written a component that enables 360 product views for users. Users can interact with image (rotate to the right or left). This Component works well when images are from local files.

I want to fetch images from Cloudinary and render them. A product may have 100+ images so I want to show loader till all images are loaded. Once done image will render and when the user rotates new image is rendered. I was also looking for npm lib that takes care of loading and rendering images.

import React, { Component } from "react";
import "./styles.css";
import { Row, Space, Typography, Image } from "antd";
import { Md3DRotation } from "react-icons/md";
// You can play with this to adjust the sensitivity
// higher values make mouse less sensitive
const pixelsPerDegree = 1;

class React360 extends Component {
  static defaultProps = { dir: "puma", numImages: 83 };

  state = {
    dragging: false,
    imageIndex: 0,
    dragStartIndex: 0,
    images: [],
    show360: false,
    imgs:null
  };

  componentDidMount = () => {
    document.addEventListener("mousemove", this.handleMouseMove, false);
    document.addEventListener("mouseup", this.handleMouseUp, false);
    // document.addEventListener("touchstart", this.handleMouseMove, false);
    // document.addEventListener("touchend", this.handleMouseUp, false);

  };

  componentWillUnmount = () => {
    document.removeEventListener("mousemove", this.handleMouseMove, false);
    document.removeEventListener("mouseup", this.handleMouseUp, false);
    // document.removeEventListener("touchstart", this.handleMouseMove, false);
    // document.removeEventListener("touchend", this.handleMouseUp, false);
  };

  handleMouseDown = (e) => {
    //   console.log("e.screenX",Math.round(e?.touches?.[0]?.clientX))
    e.persist();
    this.setState((state) => ({
      dragging: true,
      dragStart: e.screenX || Math.round(e?.touches?.[0]?.clientX),
      dragStartIndex: state.imageIndex,
    }));
  };

  handleMouseUp = () => {
    this.setState({ dragging: false });
  };

  updateImageIndex = (currentPosition) => {
    let numImages = this.props.numImages;
    const pixelsPerImage = pixelsPerDegree * (360 / numImages);
    const { dragStart, imageIndex, dragStartIndex } = this.state;
    // pixels moved
    let dx = (currentPosition - dragStart) / pixelsPerImage;
    let index = Math.floor(dx) % numImages;

    if (index < 0) {
      index = numImages + index - 1;
    }
    index = (index + dragStartIndex) % numImages;
    // console.log(index, dragStartIndex, numImages)
    if (index !== imageIndex) {
      this.setState({ imageIndex: index === 0 ? 1 : index });
    }
  };

  handleMouseMove = (e) => {
    //   console.log("handleMouseMove",this.state.dragging)
    console.log("screenX", Math.round(e?.touches?.[0]?.clientX));
    if (this.state.dragging) {
      this.updateImageIndex(e.screenX || Math.round(e?.touches?.[0]?.clientX));
    }
  };

  preventDragHandler = (e) => {
    e.preventDefault();
  };

  renderImage = () => {
    const { imageIndex, images } = this.state;

    return (
      <>

            9 ? imageIndex : "0" + imageIndex
               }.JPG`).default
             }

          />

        <Row justify="center" style={{ marginTop: "1.5em" }}>
          <Space>
            <Md3DRotation size={25} color="#8C8C8C" />
            <Typography.Title
              level={5}
              type="secondary"
              style={{ fontFamily: "Gilroy" }}
              className="helptext-360"
            >
              Drag to view 360 degrees
            </Typography.Title>
          </Space>
        </Row>
      </>
    );
  };

  render = () => {
    return (

        {this.renderImage()}

    );
  };
}

Body:
1.For library you can use React Loading Skeleton : https://www.npmjs.com/package/react-loading-skeleton
2.If you want to display loading when you get data you have to add condition to your jsx, for instance:

fetchData.loading?(
   return <Skeleton/>
  ):(
  <div className="react360">
   data.map(res=>{
    <img
      alt=""
      src={
      require(`../../assets/puma_opti/IMG_00${
       imageIndex > 9 ? imageIndex : "0" + imageIndex}.JPG`).default
      }
    />
  }))
 </div>

N.B: fetchdata is the status of your API call (if is loading or successful), data is data obtained from API.


问:
Stuck in loop after entering any other datatype in place of int
Can anyone please tell me what is wrong with the code. I am stuck in a loop after entering any other datatype in place of int.

I am trying to make this program so if i enter any other datatype than the datatype which is mentioned i will get a message and the program will ask me again to enter the code.

```<code>import java.util.Scanner;

public class main {
    public static void main(String[] args) {
        Integer i=null;
        int j=0;
        Scanner sc = new Scanner(System.in);
        while(j==0) {
            i=0;
            try {
                i = sc.nextInt();
                System.out.println(i);
                if(i>=0||i<=0){
                    break;
                }
            } catch (Exception e) {
                System.out.println("Please enter only integers!");
            }

        }

    }
}
</code>```

答:
Here is a solution :-</p>
```<code>import java.util.Scanner;

public class main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (true) {
            try {
                System.out.println(sc.nextInt());
                break;

            } catch (Exception e) {
                System.out.println("Please enter only integers!");
                sc.nextLine();
            }
        }
    }
}
</code>```

Body:
Can anyone please tell me what is wrong with the code. I am stuck in a loop after entering any other datatype in place of int.

I am trying to make this program so if i enter any other datatype than the datatype which is mentioned i will get a message and the program will ask me again to enter the code.

import java.util.Scanner;

public class main {
    public static void main(String[] args) {
        Integer i=null;
        int j=0;
        Scanner sc = new Scanner(System.in);
        while(j==0) {
            i=0;
            try {
                i = sc.nextInt();
                System.out.println(i);
                if(i>=0||i<=0){
                    break;
                }
            } catch (Exception e) {
                System.out.println("Please enter only integers!");
            }

        }

    }
}

Body:
Here is a solution :-

import java.util.Scanner;

public class main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (true) {
            try {
                System.out.println(sc.nextInt());
                break;

            } catch (Exception e) {
                System.out.println("Please enter only integers!");
                sc.nextLine();
            }
        }
    }
}


问:
What is the difference between accuracy_score and clf.score in sklearn?

from sklearn.svm import SVC
from sklearn.datasets import make_blobs
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split

X, y = make_blobs(n_samples=500, n_features=2, centers=2, random_state=34)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
clf = SVC()
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print(clf.score(X_test, y_test) == accuracy_score(y_test, y_pred))
```
<p>The output of the above code is:</p>
```True
```
<p>I don't know the difference between them, can someone tell me?</p>
<hr />
<p><strong>Edit:</strong> The source code of the <code>score</code> function is:</p>
<pre class="lang-py prettyprint-override"><code>def score(self, X, y, sample_weight=None):
    """
    Return the mean accuracy on the given test data and labels.
    In multi-label classification, this is the subset accuracy
    which is a harsh metric since you require for each sample that
    each label set be correctly predicted.
    Parameters
    ----------
    X : array-like of shape (n_samples, n_features)
        Test samples.
    y : array-like of shape (n_samples,) or (n_samples, n_outputs)
        True labels for `X`.
    sample_weight : array-like of shape (n_samples,), default=None
        Sample weights.
    Returns
    -------
    score : float
        Mean accuracy of ``self.predict(X)`` wrt. `y`.
    """
    from .metrics import accuracy_score

    return accuracy_score(y, self.predict(X), sample_weight=sample_weight)
</code>```

i.e., the score function is implemented with accuracy_score function, so these two functions are the same?

答:
clf.score() is actually for the SVC class, and it returns the mean accuracy on the given data and labels.

accuracy_score on the other hand returns a fraction of instances where classification was done correctly. For example, if you pass-in 10 items for classification, and say 7 of them are classified correctly (whatever is the clsss - True / False, Multiclass), its return value will be 0.7. You can set a flag normalize to False and then it will return just an integer of how many instances were classified correctly.

Body:
from sklearn.svm import SVC
from sklearn.datasets import make_blobs
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split

X, y = make_blobs(n_samples=500, n_features=2, centers=2, random_state=34)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
clf = SVC()
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print(clf.score(X_test, y_test) == accuracy_score(y_test, y_pred))

The output of the above code is:

True

I don't know the difference between them, can someone tell me?

Edit: The source code of the score function is:

def score(self, X, y, sample_weight=None):
    """
    Return the mean accuracy on the given test data and labels.
    In multi-label classification, this is the subset accuracy
    which is a harsh metric since you require for each sample that
    each label set be correctly predicted.
    Parameters
    ----------
    X : array-like of shape (n_samples, n_features)
        Test samples.
    y : array-like of shape (n_samples,) or (n_samples, n_outputs)
        True labels for `X`.
    sample_weight : array-like of shape (n_samples,), default=None
        Sample weights.
    Returns
    -------
    score : float
        Mean accuracy of ``self.predict(X)`` wrt. `y`.
    """
    from .metrics import accuracy_score

    return accuracy_score(y, self.predict(X), sample_weight=sample_weight)

i.e., the score function is implemented with accuracy_score function, so these two functions are the same?


问:
opencv cvblob render issue
I just installed cvblob for object detection.

When I tried to run the program, the image would not show up and it gives me an error:
"VIDIOC_QUERYMENU: Invalid argument"

Here is the code.

```<code>#include "highgui.h"
#include "cv.h"
#include "cvaux.h"
#include "iostream"
#include <stdio.h>
#include <ctype.h>

#include <cvblob.h>

using namespace cv;
using namespace std;
using namespace cvb;

int main(int argc, char** argv) {
    CvTracks tracks;

    namedWindow("frame", CV_WINDOW_AUTOSIZE);
    cvMoveWindow("frame", 50, 100);

    CvCapture* capture;

    IplImage* frame = 0;

//    frame = cvLoadImage("fruits.jpg", 1);

    capture = cvCreateCameraCapture( 1 ); //capture frames from cam on index 0: /dev/video0/

    cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, 240);
    cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, 320);

    frame = cvQueryFrame(capture);

    while(capture) {
        IplImage *gray = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 1);
        cvCvtColor(frame, gray, CV_BGR2GRAY);
        cvThreshold(gray, gray, 150, 255, CV_THRESH_BINARY);

        IplImage *labelImg=cvCreateImage(cvGetSize(gray), IPL_DEPTH_LABEL, 1);
        CvBlobs blobs;
        unsigned int result=cvLabel(gray, labelImg, blobs);

        cvFilterByArea(blobs, 500, 1000000);
        cvRenderBlobs(labelImg, blobs, frame, frame, CV_BLOB_RENDER_BOUNDING_BOX);
        cvUpdateTracks(blobs, tracks, 200., 5);
        cvRenderTracks(tracks, frame, frame, CV_TRACK_RENDER_ID|CV_TRACK_RENDER_BOUNDING_BOX);

//        for (CvBlobs::const_iterator it=blobs.begin(); it!=blobs.end(); ++it) {
//            cout << "Blob #" << it->second->label << ": Area=" << it->second->area << ", Centroid=(" << it->second->centroid.x << ", " << it->second->centroid.y << ")" << endl;
//        }

        cvShowImage("frame", frame);

        frame = cvQueryFrame(capture);
    }
}
</code>```

If I uncomment the commented part, the blob information will be shown.

Can anyone help me find out why the image is not showing?

Thanks,
Milo

答:
That error is coming from the video capture system, not cvBlob.

I see a few issues:

You must test capture after creating it to make sure you have successfully opened a camera.

Your while loop should be testing frame, not capture to make sure you've successfully received a frame of video.

Are you sure you have a camera at index 1?

Try this simplified version and see if it works. Note that I'm testing capture, looping while frame is not 0, and opening the camera at index 0. This works on my system.

```<code>int main(int argc, char** argv) {
    namedWindow("frame", CV_WINDOW_AUTOSIZE);
    cvMoveWindow("frame", 50, 100);

    CvCapture* capture;

    IplImage* frame = 0;

    capture = cvCreateCameraCapture( 0 ); //capture frames from cam on index 0: /dev/video0/
    if (!capture) {
        return -1;
    }

    cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, 240);
    cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, 320);

    frame = cvQueryFrame(capture);

    while(frame) {
        cvShowImage("frame", frame);

        frame = cvQueryFrame(capture);
    }
}
</code>```

If this works for you, try changing the cvCreateCameraCapture argument to 1. Then try adding back your code a little at a time.

Title: opencv cvblob render issue

Body:
I just installed cvblob for object detection.

When I tried to run the program, the image would not show up and it gives me an error:
"VIDIOC_QUERYMENU: Invalid argument"

Here is the code.

#include "highgui.h"
#include "cv.h"
#include "cvaux.h"
#include "iostream"
#include <stdio.h>
#include <ctype.h>

#include <cvblob.h>

using namespace cv;
using namespace std;
using namespace cvb;

int main(int argc, char** argv) {
    CvTracks tracks;

    namedWindow("frame", CV_WINDOW_AUTOSIZE);
    cvMoveWindow("frame", 50, 100);

    CvCapture* capture;

    IplImage* frame = 0;

//    frame = cvLoadImage("fruits.jpg", 1);

    capture = cvCreateCameraCapture( 1 ); //capture frames from cam on index 0: /dev/video0/

    cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, 240);
    cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, 320);

    frame = cvQueryFrame(capture);

    while(capture) {
        IplImage *gray = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 1);
        cvCvtColor(frame, gray, CV_BGR2GRAY);
        cvThreshold(gray, gray, 150, 255, CV_THRESH_BINARY);

        IplImage *labelImg=cvCreateImage(cvGetSize(gray), IPL_DEPTH_LABEL, 1);
        CvBlobs blobs;
        unsigned int result=cvLabel(gray, labelImg, blobs);

        cvFilterByArea(blobs, 500, 1000000);
        cvRenderBlobs(labelImg, blobs, frame, frame, CV_BLOB_RENDER_BOUNDING_BOX);
        cvUpdateTracks(blobs, tracks, 200., 5);
        cvRenderTracks(tracks, frame, frame, CV_TRACK_RENDER_ID|CV_TRACK_RENDER_BOUNDING_BOX);

//        for (CvBlobs::const_iterator it=blobs.begin(); it!=blobs.end(); ++it) {
//            cout << "Blob #" << it->second->label << ": Area=" << it->second->area << ", Centroid=(" << it->second->centroid.x << ", " << it->second->centroid.y << ")" << endl;
//        }

        cvShowImage("frame", frame);

        frame = cvQueryFrame(capture);
    }
}

If I uncomment the commented part, the blob information will be shown.

Can anyone help me find out why the image is not showing?

Thanks,
Milo

Body:
That error is coming from the video capture system, not cvBlob.

I see a few issues:

You must test capture after creating it to make sure you have successfully opened a camera.

Your while loop should be testing frame, not capture to make sure you've successfully received a frame of video.

Are you sure you have a camera at index 1?

Try this simplified version and see if it works. Note that I'm testing capture, looping while frame is not 0, and opening the camera at index 0. This works on my system.

int main(int argc, char** argv) {
    namedWindow("frame", CV_WINDOW_AUTOSIZE);
    cvMoveWindow("frame", 50, 100);

    CvCapture* capture;

    IplImage* frame = 0;

    capture = cvCreateCameraCapture( 0 ); //capture frames from cam on index 0: /dev/video0/
    if (!capture) {
        return -1;
    }

    cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, 240);
    cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, 320);

    frame = cvQueryFrame(capture);

    while(frame) {
        cvShowImage("frame", frame);

        frame = cvQueryFrame(capture);
    }
}

If this works for you, try changing the cvCreateCameraCapture argument to 1. Then try adding back your code a little at a time.


问:
How does Random String in Kubernetes pod Name decided
I have few questions regarding how a random string part in kubernetes podname is decided .

how is pod-template-hash decided ?? ( i understand that it is a random string generated by deployment controller). But exactly what are the inputs which the deployment controller considers before generating this random string .
is there a maximum length this hash string will limit to ??

The reason for asking this, we are storing the complete pod name in database and it cannot exceed certain character length.

Most of the times i have seen the length is 10 characters. Can it go beyond 10 characters ??

答:
10 characters? That is only the alphanumeric suffix of the replica set name. Pods under a replica set will have additional suffixes of a dash plus 5 characters long alphanumeric string.

The name structure of a Pod will be different depending on the controller type:

StatefulSet: StatefulSet name + "-" + ordinal number starting from 0

DaemonSet: DaemonSet name + "-" + 5 alphanumeric characters long string

Deployment: ReplicaSet name (which is Deployment name + "-" + 10 alphanumeric characters long string) + "-" + 5 alphanumeric characters long string

But then, the full name of the Pods will also include the name of their controllers, which is rather arbitrary.

So, how do you proceed?

You just have to prepare the length of the column to be the maximum length of a  pod name, which is 253 characters.


问:
Adding a new column to a list of data frames and then 'unlist' with names intact?
I have a number of dfs to which I want to add a column.
For the sake of a mrp, these dfs are called df_1, df_2, df_3...

```<code>for (i in 1:10) {
assign(paste("df_",i,sep = ""),data.frame(x = rep(1,10), y  = rep(2,10)))
}
</code>```

I want to add another column z to each of these dfs.

```<code>z <- rep("hello",10)

</code>```

How can I accomplish this?

Using lapply I have been able to do this

```<code>q <- list()
for (i in 1:10) {
q[[i]] <-  assign(paste("df_",i,sep = ""),data.frame(x = rep(1,10), y  = rep(2,10)))
}
z <- rep("hello",10)
q <- lapply(q, cbind,z)
</code>```

This adds the required column, however, I don't know how to preserve the names. How can I still have df_1, df_2, etc but each with a new column z?

Thanks in advance

答:
Alternatively, you can slightly adjust your own list-method such that the names of the data frames are also stored:

```<code>q <- list()
for (i in 1:10) {
  q[[paste0('df_', i)]] <-  data.frame(x = rep(1,10), y  = rep(2,10))
}
z <- rep("hello",10)
q <- lapply(q, cbind,z)
</code>```

Edit: using list2env mentioned by @jay.sf, the dfs are returned to the global environment.

```<code>list2env(q , .GlobalEnv)
</code>```

Body:
I have a number of dfs to which I want to add a column.
For the sake of a mrp, these dfs are called df_1, df_2, df_3...

for (i in 1:10) {
assign(paste("df_",i,sep = ""),data.frame(x = rep(1,10), y  = rep(2,10)))
}

I want to add another column z to each of these dfs.

z <- rep("hello",10)

How can I accomplish this?

Using lapply I have been able to do this

q <- list()
for (i in 1:10) {
q[[i]] <-  assign(paste("df_",i,sep = ""),data.frame(x = rep(1,10), y  = rep(2,10)))
}
z <- rep("hello",10)
q <- lapply(q, cbind,z)

This adds the required column, however, I don't know how to preserve the names. How can I still have df_1, df_2, etc but each with a new column z?

Thanks in advance

Body:
Alternatively, you can slightly adjust your own list-method such that the names of the data frames are also stored:

q <- list()
for (i in 1:10) {
  q[[paste0('df_', i)]] <-  data.frame(x = rep(1,10), y  = rep(2,10))
}
z <- rep("hello",10)
q <- lapply(q, cbind,z)

Edit: using list2env mentioned by @jay.sf, the dfs are returned to the global environment.

list2env(q , .GlobalEnv)


问:
need to continue after the MQ exception MQRC_UNKNOWN_OBJECT_NAME in java( Sprinngboot)
I have following method to send a message to MQ , when the queue name is incorrect it throws MQRC_UNKNOWN_OBJECT_NAME error, but I want to pass the custom error (something like "queue name is not found") and let the user to continue with a correct queue name. I tried to capture the message send not successful scenario by returning the mqSend() method as false. but it doesn't work as I expected. Can someone help me out here? ( please note I'm setting the required MQ properties(QUEUE_NAME,QMGR,CHANNEL,HOST,PORT) separately.</p>
```<code>    public boolean mqSend()
    {

        String APP_USER = ""; // User name that application uses to connect to MQ
        String APP_PASSWORD = ""; // Password that the application uses to connect to MQ

        // Variables
        JMSContext context = null;
        Destination destination = null;
        JMSProducer producer = null;
        //JMSConsumer consumer = null;

        try {
            // Create a connection factory
            JmsFactoryFactory ff = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);
            JmsConnectionFactory cf = ff.createConnectionFactory();

            // Set the properties
            cf.setStringProperty(WMQConstants.WMQ_HOST_NAME, HOST);
            cf.setIntProperty(WMQConstants.WMQ_PORT, PORT);
            cf.setStringProperty(WMQConstants.WMQ_CHANNEL, CHANNEL);
            cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT);
            cf.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER, QMGR);
            cf.setStringProperty(WMQConstants.WMQ_APPLICATIONNAME, "Manual message publihser");
            cf.setBooleanProperty(WMQConstants.USER_AUTHENTICATION_MQCSP, true);
            cf.setStringProperty(WMQConstants.USERID, APP_USER);
            cf.setStringProperty(WMQConstants.PASSWORD, APP_PASSWORD);

            //cf.setStringProperty(WMQConstants.WMQ_SSL_CIPHER_SUITE, "*TLS12");

            // Create JMS objects
            context = cf.createContext();

            destination = context.createQueue("queue:///" + QUEUE_NAME);
            ((MQDestination)destination).setTargetClient(JMSC.MQJMS_CLIENT_NONJMS_MQ);

            //long uniqueNumber = System.currentTimeMillis() % 1000;
            //TextMessage message = context.createTextMessage("Your lucky number today is " + uniqueNumber);
            TextMessage message = context.createTextMessage(MESSAGE);

            producer = context.createProducer();
            producer.send(destination, message);
            System.out.println("<INFO> : Sent message details:\n" + message);

            //consumer = context.createConsumer(destination); // autoclosable
            //String receivedMessage = consumer.receiveBody(String.class, 15000); // in ms or 15 seconds

            //System.out.println("\nReceived message:\n" + receivedMessage);

                        context.close();
return true;
            //recordSuccess();
        } catch (JMSException jmsex) {
            //recordFailure(jmsex);
            System.out.println("JMS/MQ error OCCURED!!!!");
return false;
        }

        //System.exit(status);

    }
</code>```

答: Wrap the producer.send call in its own try/catch and look for MQRC_UNKNOWN_OBJECT_NAME or other errors such as MQRC_NOT_AUTHORIZED or MQRC_Q_FULL.

Body:
I have following method to send a message to MQ , when the queue name is incorrect it throws MQRC_UNKNOWN_OBJECT_NAME error, but I want to pass the custom error (something like "queue name is not found") and let the user to continue with a correct queue name. I tried to capture the message send not successful scenario by returning the mqSend() method as false. but it doesn't work as I expected. Can someone help me out here? ( please note I'm setting the required MQ properties(QUEUE_NAME,QMGR,CHANNEL,HOST,PORT) separately.

    public boolean mqSend()
    {

        String APP_USER = ""; // User name that application uses to connect to MQ
        String APP_PASSWORD = ""; // Password that the application uses to connect to MQ

        // Variables
        JMSContext context = null;
        Destination destination = null;
        JMSProducer producer = null;
        //JMSConsumer consumer = null;

        try {
            // Create a connection factory
            JmsFactoryFactory ff = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);
            JmsConnectionFactory cf = ff.createConnectionFactory();

            // Set the properties
            cf.setStringProperty(WMQConstants.WMQ_HOST_NAME, HOST);
            cf.setIntProperty(WMQConstants.WMQ_PORT, PORT);
            cf.setStringProperty(WMQConstants.WMQ_CHANNEL, CHANNEL);
            cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT);
            cf.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER, QMGR);
            cf.setStringProperty(WMQConstants.WMQ_APPLICATIONNAME, "Manual message publihser");
            cf.setBooleanProperty(WMQConstants.USER_AUTHENTICATION_MQCSP, true);
            cf.setStringProperty(WMQConstants.USERID, APP_USER);
            cf.setStringProperty(WMQConstants.PASSWORD, APP_PASSWORD);

            //cf.setStringProperty(WMQConstants.WMQ_SSL_CIPHER_SUITE, "*TLS12");

            // Create JMS objects
            context = cf.createContext();

            destination = context.createQueue("queue:///" + QUEUE_NAME);
            ((MQDestination)destination).setTargetClient(JMSC.MQJMS_CLIENT_NONJMS_MQ);

            //long uniqueNumber = System.currentTimeMillis() % 1000;
            //TextMessage message = context.createTextMessage("Your lucky number today is " + uniqueNumber);
            TextMessage message = context.createTextMessage(MESSAGE);

            producer = context.createProducer();
            producer.send(destination, message);
            System.out.println("<INFO> : Sent message details:\n" + message);

            //consumer = context.createConsumer(destination); // autoclosable
            //String receivedMessage = consumer.receiveBody(String.class, 15000); // in ms or 15 seconds

            //System.out.println("\nReceived message:\n" + receivedMessage);

                        context.close();
return true;
            //recordSuccess();
        } catch (JMSException jmsex) {
            //recordFailure(jmsex);
            System.out.println("JMS/MQ error OCCURED!!!!");
return false;
        }

        //System.exit(status);

    }


问:
DRF is not updating the database
Here's the model:

```<code>from django.db import models
from datetime import datetime, timedelta

# Create your models here.

def set_expiration():
    return datetime.today().date() + timedelta(days=30)

class Customer(models.Model):
    email = models.EmailField(max_length=254, unique=True)
    created_on = models.DateField(auto_now_add=True)
    expires_on = models.DateField(editable=False, default=set_expiration())

    def __str__(self):
        return self.email
</code>```

And this is the view:

```<code>@api_view(['POST'])
def update_customer(request):
    try:
        customer = Customer.objects.get(email=request.data['email'])
    except ObjectDoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    serializer = CustomerSerializer(instance=customer, data=request.data)

    if serializer.is_valid(raise_exception=True):
        serializer.save()

    return Response(serializer.data)

</code>```

And the serilizer:

```<code>from rest_framework import serializers
from .models import Customer

class CustomerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Customer
        fields = '__all__'
</code>```

At this moment I have a record in database with expires_on set to 2022-03-14 and I want to update that to 2024-12-12 so I call the endpoint with the following data:

```<code>{
    "email": "myemail@mydomain.com",
    "expires_on": "2024-12-12"
}
</code>```

The view returns this:

```<code>{
    "id": 1,
    "email": "myemail@mydomain.com",
    "created_on": "2022-02-12",
    "expires_on": "2022-03-14"
}
</code>```

This is the existing data. expires_on is not updated with the new value.

I get no error and no exception. It just doesn't work.

答:
Remove editable=False from expires_on field.

```<code>class Customer(models.Model):
    email = models.EmailField(max_length=254, unique=True)
    created_on = models.DateField(auto_now_add=True)
    expires_on = models.DateField(default=set_expiration())

    def __str__(self):
        return self.email
</code>```

Title: DRF is not updating the database

Body:
Here's the model:

from django.db import models
from datetime import datetime, timedelta

# Create your models here.

def set_expiration():
    return datetime.today().date() + timedelta(days=30)

class Customer(models.Model):
    email = models.EmailField(max_length=254, unique=True)
    created_on = models.DateField(auto_now_add=True)
    expires_on = models.DateField(editable=False, default=set_expiration())

    def __str__(self):
        return self.email

And this is the view:

@api_view(['POST'])
def update_customer(request):
    try:
        customer = Customer.objects.get(email=request.data['email'])
    except ObjectDoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    serializer = CustomerSerializer(instance=customer, data=request.data)

    if serializer.is_valid(raise_exception=True):
        serializer.save()

    return Response(serializer.data)

And the serilizer:

from rest_framework import serializers
from .models import Customer

class CustomerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Customer
        fields = '__all__'

At this moment I have a record in database with expires_on set to 2022-03-14 and I want to update that to 2024-12-12 so I call the endpoint with the following data:

{
    "email": "myemail@mydomain.com",
    "expires_on": "2024-12-12"
}

The view returns this:

{
    "id": 1,
    "email": "myemail@mydomain.com",
    "created_on": "2022-02-12",
    "expires_on": "2022-03-14"
}

This is the existing data. expires_on is not updated with the new value.

I get no error and no exception. It just doesn't work.

Body:
Remove editable=False from expires_on field.

class Customer(models.Model):
    email = models.EmailField(max_length=254, unique=True)
    created_on = models.DateField(auto_now_add=True)
    expires_on = models.DateField(default=set_expiration())

    def __str__(self):
        return self.email


问:
SwiftUI Conditionally disable modifier
So say I want to conditionally enable or disable a modifier on a view such as matched geometry effect? As silly as this looks, how would I do this?</p>
```<code>Image("Test")
   .scaleEffect(self.selectedImageScale)
   .offset(self.selectedImageOffset)
   .aspectRatio(contentMode: .fit)
if disabled {
   .matchedGeometryEffect(id: selectedImage.id, in: self.namespace)
}
</code>```

答:
You can achieve it with a simple extension on the View:

```<code>extension View {

    @ViewBuilder
    public func `if`<T: View, U: View>(
        _ condition: Bool,
        then modifierT: (Self) -> T,
        else modifierU: (Self) -> U
    ) -> some View {

        if condition { modifierT(self) }
        else { modifierU(self) }
    }
}
</code>```

Now you can use it like:

```<code>Image("Test")
   .scaleEffect(self.selectedImageScale)
   .offset(self.selectedImageOffset)
   .aspectRatio(contentMode: .fit)

   .if(disabled) { view in
       view.matchedGeometryEffect(id: selectedImage.id, in: self.namespace)
   } else { $0 } // returns unmodified view
</code>```

Title: SwiftUI Conditionally disable modifier

Body:
So say I want to conditionally enable or disable a modifier on a view such as matched geometry effect? As silly as this looks, how would I do this?

Image("Test")
   .scaleEffect(self.selectedImageScale)
   .offset(self.selectedImageOffset)
   .aspectRatio(contentMode: .fit)
if disabled {
   .matchedGeometryEffect(id: selectedImage.id, in: self.namespace)
}

Body:
You can achieve it with a simple extension on the View:

extension View {

    @ViewBuilder
    public func `if`<T: View, U: View>(
        _ condition: Bool,
        then modifierT: (Self) -> T,
        else modifierU: (Self) -> U
    ) -> some View {

        if condition { modifierT(self) }
        else { modifierU(self) }
    }
}

Now you can use it like:

Image("Test")
   .scaleEffect(self.selectedImageScale)
   .offset(self.selectedImageOffset)
   .aspectRatio(contentMode: .fit)

   .if(disabled) { view in
       view.matchedGeometryEffect(id: selectedImage.id, in: self.namespace)
   } else { $0 } // returns unmodified view


问:
How use custom color mapping and vertically align images in matplotlib?
Image matrix contains only 0,1,2,3 values.
Can you please suggest how to:

Convert: [(0, white color),(1, red color),(2, green color),(3, blue color)] when displayed using matplotlib.

Align images vertically bottom.

Code:

```<code>from matplotlib import pyplot as plt
import numpy as np

img1 = np.random.randint(0, 3, (1, 4)).tolist()
img2 = np.random.randint(0, 3, (2, 4)).tolist()
img3 = np.random.randint(0, 3, (4, 4)).tolist()

fig = plt.figure()
fig.set_size_inches(10, 5)

ax0 = plt.subplot(1, 3, 1)
ax0.pcolor(img1, edgecolors='k', linewidths=2, vmin=0, vmax=4, cmap='gray')
ax0.set_aspect('equal')
ax0.axis("off")
plt.gca().invert_yaxis()

ax1 = plt.subplot(1, 3, 2)
ax1.pcolor(img2, edgecolors='k', linewidths=2, vmin=0, vmax=4, cmap='gray')
ax1.set_aspect('equal')
ax1.axis("off")
plt.gca().invert_yaxis()

ax2 = plt.subplot(1, 3, 3)
ax2.pcolor(img3, edgecolors='k', linewidths=2, vmin=0, vmax=4, cmap='gray')
ax2.set_aspect('equal')
ax2.axis("off")
plt.gca().invert_yaxis()

plt.show()
</code>```

答:
You can use a ListedColormap for this (also, the high limit for np.random.rand is excluded, so to get numbers from 0 to 3, you should have np.random.rand(0, 4, ...). You can use ax.set_anchor('S') (for all axis) to align the plots to the bottom:

```<code>from matplotlib import pyplot as plt
import numpy as np
import matplotlib.colors

img1 = np.random.randint(0, 4, (1, 4)).tolist()
img2 = np.random.randint(0, 4, (2, 4)).tolist()
img3 = np.random.randint(0, 4, (4, 4)).tolist()

print(img1)
print(img2)
print(img3)

fig = plt.figure()
fig.set_size_inches(10, 5)

cmap = matplotlib.colors.ListedColormap(["white", "red", "green", "blue"])

ax0 = plt.subplot(1, 3, 1)
ax0.pcolor(img1, edgecolors='k', linewidths=2, vmin=0, vmax=4, cmap=cmap)
ax0.set_aspect('equal')
ax0.axis("off")
ax0.set_anchor('S')
plt.gca().invert_yaxis()

ax1 = plt.subplot(1, 3, 2)
ax1.pcolor(img2, edgecolors='k', linewidths=2, vmin=0, vmax=4, cmap=cmap)
ax1.set_aspect('equal')
ax1.axis("off")
ax1.set_anchor('S')
plt.gca().invert_yaxis()

ax2 = plt.subplot(1, 3, 3)
ax2.pcolor(img3, edgecolors='k', linewidths=2, vmin=0, vmax=4, cmap=cmap)
ax2.set_aspect('equal')
ax2.axis("off")
ax2.set_anchor('S')
plt.gca().invert_yaxis()

plt.show()
</code>```

Example output:

The arrays:

```<code>[[1, 1, 2, 1]]
[[1, 2, 3, 1], [3, 1, 0, 3]]
[[0, 1, 2, 1], [0, 2, 1, 3], [0, 1, 1, 3], [3, 1, 3, 3]]
</code>```

The images:

Body:
Image matrix contains only 0,1,2,3 values.
Can you please suggest how to:

Convert: [(0, white color),(1, red color),(2, green color),(3, blue color)] when displayed using matplotlib.

Align images vertically bottom.

Code:

from matplotlib import pyplot as plt
import numpy as np

img1 = np.random.randint(0, 3, (1, 4)).tolist()
img2 = np.random.randint(0, 3, (2, 4)).tolist()
img3 = np.random.randint(0, 3, (4, 4)).tolist()

fig = plt.figure()
fig.set_size_inches(10, 5)

ax0 = plt.subplot(1, 3, 1)
ax0.pcolor(img1, edgecolors='k', linewidths=2, vmin=0, vmax=4, cmap='gray')
ax0.set_aspect('equal')
ax0.axis("off")
plt.gca().invert_yaxis()

ax1 = plt.subplot(1, 3, 2)
ax1.pcolor(img2, edgecolors='k', linewidths=2, vmin=0, vmax=4, cmap='gray')
ax1.set_aspect('equal')
ax1.axis("off")
plt.gca().invert_yaxis()

ax2 = plt.subplot(1, 3, 3)
ax2.pcolor(img3, edgecolors='k', linewidths=2, vmin=0, vmax=4, cmap='gray')
ax2.set_aspect('equal')
ax2.axis("off")
plt.gca().invert_yaxis()

plt.show()

Body:
You can use a ListedColormap for this (also, the high limit for np.random.rand is excluded, so to get numbers from 0 to 3, you should have np.random.rand(0, 4, ...). You can use ax.set_anchor('S') (for all axis) to align the plots to the bottom:

from matplotlib import pyplot as plt
import numpy as np
import matplotlib.colors

img1 = np.random.randint(0, 4, (1, 4)).tolist()
img2 = np.random.randint(0, 4, (2, 4)).tolist()
img3 = np.random.randint(0, 4, (4, 4)).tolist()

print(img1)
print(img2)
print(img3)

fig = plt.figure()
fig.set_size_inches(10, 5)

cmap = matplotlib.colors.ListedColormap(["white", "red", "green", "blue"])

ax0 = plt.subplot(1, 3, 1)
ax0.pcolor(img1, edgecolors='k', linewidths=2, vmin=0, vmax=4, cmap=cmap)
ax0.set_aspect('equal')
ax0.axis("off")
ax0.set_anchor('S')
plt.gca().invert_yaxis()

ax1 = plt.subplot(1, 3, 2)
ax1.pcolor(img2, edgecolors='k', linewidths=2, vmin=0, vmax=4, cmap=cmap)
ax1.set_aspect('equal')
ax1.axis("off")
ax1.set_anchor('S')
plt.gca().invert_yaxis()

ax2 = plt.subplot(1, 3, 3)
ax2.pcolor(img3, edgecolors='k', linewidths=2, vmin=0, vmax=4, cmap=cmap)
ax2.set_aspect('equal')
ax2.axis("off")
ax2.set_anchor('S')
plt.gca().invert_yaxis()

plt.show()

Example output:

The arrays:

[[1, 1, 2, 1]]
[[1, 2, 3, 1], [3, 1, 0, 3]]
[[0, 1, 2, 1], [0, 2, 1, 3], [0, 1, 1, 3], [3, 1, 3, 3]]

The images:


问:
Theory of storing a number and text in same SQL field
I have a three tables

Results:
TestID
TestCode
Value

Tests:
TestID
TestType
SysCodeID

SystemCodes
SysCodeID
ParentSysCodeID
Description

The question I have is for when the user is entering data into the results table.

The formatting code when the row gets the focus changes the value field to a dropdown combobox if the testCode is of type SystemList.  The drop down has a list of all the system codes that have a parentsyscodeID of the test.SysCodeID.  When the user chooses a value in the list it translates into a number which goes into the value field.

The datatype of the Results.Value field is integer.  I made it an integer instead of a string because when reporting it is easier to do calculations and sorting if it is a number.  There are issues if you are putting integer/decimal value into a string field.  As well, when the system was being designed they only wanted numbers in there.

The users now want to put strings into the value field as well as numbers/values from a list and I'm wondering what the best way of doing that would be.

Would it be bad practice to convert the field over to a string and then store both strings and integers in the same field?  There are different issues related to this one but i'm not sure if any are a really big deal.

Should I add another column into the table of string datatype and  if the test is a string type then put the data the user enters into the different field.

Another option would be to create a 1-1 relationship to another table and if the user types in a string into the value field it adds it into the new table with a key of a number.

Anyone have any interesting ideas?

答:
One of two solutions comes to mind.  It kind of depends on what you're doing with the numbers.  If they just represent a choice of some kind, then pick one.  If you need to do math on it (sorting, conversion, etc..) then pick another.

Change the column to be a varchar, and then either put numbers or text in it.  Sorting numerically will suck, but hey, it's one column.

Have both a varchar column for the text, and an int column for the number.  Use a view to hide the differences, and to control the sorting if necessary.  You can coalesce the two columns together if you don't care about whether you're looking at numbers or text.

OwnerDisplayName: Jaydel Gluckie

LastEditorDisplayName: Jonathan Leffler

OwnerDisplayName: clintp