问:
What is the best approach for bulk cleaning a database table that has a large amount of duplicated data loaded every day (snowflake db)
Thanks in advance for reading this, I hope I explain my problem.

In one of our domains, we have a pipeline (Multiple) where data flows from S3 into a snowflake staging table using airflow. The data itself originates from a number of different applications but the process is always the same. The data is extracted from the application by the support teams (multiple support teams across multiple countries, using different technologies), then into AWS S3 and then bulk loaded into snowflake. Due to limitations on the data from source their often isn't any filter on the data itself and effectively the staging table is loaded with the raw CSV every single day, a file date column is added to the data itself. The result is that we have tables that have been loaded with the same data every single day since 2009.

However the data does change, from day to day a column value will change and so the file date is very useful in tracking changed attributes and something that I want to exploit. Further if the data was cleansed we would need approximately 1% of the data.

These tables are huge some contain around 16 trillion rows but can we be quite narrow.

I would like to optimally loop through each days worth of data and then only load into the staging tables new data as apposed to just loading everything each day.

I have tried the following

A query that windows over the entire set and compares the hashed value of each row (minus the file date) and then only returns if it did not appear in the previous dates data set. This works but not for the larger tables as the warehouse starts to write to disk and then it takes hours.

A day by day loop that looks at each file date data set and compares to the previous day and only loads the difference, this takes to long on the initial clean of the tables but is what I am doing once the data has been cleaned and will form the initial load procedure.

The current solution is where I dynamically create multiple minus set statement where I look at each day minus the day before then batch these into blocks of 10-20 based of the average daily row size so as an example

```<code>INSERT INTO TEMP TABLE
(Select * FROM TABLE A WHERE FILE_DATE = 040123
MINUS
Select * FROM TABLE A WHERE FILE_DATE = 030123)
UNION ALL
(Select * FROM TABLE A WHERE FILE_DATE = 030123
MINUS
Select * FROM TABLE A WHERE FILE_DATE = 020123)
</code>```

etc...

This is not pretty though does work however its taking me around 12 hours to process 70 odd tables.

I would like advice on if their is another approach.

Please bear in mind that I am limited to using snowflake due to resourcing issues and politics.

Any guidance and ideas would be much appreciated.

Regards

Body:
Thanks in advance for reading this, I hope I explain my problem.

In one of our domains, we have a pipeline (Multiple) where data flows from S3 into a snowflake staging table using airflow. The data itself originates from a number of different applications but the process is always the same. The data is extracted from the application by the support teams (multiple support teams across multiple countries, using different technologies), then into AWS S3 and then bulk loaded into snowflake. Due to limitations on the data from source their often isn't any filter on the data itself and effectively the staging table is loaded with the raw CSV every single day, a file date column is added to the data itself. The result is that we have tables that have been loaded with the same data every single day since 2009.

However the data does change, from day to day a column value will change and so the file date is very useful in tracking changed attributes and something that I want to exploit. Further if the data was cleansed we would need approximately 1% of the data.

These tables are huge some contain around 16 trillion rows but can we be quite narrow.

I would like to optimally loop through each days worth of data and then only load into the staging tables new data as apposed to just loading everything each day.

I have tried the following

A query that windows over the entire set and compares the hashed value of each row (minus the file date) and then only returns if it did not appear in the previous dates data set. This works but not for the larger tables as the warehouse starts to write to disk and then it takes hours.

A day by day loop that looks at each file date data set and compares to the previous day and only loads the difference, this takes to long on the initial clean of the tables but is what I am doing once the data has been cleaned and will form the initial load procedure.

The current solution is where I dynamically create multiple minus set statement where I look at each day minus the day before then batch these into blocks of 10-20 based of the average daily row size so as an example

INSERT INTO TEMP TABLE
(Select * FROM TABLE A WHERE FILE_DATE = 040123
MINUS
Select * FROM TABLE A WHERE FILE_DATE = 030123)
UNION ALL
(Select * FROM TABLE A WHERE FILE_DATE = 030123
MINUS
Select * FROM TABLE A WHERE FILE_DATE = 020123)

etc...

This is not pretty though does work however its taking me around 12 hours to process 70 odd tables.

I would like advice on if their is another approach.

Please bear in mind that I am limited to using snowflake due to resourcing issues and politics.

Any guidance and ideas would be much appreciated.

Regards


来源: stackexchange

问:
How to print sequelize associations in react?
So I have a sequelize model (In this case the name is "Orders"), and this particular model has an association (With the "Providers" model) so when I console.log the information that came from a function the information is the following.

```<code>Json Object{
id: 20
isPayed: false
orderArrive: "2022-08-26"
provider.email: "provider@mail.com"
provider.id: 14
provider.name: "provider"
provider.phone: "6183802232"
provider.phone2: null
providerId: 14
total: 850
}
</code>```

provider.name, provider.phone... these are the data from the "Providers" model (table). If I tried to print any information that is not from the association it's printed with any problems, but when I try to print the info from the association it just doesn't show up, it's weird because the JSON object includes the information.

I tried to print it from different approaches but i don't know how this actually works.

ContentLicense: CC BY-SA 4.0

Body:
So I have a sequelize model (In this case the name is "Orders"), and this particular model has an association (With the "Providers" model) so when I console.log the information that came from a function the information is the following.

Json Object{
id: 20
isPayed: false
orderArrive: "2022-08-26"
provider.email: "provider@mail.com"
provider.id: 14
provider.name: "provider"
provider.phone: "6183802232"
provider.phone2: null
providerId: 14
total: 850
}

provider.name, provider.phone... these are the data from the "Providers" model (table). If I tried to print any information that is not from the association it's printed with any problems, but when I try to print the info from the association it just doesn't show up, it's weird because the JSON object includes the information.

I tried to print it from different approaches but i don't know how this actually works.


问:
Fail ctOpen in python for citect . OSError: [WinError -532462766] Windows Error 0xe0434352
I am trying to write an API in python for reading and writing tags from citect app, so I am loading the dlls files: "Ctapi.dll" and else of "Aveva-Citect 2018R2" details:

Python version:3.6.5/3.8.0 32 bit

Citect version:2018 R2

CtAPI dlls: I took from the folder: C:...\Citect 2018 R2\Citect SCADA 2018 R2\Extras\CtApi\CtApi.Win32.Redist.zip

The program fails when I try to call to the function:"ctOpen"

```<code>import ctypes
import os

IP_ADDRESS = "172.16.11.222"
CITECT_USERNAME = "Analyst"
CITECT_PASSWORD = "1"
CITECT_PATH = "C:/Users/ryfrach/PycharmProjects/TrainingCallDll/dlls/CtApi32"
CITECT_MODE = 0x00000002
os.chdir(CITECT_PATH)

ct_api = ctypes.CDLL(CITECT_PATH + '/CtApi.dll')
function = ct_api.ctOpen
function.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p,ctypes.c_wchar_p,ctypes.c_int]
function(IP_ADDRESS,CITECT_USERNAME,CITECT_PASSWORD,CITECT_MODE)
</code>```

This is the error I get:

```<code>File "C:/Users/ryfrach/PycharmProjects/TrainingCallDll/main.py", line 27, in <module>
function(IP_ADDRESS,CITECT_USERNAME,CITECT_PASSWORD,CITECT_MODE)
OSError: [WinError -532462766] Windows Error 0xe0434352
</code>```

Does someone know the solution? PLEASE!!

Body:
I am trying to write an API in python for reading and writing tags from citect app, so I am loading the dlls files: "Ctapi.dll" and else of "Aveva-Citect 2018R2" details:

Python version:3.6.5/3.8.0 32 bit

Citect version:2018 R2

CtAPI dlls: I took from the folder: C:...\Citect 2018 R2\Citect SCADA 2018 R2\Extras\CtApi\CtApi.Win32.Redist.zip

The program fails when I try to call to the function:"ctOpen"

import ctypes
import os

IP_ADDRESS = "172.16.11.222"
CITECT_USERNAME = "Analyst"
CITECT_PASSWORD = "1"
CITECT_PATH = "C:/Users/ryfrach/PycharmProjects/TrainingCallDll/dlls/CtApi32"
CITECT_MODE = 0x00000002
os.chdir(CITECT_PATH)

ct_api = ctypes.CDLL(CITECT_PATH + '/CtApi.dll')
function = ct_api.ctOpen
function.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p,ctypes.c_wchar_p,ctypes.c_int]
function(IP_ADDRESS,CITECT_USERNAME,CITECT_PASSWORD,CITECT_MODE)

This is the error I get:

File "C:/Users/ryfrach/PycharmProjects/TrainingCallDll/main.py", line 27, in <module>
function(IP_ADDRESS,CITECT_USERNAME,CITECT_PASSWORD,CITECT_MODE)
OSError: [WinError -532462766] Windows Error 0xe0434352

Does someone know the solution? PLEASE!!


问:
AttributeError: module 'object_detection.metrics.coco_evaluation' has no attribute 'CocoKeypointEvaluator'
Folks, I'm trying to run this model_main_tf2.py and I'm getting the below error.

```<code>---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
File ~/Documents/Indian_License_Plate_Recognition/models/research/object_detection/model_main_tf2.py:31
     29 from absl import flags
     30 import tensorflow.compat.v2 as tf
---> 31 from object_detection import model_lib_v2
     33 flags.DEFINE_string('pipeline_config_path', None, 'Path to pipeline config '
     34                     'file.')
     35 flags.DEFINE_integer('num_train_steps', None, 'Number of train steps.')

File ~/anaconda3/envs/tfsetup/lib/python3.10/site-packages/object_detection/model_lib_v2.py:29
     26 import numpy as np
     27 import tensorflow.compat.v1 as tf
---> 29 from object_detection import eval_util
     30 from object_detection import inputs
     31 from object_detection import model_lib

File ~/anaconda3/envs/tfsetup/lib/python3.10/site-packages/object_detection/eval_util.py:53
     44 EVAL_KEYPOINT_METRIC = 'coco_keypoint_metrics'
     46 # A dictionary of metric names to classes that implement the metric. The classes
     47 # in the dictionary must implement
     48 # utils.object_detection_evaluation.DetectionEvaluator interface.
     49 EVAL_METRICS_CLASS_DICT = {
     50     'coco_detection_metrics':
     51         coco_evaluation.CocoDetectionEvaluator,
     52     'coco_keypoint_metrics':
---> 53         coco_evaluation.CocoKeypointEvaluator,
     54     'coco_mask_metrics':
     55         coco_evaluation.CocoMaskEvaluator,
     56     'coco_panoptic_metrics':
     57         coco_evaluation.CocoPanopticSegmentationEvaluator,
     58     'lvis_mask_metrics':
     59         lvis_evaluation.LVISMaskEvaluator,
     60     'oid_challenge_detection_metrics':
     61         object_detection_evaluation.OpenImagesDetectionChallengeEvaluator,
     62     'oid_challenge_segmentation_metrics':
     63         object_detection_evaluation
     64         .OpenImagesInstanceSegmentationChallengeEvaluator,
     65     'pascal_voc_detection_metrics':
     66         object_detection_evaluation.PascalDetectionEvaluator,
     67     'weighted_pascal_voc_detection_metrics':
     68         object_detection_evaluation.WeightedPascalDetectionEvaluator,
     69     'precision_at_recall_detection_metrics':
     70         object_detection_evaluation.PrecisionAtRecallDetectionEvaluator,
     71     'pascal_voc_instance_segmentation_metrics':
     72         object_detection_evaluation.PascalInstanceSegmentationEvaluator,
     73     'weighted_pascal_voc_instance_segmentation_metrics':
     74         object_detection_evaluation.WeightedPascalInstanceSegmentationEvaluator,
     75     'oid_V2_detection_metrics':
     76         object_detection_evaluation.OpenImagesDetectionEvaluator,
     77 }
     79 EVAL_DEFAULT_METRIC = 'coco_detection_metrics'
     82 def write_metrics(metrics, global_step, summary_dir):

AttributeError: module 'object_detection.metrics.coco_evaluation' has no attribute 'CocoKeypointEvaluator'

</code>```

When I check my coco_evaluation.py file in my local, I'm able to find this class CocoKeypointEvaluator. Can someone please help me on how I can resolve this issue.

I tried re-installing object detection api, tensorflow and pycocotools, but nothing helps.

Body:
Folks, I'm trying to run this model_main_tf2.py and I'm getting the below error.

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
File ~/Documents/Indian_License_Plate_Recognition/models/research/object_detection/model_main_tf2.py:31
     29 from absl import flags
     30 import tensorflow.compat.v2 as tf
---> 31 from object_detection import model_lib_v2
     33 flags.DEFINE_string('pipeline_config_path', None, 'Path to pipeline config '
     34                     'file.')
     35 flags.DEFINE_integer('num_train_steps', None, 'Number of train steps.')

File ~/anaconda3/envs/tfsetup/lib/python3.10/site-packages/object_detection/model_lib_v2.py:29
     26 import numpy as np
     27 import tensorflow.compat.v1 as tf
---> 29 from object_detection import eval_util
     30 from object_detection import inputs
     31 from object_detection import model_lib

File ~/anaconda3/envs/tfsetup/lib/python3.10/site-packages/object_detection/eval_util.py:53
     44 EVAL_KEYPOINT_METRIC = 'coco_keypoint_metrics'
     46 # A dictionary of metric names to classes that implement the metric. The classes
     47 # in the dictionary must implement
     48 # utils.object_detection_evaluation.DetectionEvaluator interface.
     49 EVAL_METRICS_CLASS_DICT = {
     50     'coco_detection_metrics':
     51         coco_evaluation.CocoDetectionEvaluator,
     52     'coco_keypoint_metrics':
---> 53         coco_evaluation.CocoKeypointEvaluator,
     54     'coco_mask_metrics':
     55         coco_evaluation.CocoMaskEvaluator,
     56     'coco_panoptic_metrics':
     57         coco_evaluation.CocoPanopticSegmentationEvaluator,
     58     'lvis_mask_metrics':
     59         lvis_evaluation.LVISMaskEvaluator,
     60     'oid_challenge_detection_metrics':
     61         object_detection_evaluation.OpenImagesDetectionChallengeEvaluator,
     62     'oid_challenge_segmentation_metrics':
     63         object_detection_evaluation
     64         .OpenImagesInstanceSegmentationChallengeEvaluator,
     65     'pascal_voc_detection_metrics':
     66         object_detection_evaluation.PascalDetectionEvaluator,
     67     'weighted_pascal_voc_detection_metrics':
     68         object_detection_evaluation.WeightedPascalDetectionEvaluator,
     69     'precision_at_recall_detection_metrics':
     70         object_detection_evaluation.PrecisionAtRecallDetectionEvaluator,
     71     'pascal_voc_instance_segmentation_metrics':
     72         object_detection_evaluation.PascalInstanceSegmentationEvaluator,
     73     'weighted_pascal_voc_instance_segmentation_metrics':
     74         object_detection_evaluation.WeightedPascalInstanceSegmentationEvaluator,
     75     'oid_V2_detection_metrics':
     76         object_detection_evaluation.OpenImagesDetectionEvaluator,
     77 }
     79 EVAL_DEFAULT_METRIC = 'coco_detection_metrics'
     82 def write_metrics(metrics, global_step, summary_dir):

AttributeError: module 'object_detection.metrics.coco_evaluation' has no attribute 'CocoKeypointEvaluator'

When I check my coco_evaluation.py file in my local, I'm able to find this class CocoKeypointEvaluator. Can someone please help me on how I can resolve this issue.

I tried re-installing object detection api, tensorflow and pycocotools, but nothing helps.


问:
Add colors to ascii table with discordjs
I've created an ascii table using ascii-table3 that gets posted to discord. The table gets posted no problem with no issues like in pic below, but I'm trying to integrate colors to the table, but can't seem to get that part working. As far as I know colors only work with code blocks so I'm using inlineCode from @discordjs/builders to put the ascii table inside of, but it doesn't seem to recognize the markdown language. When I try to add markdown language it breaks the table like this when doing table.addRow('```diff\n+' + position.value + 'n\n```') for a row. Adding newLines does seem problematic though with ascii-table3 so perhaps there's a better way...

So my question is how can I build a table in discord and add colors? Maybe a different library or my syntax might be off, but I don't think it is. I know that markdown syntax is sensitive to things like spaces though so maybe that is the problem... I appreciate any help!

UPDATED

```<code>  for (let position of positions) {

         table.addRow(
            position.value,
            position.value,
            position.value,
            position.value,
            position.value,
            position.value,
            '+' + position.value
        );
    }
    table.setAlign(1, AlignmentEnum.CENTER);
    table.setAlign(2, AlignmentEnum.CENTER);
    table.setAlign(3, AlignmentEnum.CENTER);
    table.setAlign(4, AlignmentEnum.CENTER);
    table.setAlign(5, AlignmentEnum.CENTER);
    table.setAlign(6, AlignmentEnum.CENTER);
    table.setAlign(7, AlignmentEnum.CENTER);

    table.setStyle('unicode-single');

    return inlineCode('```diff\n' + table.toString() + '```');
</code>```

[![enter image description here][3]][3]

Body:
I've created an ascii table using ascii-table3 that gets posted to discord. The table gets posted no problem with no issues like in pic below, but I'm trying to integrate colors to the table, but can't seem to get that part working. As far as I know colors only work with code blocks so I'm using inlineCode from @discordjs/builders to put the ascii table inside of, but it doesn't seem to recognize the markdown language. When I try to add markdown language it breaks the table like this when doing table.addRow('```diff\n+' + position.value + 'n\n```') for a row. Adding newLines does seem problematic though with ascii-table3 so perhaps there's a better way...

So my question is how can I build a table in discord and add colors? Maybe a different library or my syntax might be off, but I don't think it is. I know that markdown syntax is sensitive to things like spaces though so maybe that is the problem... I appreciate any help!

UPDATED

  for (let position of positions) {

         table.addRow(
            position.value,
            position.value,
            position.value,
            position.value,
            position.value,
            position.value,
            '+' + position.value
        );
    }
    table.setAlign(1, AlignmentEnum.CENTER);
    table.setAlign(2, AlignmentEnum.CENTER);
    table.setAlign(3, AlignmentEnum.CENTER);
    table.setAlign(4, AlignmentEnum.CENTER);
    table.setAlign(5, AlignmentEnum.CENTER);
    table.setAlign(6, AlignmentEnum.CENTER);
    table.setAlign(7, AlignmentEnum.CENTER);

    table.setStyle('unicode-single');

    return inlineCode('```diff\n' + table.toString() + '```');

[![enter image description here][3]][3]


问:
Flutter Try-Catch block is not catching errors in local_auth plugin
I am calling LocalAuth.Authenticate() when a button is pressed. I tried to run the app with no Passcode/PIN set and therefore it should raise a "NotAvailable" error. But this error is not caught by the try-catch block and instead just outputs the error in debug console. Any help is appreciated!

Here's my home_page.dart code:

```<code>                     TextButton(
                        child: Text('YES'),
                        onPressed: () async {
                          try {
                            final authenticated = await LocalAuth.authenticate();
                            print(authenticated);
                            if (authenticated) {
                              DatabaseHelper.instance.deleteModel(id as int);
                              Navigator.pop(context);
                            }
                          } on PlatformException catch (e) {
                            print(e);
                          }
                        },
                      )
</code>```

Debug Console output:

I/flutter (10972): error PlatformException(NotAvailable, Required security features not enabled, null, null)

Body:
I am calling LocalAuth.Authenticate() when a button is pressed. I tried to run the app with no Passcode/PIN set and therefore it should raise a "NotAvailable" error. But this error is not caught by the try-catch block and instead just outputs the error in debug console. Any help is appreciated!

Here's my home_page.dart code:

                     TextButton(
                        child: Text('YES'),
                        onPressed: () async {
                          try {
                            final authenticated = await LocalAuth.authenticate();
                            print(authenticated);
                            if (authenticated) {
                              DatabaseHelper.instance.deleteModel(id as int);
                              Navigator.pop(context);
                            }
                          } on PlatformException catch (e) {
                            print(e);
                          }
                        },
                      )

Debug Console output:

I/flutter (10972): error PlatformException(NotAvailable, Required security features not enabled, null, null)


问:
is there a way to change the CAS APEREO collection structure?
I am planning to implement CAS with MongoDB authentication and also planning to use existing MongoDB collection which is not following the expected Document scheme as mentioned in apreo documentation.

As per documents,

Accounts are expected to be found as such in collections:

```<code>{
    "username": "casuser",
    "password": "34598dfkjdjk3487jfdkh874395",
    "first_name": "john",
    "last_name": "smith"
}
</code>```

is there way to customize the username and password attributes something like below

```<code>{
    "_id" : "000debf7-ee17-42ec-b267-9028b721cd57",
    "firstName" : "Steve Ward",
    "lastName" : "Steve Ward",
    "emailAddress1" : "test@inter.com",
    "status" : "active",
    "users" : [
        {
            "userName" : "weldoneinc",
            "password" : "KJH8u3lRYvm82EbiGjKZs7exPbY=",
            "createUser" : "TEST",
            "createDate" : ISODate("2020-05-22T15:28:54.439+0000"),
            "updateUser" : "TEST",
            "updateDate" : ISODate("2020-05-22T15:28:54.439+0000")
            }
            ]

}

</code>```

Body:
I am planning to implement CAS with MongoDB authentication and also planning to use existing MongoDB collection which is not following the expected Document scheme as mentioned in apreo documentation.

As per documents,

Accounts are expected to be found as such in collections:

{
    "username": "casuser",
    "password": "34598dfkjdjk3487jfdkh874395",
    "first_name": "john",
    "last_name": "smith"
}

is there way to customize the username and password attributes something like below

{
    "_id" : "000debf7-ee17-42ec-b267-9028b721cd57",
    "firstName" : "Steve Ward",
    "lastName" : "Steve Ward",
    "emailAddress1" : "test@inter.com",
    "status" : "active",
    "users" : [
        {
            "userName" : "weldoneinc",
            "password" : "KJH8u3lRYvm82EbiGjKZs7exPbY=",
            "createUser" : "TEST",
            "createDate" : ISODate("2020-05-22T15:28:54.439+0000"),
            "updateUser" : "TEST",
            "updateDate" : ISODate("2020-05-22T15:28:54.439+0000")
            }
            ]

}


问:
Build python package using swig and setuptools
I have a dll file that I am wrapping using swig.
Then I want to create a package to distribute the python extension.

The folder structure looks like:

```<code>- myPackage
   - __init__.py
   - my_interface.i
   - my_header.hpp
   - my_dll.dll
   - my_lib.lib
- setup.py
- pyproject.toml
- MANIFEST.in
</code>```

My setup.py file looks like:

```<code>from setuptools import setup, Extension, find_packages
my_module = Extension('_MyModule',
                           sources=['myPackage/my_interface_wrap.cpp'],
                           library_dirs=['myPackage'],
                           libraries= ["my_lib"],
                           include_dirs=['myPackage']
                           )

# my_module = Extension('_MyModule',
#                            sources=['myPackage/my_interface.i'],
#                            swig_opts=["-c++", "-ImyPackage"],
#                            library_dirs=['myPackage'],
#                            libraries= ["my_lib"],
#                            include_dirs=['myPackage']
#                            )

setup (name = 'MyPackage',
       version = '1.0',
       author      = "",
       description = """SWIG wrapper""",
       ext_modules = [my_module],
       py_modules = ["myModule.myModule"],
       package=["myPackage"],
       package_data={"myPackage": ["my_dll.dll"]},
       )
</code>```

I would like setup tools to run swig, create the python module and build the extension (create the .pyd file). Then I would like to have everything in an archive to publish the package.

To build the package I use: python -m build

The problem I have is that with the non commented extension definition, the extension is not packaged in the archive. I have no error message from the build.

In order for the build to work, I need to first run swig and then build the package.
In that case I use the commented extension definition.

```<code> swig -c++ -python myPackage/my_interface.i
 python -m build
</code>```

Something must be wrong in the setup.py file.

There is not problem in the .i file since when doing all steps manually, the wrapper works.

Body:
I have a dll file that I am wrapping using swig.
Then I want to create a package to distribute the python extension.

The folder structure looks like:

- myPackage
   - __init__.py
   - my_interface.i
   - my_header.hpp
   - my_dll.dll
   - my_lib.lib
- setup.py
- pyproject.toml
- MANIFEST.in

My setup.py file looks like:

from setuptools import setup, Extension, find_packages
my_module = Extension('_MyModule',
                           sources=['myPackage/my_interface_wrap.cpp'],
                           library_dirs=['myPackage'],
                           libraries= ["my_lib"],
                           include_dirs=['myPackage']
                           )

# my_module = Extension('_MyModule',
#                            sources=['myPackage/my_interface.i'],
#                            swig_opts=["-c++", "-ImyPackage"],
#                            library_dirs=['myPackage'],
#                            libraries= ["my_lib"],
#                            include_dirs=['myPackage']
#                            )

setup (name = 'MyPackage',
       version = '1.0',
       author      = "",
       description = """SWIG wrapper""",
       ext_modules = [my_module],
       py_modules = ["myModule.myModule"],
       package=["myPackage"],
       package_data={"myPackage": ["my_dll.dll"]},
       )

I would like setup tools to run swig, create the python module and build the extension (create the .pyd file). Then I would like to have everything in an archive to publish the package.

To build the package I use: python -m build

The problem I have is that with the non commented extension definition, the extension is not packaged in the archive. I have no error message from the build.

In order for the build to work, I need to first run swig and then build the package.
In that case I use the commented extension definition.

 swig -c++ -python myPackage/my_interface.i
 python -m build

Something must be wrong in the setup.py file.

There is not problem in the .i file since when doing all steps manually, the wrapper works.


问:
React > images inside Image folder are not rendered
Problem > React > Images in image folder are not rendered.

I am currently working on a React tutorial.
When I try to render images on the page, they are not displayed.

I tried this in vsCode and Replid and got the same results.
How do I put the images in my src > Images folder and still reference and render?
The screenshots may not be very accurate, I changed the names a few times to fix the problem.

I have made sure that they are placed in my src > images folder, and reference each image with "./images/image-name.png". But that seems to be a problem.
(screenshot 1)

I put all the images in the public folder and point to the specific image with "/image-name.png" and that works.
(screenshots 2-3)

Rendering by pointing to the specific image with url works.
(screenshot 4)

[[[enter image description here](https://i.stack.imgur.com/rEAcQ.png)](https://i.stack.imgur.com/57ufp.jpg)](https://i.stack.imgur.com/q9DEV.png)


问:
replace column value one by another in mysql?
I have 10 rows.first 5 rows is gender column with "male".
second 5 rows gender column with "female".

I want mysql query to change where column "male" into "female" and "female" into "male".

Thanks for answering...

If i tried male into female . all fields will be male.


问:
Why Does Rad Studio Always Want to Dock to the Edge of the Screen
Using Rad Studio 11.2, at some point Rad Studio started wanting to dock itself to the edge of the screen, and no it's not the Windows docking feature, that is turned off and it is only Rad Studio that is doing this.

Even when you're dragging the window around the screen it's sluggish because it's looking for an edge to latch on to it seems. I've looked everywhere for a way to turn this off, it is maddening. Does anyone know how to turn this off?


问:
SQS rule with an event pattern in EventBridge not triggered
I want to create a "Rule with an event pattern" where the match is any event from SQS.

This is my CloudFormation Template:

AWSTemplateFormatVersion: '2010-09-09'
Description: CloudFormation template for EventBridge rule 'RuleSQSToLambda'
Resources:
  EventRule0:
    Type: AWS::Events::Rule
    Properties:
      Description: trigger by all sqs actions
      EventBusName: default
      EventPattern:
        source:
          - aws.sqs
      Name: RuleSQSToLambda
      State: ENABLED
      Targets:
        - Id: <some id>
          Arn: arn:aws:lambda:eu-west-2:<account id>:function:<lambda function name>
          RetryPolicy:
            MaximumRetryAttempts: 0
            MaximumEventAgeInSeconds: 60

```
<p>But no Invocations or TriggeredRules show up in the Rule monitoring when I SendMessage to a queue or create a new queue (also the lambda is not triggered).</p>
<p><strong>QUESTION:</strong> What could be the reason the EventBridge Rule is not triggered?</p>
<p>My guess: I made the same attempt with S3 events, obtaining an identical CloudFormation template but for</p>
<pre class="lang-yaml prettyprint-override"><code>      EventPattern:
        source:
          - aws.s3
</code>```

which first failed as above, until I realized I had to set Send notifications to Amazon EventBridge for all events in this bucket to On within the desired S3 bucket permissions. Then the EventBridge Rule was invoked succesfully. I tried to find this Send notifications switch for my SQS queue but I cannot find anywhere. Could this be the issue?

Body:
I want to create a "Rule with an event pattern" where the match is any event from SQS.

This is my CloudFormation Template:

AWSTemplateFormatVersion: '2010-09-09'
Description: CloudFormation template for EventBridge rule 'RuleSQSToLambda'
Resources:
  EventRule0:
    Type: AWS::Events::Rule
    Properties:
      Description: trigger by all sqs actions
      EventBusName: default
      EventPattern:
        source:
          - aws.sqs
      Name: RuleSQSToLambda
      State: ENABLED
      Targets:
        - Id: <some id>
          Arn: arn:aws:lambda:eu-west-2:<account id>:function:<lambda function name>
          RetryPolicy:
            MaximumRetryAttempts: 0
            MaximumEventAgeInSeconds: 60

But no Invocations or TriggeredRules show up in the Rule monitoring when I SendMessage to a queue or create a new queue (also the lambda is not triggered).

QUESTION: What could be the reason the EventBridge Rule is not triggered?

My guess: I made the same attempt with S3 events, obtaining an identical CloudFormation template but for

      EventPattern:
        source:
          - aws.s3

which first failed as above, until I realized I had to set Send notifications to Amazon EventBridge for all events in this bucket to On within the desired S3 bucket permissions. Then the EventBridge Rule was invoked succesfully. I tried to find this Send notifications switch for my SQS queue but I cannot find anywhere. Could this be the issue?


问:
Javascript Discord bot not running correct function
Im trying to create a discord bot, theres one command that returns the ping when /ping is typed, and another one im trying to add that restarts the bot when /restart is typed. But when I type /restart, it functions like I typed /ping and replied with the ping. I cannot find a solution to my problem so any help is appreciated. If you need more information on this please reply to me.
Here is a file called "handleCommands" with its code:

```<code>const { REST } = require('discord.js');
const { Routes } = require('discord-api-types/v9');
const fs = require('fs');
const pingCommand = require(`./src/commands/tools/ping.js`);
const restartCommand = require('../../commands/tools/restart.js');

module.exports = (client) => {
    client.handleCommands = async () => {
        const commandFolders = fs.readdirSync('./src/commands');
        for (const folder of commandFolders) {
            const commandFiles = fs
                .readdirSync(`./src/commands/${folder}`)
                .filter((file) => file.endsWith(".js"));

            const { commands, commandArray } = client;

            for (const file of commandFiles) {
                const command = require(`../../commands/${folder}/${file}`);
                if (command.data.name !== 'restart') {
                    commands.set(command.data.name, command);
                    commandArray.push(command.data.toJSON());
                  } else {
                    commands.set(restartCommand.data.name, restartCommand);
                    commandArray.push(restartCommand.data.toJSON());
                  }
            }
        }

        const clientId = '(BotsClientIdWentHere)';
        const guildId = '(ServersClientIdWentHere';
        const rest = new REST({ version: '9' }).setToken(process.env.token);
        try {
            console.log('Started refreshing application (/) commands.');

            await rest.put(
                Routes.applicationGuildCommands(clientId, guildId), {
                body: client.commandArray,
            });

            console.log('Successfully reloaded application (/) commands.')

        } catch (error) {
            console.error(error);
        }
    };
};

</code>```

Here is code from restart.js:

```<code>const { SlashCommandBuilder } = require('discord.js');

module.exports = {
  data: new SlashCommandBuilder()
    .setName('restart')
    .setDescription('Restarts the bot (Debug)'),
  async execute(interaction, client) {
    // Shut down the bot
    await client.destroy();

    // Log the bot back in to Discord
    await client.login(MyBotsTokenWentHere);

    // Send a message to confirm that the bot has been restarted
    await interaction.editReply({
      content: 'Bot restarted successfully'
    });
  }
}
</code>```

A file called "interactionCreate":

```<code>module.exports = {
    name: "interactionCreate",
    async execute(interaction, client) {
      console.log("Received interaction event:", interaction);

      if (interaction.isChatInputCommand()) {
        console.log("Received chat input command:", interaction.commandName);

        const { commands } = client;
        const { commandName } = interaction;
        const command = commands.get(commandName);
        if (!command) return;

        try {
          await command.execute(interaction, client);
        } catch (error) {
          console.error(error);
          await interaction.reply({
            content: `Something went wrong.. Please try again later. If this issue persists, please message my creator.`,
            ephermeral: true,
          });
        }
      }
    },
  };
</code>```

And bot.js:

```<code>require("dotenv").config();
const { token } = process.env;
const { Client, Collection, GatewayIntentBits } = require("discord.js");
const fs = require("fs");

const client = new Client({ intents: GatewayIntentBits.Guilds });
client.commands = new Collection();
client.commandArray = [];

const functionFolders = fs.readdirSync(`./src/functions`);
for (const folder of functionFolders) {
    const functionFiles = fs
    .readdirSync (`./src/functions/${folder}`)
    .filter((file) => file.endsWith('.js'));
    for (const file of functionFiles)
    require(`./functions/${folder}/${file}`)(client);
}
client.handleEvents();
client.handleCommands();
client.login(token);
</code>```

Here is also the ping file code:

```<code>const { SlashCommandBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
    .setName('ping')
    .setDescription('Returns the bots ping (Debug)'),
    async execute(interaction, client) {
        const message = await interaction.deferReply({
            fetchReply: true
        });
        const currentTime = Date.now();
        const responseTime = currentTime - interaction.createdTimestamp;
        const responseTimeSeconds = responseTime / 1000;  // convert to seconds
        const newMessage = `API Latency: ${client.ws.ping}\nClient Ping: ${message.createdTimestamp - interaction.createdTimestamp}\nTime: ${responseTimeSeconds} seconds`
        await interaction.editReply({
            content: newMessage
        });
    }
}
</code>```

And here I attacked a picture of the file heirarchy.
enter image description here

I tried to add functions that were supposed to add the function to table and add logs to the console to try to see what its printing but in the end the last error was "ReferenceError: (MyBotsTokenWentHere) is not defined". Any help appreciated.
Edit: Problem solved. Here is the updated restart.js and handleCommands files:

```<code>const { SlashCommandBuilder } = require('discord.js');

module.exports = {
  data: new SlashCommandBuilder()
    .setName('restart')
    .setDescription('Restarts the bot (Debug)'),
  async execute(interaction, client) {
    // Send a reply to the command message
    await interaction.deferReply({
      content: 'Restarting the bot...'
    });

    // Shut down the bot
    await client.destroy();

    // Log the bot back in to Discord
    await client.login(MyBotsTokenWentHere);

    // Edit the reply to confirm that the bot has been restarted
    await interaction.editReply({
      content: 'Bot restarted successfully'
    });
  }
}

</code>```

handleCommands:

```<code>const { REST } = require('discord.js');
const { Routes } = require('discord-api-types/v9');
const fs = require('fs');
const pingCommand = require(`../../commands/tools/ping.js`);
const restartCommand = require('../../commands/tools/restart.js');

module.exports = (client) => {
    client.handleCommands = async () => {
        const commandFolders = fs.readdirSync('./src/commands');
        for (const folder of commandFolders) {
            const commandFiles = fs
                .readdirSync(`./src/commands/${folder}`)
                .filter((file) => file.endsWith(".js"));

            const { commands, commandArray } = client;

            for (const file of commandFiles) {
                const command = require(`../../commands/${folder}/${file}`);
               //console.log(`loading ${command.data.name} from commands/${folder}/${file}`)
                if (command.data.name !== 'restart') {
                    commands.set(command.data.name, command);
                    commandArray.push(command.data.toJSON());
                  } else {
                    commands.set(restartCommand.data.name, restartCommand);
                    commandArray.push(restartCommand.data.toJSON());
                  }
            }
        }

        const clientId = '(ClientIdWentHere)';
        const guildId = '(GuildIdWentHere)';
        const rest = new REST({ version: '9' }).setToken(process.env.token);
        try {
            console.log('Started refreshing application (/) commands.');

            await rest.put(
                Routes.applicationGuildCommands(clientId, guildId), {
                body: client.commandArray,
            });

            console.log('Successfully reloaded application (/) commands.')

        } catch (error) {
            console.error(error);
        }
    };
};

</code>```

Body:
Im trying to create a discord bot, theres one command that returns the ping when /ping is typed, and another one im trying to add that restarts the bot when /restart is typed. But when I type /restart, it functions like I typed /ping and replied with the ping. I cannot find a solution to my problem so any help is appreciated. If you need more information on this please reply to me.
Here is a file called "handleCommands" with its code:

const { REST } = require('discord.js');
const { Routes } = require('discord-api-types/v9');
const fs = require('fs');
const pingCommand = require(`./src/commands/tools/ping.js`);
const restartCommand = require('../../commands/tools/restart.js');

module.exports = (client) => {
    client.handleCommands = async () => {
        const commandFolders = fs.readdirSync('./src/commands');
        for (const folder of commandFolders) {
            const commandFiles = fs
                .readdirSync(`./src/commands/${folder}`)
                .filter((file) => file.endsWith(".js"));

            const { commands, commandArray } = client;

            for (const file of commandFiles) {
                const command = require(`../../commands/${folder}/${file}`);
                if (command.data.name !== 'restart') {
                    commands.set(command.data.name, command);
                    commandArray.push(command.data.toJSON());
                  } else {
                    commands.set(restartCommand.data.name, restartCommand);
                    commandArray.push(restartCommand.data.toJSON());
                  }
            }
        }

        const clientId = '(BotsClientIdWentHere)';
        const guildId = '(ServersClientIdWentHere';
        const rest = new REST({ version: '9' }).setToken(process.env.token);
        try {
            console.log('Started refreshing application (/) commands.');

            await rest.put(
                Routes.applicationGuildCommands(clientId, guildId), {
                body: client.commandArray,
            });

            console.log('Successfully reloaded application (/) commands.')

        } catch (error) {
            console.error(error);
        }
    };
};

Here is code from restart.js:

const { SlashCommandBuilder } = require('discord.js');

module.exports = {
  data: new SlashCommandBuilder()
    .setName('restart')
    .setDescription('Restarts the bot (Debug)'),
  async execute(interaction, client) {
    // Shut down the bot
    await client.destroy();

    // Log the bot back in to Discord
    await client.login(MyBotsTokenWentHere);

    // Send a message to confirm that the bot has been restarted
    await interaction.editReply({
      content: 'Bot restarted successfully'
    });
  }
}

A file called "interactionCreate":

module.exports = {
    name: "interactionCreate",
    async execute(interaction, client) {
      console.log("Received interaction event:", interaction);

      if (interaction.isChatInputCommand()) {
        console.log("Received chat input command:", interaction.commandName);

        const { commands } = client;
        const { commandName } = interaction;
        const command = commands.get(commandName);
        if (!command) return;

        try {
          await command.execute(interaction, client);
        } catch (error) {
          console.error(error);
          await interaction.reply({
            content: `Something went wrong.. Please try again later. If this issue persists, please message my creator.`,
            ephermeral: true,
          });
        }
      }
    },
  };

And bot.js:

require("dotenv").config();
const { token } = process.env;
const { Client, Collection, GatewayIntentBits } = require("discord.js");
const fs = require("fs");

const client = new Client({ intents: GatewayIntentBits.Guilds });
client.commands = new Collection();
client.commandArray = [];

const functionFolders = fs.readdirSync(`./src/functions`);
for (const folder of functionFolders) {
    const functionFiles = fs
    .readdirSync (`./src/functions/${folder}`)
    .filter((file) => file.endsWith('.js'));
    for (const file of functionFiles)
    require(`./functions/${folder}/${file}`)(client);
}
client.handleEvents();
client.handleCommands();
client.login(token);

Here is also the ping file code:

const { SlashCommandBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
    .setName('ping')
    .setDescription('Returns the bots ping (Debug)'),
    async execute(interaction, client) {
        const message = await interaction.deferReply({
            fetchReply: true
        });
        const currentTime = Date.now();
        const responseTime = currentTime - interaction.createdTimestamp;
        const responseTimeSeconds = responseTime / 1000;  // convert to seconds
        const newMessage = `API Latency: ${client.ws.ping}\nClient Ping: ${message.createdTimestamp - interaction.createdTimestamp}\nTime: ${responseTimeSeconds} seconds`
        await interaction.editReply({
            content: newMessage
        });
    }
}

And here I attacked a picture of the file heirarchy.
enter image description here

I tried to add functions that were supposed to add the function to table and add logs to the console to try to see what its printing but in the end the last error was "ReferenceError: (MyBotsTokenWentHere) is not defined". Any help appreciated.
Edit: Problem solved. Here is the updated restart.js and handleCommands files:

const { SlashCommandBuilder } = require('discord.js');

module.exports = {
  data: new SlashCommandBuilder()
    .setName('restart')
    .setDescription('Restarts the bot (Debug)'),
  async execute(interaction, client) {
    // Send a reply to the command message
    await interaction.deferReply({
      content: 'Restarting the bot...'
    });

    // Shut down the bot
    await client.destroy();

    // Log the bot back in to Discord
    await client.login(MyBotsTokenWentHere);

    // Edit the reply to confirm that the bot has been restarted
    await interaction.editReply({
      content: 'Bot restarted successfully'
    });
  }
}

handleCommands:

const { REST } = require('discord.js');
const { Routes } = require('discord-api-types/v9');
const fs = require('fs');
const pingCommand = require(`../../commands/tools/ping.js`);
const restartCommand = require('../../commands/tools/restart.js');

module.exports = (client) => {
    client.handleCommands = async () => {
        const commandFolders = fs.readdirSync('./src/commands');
        for (const folder of commandFolders) {
            const commandFiles = fs
                .readdirSync(`./src/commands/${folder}`)
                .filter((file) => file.endsWith(".js"));

            const { commands, commandArray } = client;

            for (const file of commandFiles) {
                const command = require(`../../commands/${folder}/${file}`);
               //console.log(`loading ${command.data.name} from commands/${folder}/${file}`)
                if (command.data.name !== 'restart') {
                    commands.set(command.data.name, command);
                    commandArray.push(command.data.toJSON());
                  } else {
                    commands.set(restartCommand.data.name, restartCommand);
                    commandArray.push(restartCommand.data.toJSON());
                  }
            }
        }

        const clientId = '(ClientIdWentHere)';
        const guildId = '(GuildIdWentHere)';
        const rest = new REST({ version: '9' }).setToken(process.env.token);
        try {
            console.log('Started refreshing application (/) commands.');

            await rest.put(
                Routes.applicationGuildCommands(clientId, guildId), {
                body: client.commandArray,
            });

            console.log('Successfully reloaded application (/) commands.')

        } catch (error) {
            console.error(error);
        }
    };
};


问:
Using a loop to generate and redirect tar output to new directory tree, how do i match the original directory tree structure, under a new root?
I am not certain how to ask this question, but... I am attempting to alter my tar backup script so that each sub-directory recreates and is then stored in a separate directory in my backup file/folder system. For example:

```<code>/mnt/foo/old_directory_tree/{folder1..folder6} > /mnt/bar/new_directory_tree/{folder1..folder6}.tar.gz
</code>```

My loop will grab each sub-directory and print out each sub-directory in my generated log file, but I am stuck as how to use that loop function to generate and save the tar file for each sub-directory separately.

I do have an older version of a backup script that uses a separate script for each individual folder in order to accomplish this, but I am trying to use a loop instead.

```<code>SOURCE=/mnt/foo/
TAR=/mnt/bar/FooBackups/Daily/Backups/$TODAY/Daily.Backup.$TODAY.tar.gz

for p in $(find $SOURCE* -maxdepth 0 -type d); do
 echo "Backing up the following files in directory "$SOURCE "at " $(date "+%T") ":" >> $LOGS
 echo $p >> $LOGS
 echo "" >> $LOGS
 echo "" >> $LOGS
 sleep 1

 echo "" >> $LOGS
 echo "" >> $LOGS

 echo "Full Daily backup of $p started at $(date)" >> $LOGS
 tar --ignore-failed-read -I pigz -cvp -f $TAR --listed-incremental=$SNAR $p >> \
 $LOGS 2>&1 && echo "Full Daily backup of $p completed successfully at $(date)" >> \
 $LOGS || echo "Full Daily backup of $p completed with error at $(date)." >> \
 $LOGS &
 echo "" >> $LOGS
 echo "" >> $LOGS
done
</code>```

Any help is appreciated.

Body:
I am not certain how to ask this question, but... I am attempting to alter my tar backup script so that each sub-directory recreates and is then stored in a separate directory in my backup file/folder system. For example:

/mnt/foo/old_directory_tree/{folder1..folder6} > /mnt/bar/new_directory_tree/{folder1..folder6}.tar.gz

My loop will grab each sub-directory and print out each sub-directory in my generated log file, but I am stuck as how to use that loop function to generate and save the tar file for each sub-directory separately.

I do have an older version of a backup script that uses a separate script for each individual folder in order to accomplish this, but I am trying to use a loop instead.

SOURCE=/mnt/foo/
TAR=/mnt/bar/FooBackups/Daily/Backups/$TODAY/Daily.Backup.$TODAY.tar.gz

for p in $(find $SOURCE* -maxdepth 0 -type d); do
 echo "Backing up the following files in directory "$SOURCE "at " $(date "+%T") ":" >> $LOGS
 echo $p >> $LOGS
 echo "" >> $LOGS
 echo "" >> $LOGS
 sleep 1

 echo "" >> $LOGS
 echo "" >> $LOGS

 echo "Full Daily backup of $p started at $(date)" >> $LOGS
 tar --ignore-failed-read -I pigz -cvp -f $TAR --listed-incremental=$SNAR $p >> \
 $LOGS 2>&1 && echo "Full Daily backup of $p completed successfully at $(date)" >> \
 $LOGS || echo "Full Daily backup of $p completed with error at $(date)." >> \
 $LOGS &
 echo "" >> $LOGS
 echo "" >> $LOGS
done

Any help is appreciated.


问:
Field properties in xx.xxx.configuration.ElasticSearchConfiguration required a single bean, but 2 were found:
As part of spring-framework up-gradation from 1.5.6.RELEASE to 2.4.0 i am facing one issue
I am using 2 different ElasticSearch Host so i create 2 different classes one for ESConfigForMasterData and Other for ElasticSearchConfiguration while running spring boot application it throws an error

APPLICATION FAILED TO START

**Description:

Field properties in xxx.xxx.configuration.ElasticSearchConfiguration required a single bean, but 2 were found:
- integrationGlobalProperties: defined in null
- systemProperties: a programmatically registered singleton

Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed**

```<code>@Configuration
@PropertySource("classpath:application.properties")
public class ElasticSearchConfiguration {
    private static final Logger logger = LoggerFactory.getLogger(ElasticSearchConfiguration.class);

    @Autowired
    private Properties properties;

    @Value("${elasticsearch.cluster-nodes}")
    private String clusterNodes;
    @Value("${elasticsearch.cluster-name}")
    private String clusterName;

    @Value("${elasticsearch.host}")
    private String elasticHost;

    @Value("${elasticsearch.port}")
    private String elasticPort;

    @Value("${elasticsearch.protocol}")
    private String elasticProtocol;

    private Header[] headers = { new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json")};

    @Bean(name = "restClient")
    public RestClient restClient(){
        return RestClient.builder(new HttpHost(elasticHost, Integer.parseInt(elasticPort), elasticProtocol)).setDefaultHeaders(headers).build();
    }

    @Bean(name = "restHighLevelClient")
    public RestHighLevelClient restHighLevelClient(){
        logger.info(" elastic port = " + elasticPort + " host = " + elasticHost);
        return new RestHighLevelClient(RestClient.builder(new HttpHost(elasticHost, Integer.parseInt(elasticPort), elasticProtocol)));
    }
}
</code>```
```<code>@Configuration
@PropertySource("classpath:application.properties")
public class
ESConfigForMasterData {
    private static final Logger logger = LoggerFactory.getLogger(ElasticSearchConfiguration.class);

    @Autowired
    private Properties properties;

    @Value("${elasticsearch.masterdata.cluster-nodes}")
    private String clusterNodes;
    @Value("${elasticsearch.masterdata.cluster-name}")
    private String clusterName;

    @Value("${elasticsearch.masterdata.host}")
    private String elasticHost;

    @Value("${elasticsearch.masterdata.port}")
    private String elasticPort;

    @Value("${elasticsearch.masterdata.protocol}")
    private String protocol;

    private Header[] headers = { new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json")};

    @Bean(name = "restHighLevelClientMasterData")
    public RestHighLevelClient restHighLevelClientMasterData(){
        logger.info(" elastic port = " + elasticPort + " host = " + elasticHost);
        return new RestHighLevelClient(RestClient.builder(new HttpHost(elasticHost, Integer.parseInt(elasticPort), protocol)));
    }

    @Bean(name = "restClientMasterData")
    public RestClient restClientMasterData(){
        RestClientBuilder builder = RestClient.builder(new HttpHost(elasticHost, Integer.parseInt(elasticPort), protocol))
                .setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
                    @Override
                    public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) {
                        return requestConfigBuilder.setConnectTimeout(60000000)
                                .setSocketTimeout(60000000);
                    }
                });
        //TODO: As of now we are ignoring it we need to find alternative method for this setMaxRetryTimeoutMillis
        //          .setMaxRetryTimeoutMillis(60000000);
        //return RestClient.builder(new HttpHost(elasticHost, Integer.parseInt(elasticPort), protocol)).setDefaultHeaders(headers).build();
        return builder.build();
    }

}
</code>```
```<code>@Repository
public class SearchDao {
    private static final Logger logger = LoggerFactory.getLogger(SearchDao.class);

    @Autowired
    @Qualifier("restHighLevelClientMasterData")
    private RestHighLevelClient restHighLevelClientMasterData;

    @Autowired
    @Qualifier("restClientMasterData")
    private RestClient restClientMasterData;
}
</code>```

I have tryed keeping @Primary & @Qualifier annotation but it doesn't work for me
please help me in sorting this issue

Body:
As part of spring-framework up-gradation from 1.5.6.RELEASE to 2.4.0 i am facing one issue
I am using 2 different ElasticSearch Host so i create 2 different classes one for ESConfigForMasterData and Other for ElasticSearchConfiguration while running spring boot application it throws an error

APPLICATION FAILED TO START

**Description:

Field properties in xxx.xxx.configuration.ElasticSearchConfiguration required a single bean, but 2 were found:
- integrationGlobalProperties: defined in null
- systemProperties: a programmatically registered singleton

Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed**

@Configuration
@PropertySource("classpath:application.properties")
public class ElasticSearchConfiguration {
    private static final Logger logger = LoggerFactory.getLogger(ElasticSearchConfiguration.class);

    @Autowired
    private Properties properties;

    @Value("${elasticsearch.cluster-nodes}")
    private String clusterNodes;
    @Value("${elasticsearch.cluster-name}")
    private String clusterName;

    @Value("${elasticsearch.host}")
    private String elasticHost;

    @Value("${elasticsearch.port}")
    private String elasticPort;

    @Value("${elasticsearch.protocol}")
    private String elasticProtocol;

    private Header[] headers = { new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json")};

    @Bean(name = "restClient")
    public RestClient restClient(){
        return RestClient.builder(new HttpHost(elasticHost, Integer.parseInt(elasticPort), elasticProtocol)).setDefaultHeaders(headers).build();
    }

    @Bean(name = "restHighLevelClient")
    public RestHighLevelClient restHighLevelClient(){
        logger.info(" elastic port = " + elasticPort + " host = " + elasticHost);
        return new RestHighLevelClient(RestClient.builder(new HttpHost(elasticHost, Integer.parseInt(elasticPort), elasticProtocol)));
    }
}

@Configuration
@PropertySource("classpath:application.properties")
public class
ESConfigForMasterData {
    private static final Logger logger = LoggerFactory.getLogger(ElasticSearchConfiguration.class);

    @Autowired
    private Properties properties;

    @Value("${elasticsearch.masterdata.cluster-nodes}")
    private String clusterNodes;
    @Value("${elasticsearch.masterdata.cluster-name}")
    private String clusterName;

    @Value("${elasticsearch.masterdata.host}")
    private String elasticHost;

    @Value("${elasticsearch.masterdata.port}")
    private String elasticPort;

    @Value("${elasticsearch.masterdata.protocol}")
    private String protocol;

    private Header[] headers = { new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json")};

    @Bean(name = "restHighLevelClientMasterData")
    public RestHighLevelClient restHighLevelClientMasterData(){
        logger.info(" elastic port = " + elasticPort + " host = " + elasticHost);
        return new RestHighLevelClient(RestClient.builder(new HttpHost(elasticHost, Integer.parseInt(elasticPort), protocol)));
    }

    @Bean(name = "restClientMasterData")
    public RestClient restClientMasterData(){
        RestClientBuilder builder = RestClient.builder(new HttpHost(elasticHost, Integer.parseInt(elasticPort), protocol))
                .setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
                    @Override
                    public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) {
                        return requestConfigBuilder.setConnectTimeout(60000000)
                                .setSocketTimeout(60000000);
                    }
                });
        //TODO: As of now we are ignoring it we need to find alternative method for this setMaxRetryTimeoutMillis
        //          .setMaxRetryTimeoutMillis(60000000);
        //return RestClient.builder(new HttpHost(elasticHost, Integer.parseInt(elasticPort), protocol)).setDefaultHeaders(headers).build();
        return builder.build();
    }

}

@Repository
public class SearchDao {
    private static final Logger logger = LoggerFactory.getLogger(SearchDao.class);

    @Autowired
    @Qualifier("restHighLevelClientMasterData")
    private RestHighLevelClient restHighLevelClientMasterData;

    @Autowired
    @Qualifier("restClientMasterData")
    private RestClient restClientMasterData;
}

I have tryed keeping @Primary & @Qualifier annotation but it doesn't work for me
please help me in sorting this issue


问:
How can I return the design of each text I have in the PHPWORD library?
After a lot of research, I just found a way to read the doc and docs files. But I don't know how to return the design of its texts and put it in a table.

Here is the code I had used to return the content of the doc file.

```<code><?php

use PhpOffice\PhpWord\Element\AbstractContainer;
use PhpOffice\PhpWord\Element\Text;
use PhpOffice\PhpWord\IOFactory as WordIOFactory;

require_once 'vendor/autoload.php';

$source = 'test/example.doc';
$objReader = WordIOFactory::createReader('MsDoc');
$phpWord = $objReader->load($source); // instance of \PhpOffice\PhpWord\PhpWord
$text = '';

function getWordText($element) {
    $result = '';
    if ($element instanceof AbstractContainer) {
        foreach ($element->getElements() as $element) {
            $result .= getWordText($element);
        }
    } elseif ($element instanceof Text) {
        $result .= $element->getText();
    }
    // and so on for other element types (see src/PhpWord/Element)

    return $result;
}

foreach ($phpWord->getSections() as $section) {
    foreach ($section->getElements() as $element) {
        $text .= getWordText($element);
    }
}

echo $text;
</code>```

Can you help me to return the design of each text I have, one by one, and put it into an array?

I would like to return them so I can create a new doc file with my text and design.

Body:
After a lot of research, I just found a way to read the doc and docs files. But I don't know how to return the design of its texts and put it in a table.

Here is the code I had used to return the content of the doc file.

<?php

use PhpOffice\PhpWord\Element\AbstractContainer;
use PhpOffice\PhpWord\Element\Text;
use PhpOffice\PhpWord\IOFactory as WordIOFactory;

require_once 'vendor/autoload.php';

$source = 'test/example.doc';
$objReader = WordIOFactory::createReader('MsDoc');
$phpWord = $objReader->load($source); // instance of \PhpOffice\PhpWord\PhpWord
$text = '';

function getWordText($element) {
    $result = '';
    if ($element instanceof AbstractContainer) {
        foreach ($element->getElements() as $element) {
            $result .= getWordText($element);
        }
    } elseif ($element instanceof Text) {
        $result .= $element->getText();
    }
    // and so on for other element types (see src/PhpWord/Element)

    return $result;
}

foreach ($phpWord->getSections() as $section) {
    foreach ($section->getElements() as $element) {
        $text .= getWordText($element);
    }
}

echo $text;

Can you help me to return the design of each text I have, one by one, and put it into an array?

I would like to return them so I can create a new doc file with my text and design.


问:
Data not streamed from the server to the client using grpc web and nginx reverse proxy
A go GRPC server is running on an amazon Linux 2 EC2 instance. GRPC web wrapper is used, which makes the server available for a NEXTjs application. Two ports are exposed. One for regular GRPC requests and another for GRPC web requests. Nginx is configured to reverse proxy the requests, and TLS is enabled.

Regular GRPC server

```<code>server {
        listen 8000 http2;
        listen [::]:8000;

        server_name example.org;

        location / {
            grpc_pass grpc://localhost:5000;
            grpc_read_timeout 300;
            grpc_send_timeout 300;
        }
}
</code>```

GRPC web server

```<code>server {
        server_name example.org;

        location / {
            proxy_http_version 1.1;
            proxy_pass http://127.0.0.1:5001;
            proxy_read_timeout 300;
            proxy_connect_timeout 300;
            proxy_send_timeout 300;
        }
        access_log /var/log/nginx/example.org/access.log;
        error_log /var/log/nginx/example.org/error.log;

    listen [::]:443 ssl; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.org/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.org/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
</code>```

A server-side stream has been implemented. It sends an initial response soon after the connection and further responses for internal events. It works fine for regular GRPC requests but not for GRPC web.

Once the client makes a request, the status goes to pending, and once the stream closes, the client gets the response. Interim responses are not sent from the server. Requests from the client are logged in the server. They reach the server immediately. But the response it delayed. Sometimes, after 1 minute, the client gets this error - "(failed)net::ERR_INCOMPLETE_CHUNKED_ENCODING" I expect the response to be similar to regular GRPC calls.

Body:
A go GRPC server is running on an amazon Linux 2 EC2 instance. GRPC web wrapper is used, which makes the server available for a NEXTjs application. Two ports are exposed. One for regular GRPC requests and another for GRPC web requests. Nginx is configured to reverse proxy the requests, and TLS is enabled.

Regular GRPC server

server {
        listen 8000 http2;
        listen [::]:8000;

        server_name example.org;

        location / {
            grpc_pass grpc://localhost:5000;
            grpc_read_timeout 300;
            grpc_send_timeout 300;
        }
}

GRPC web server

server {
        server_name example.org;

        location / {
            proxy_http_version 1.1;
            proxy_pass http://127.0.0.1:5001;
            proxy_read_timeout 300;
            proxy_connect_timeout 300;
            proxy_send_timeout 300;
        }
        access_log /var/log/nginx/example.org/access.log;
        error_log /var/log/nginx/example.org/error.log;

    listen [::]:443 ssl; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.org/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.org/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}

A server-side stream has been implemented. It sends an initial response soon after the connection and further responses for internal events. It works fine for regular GRPC requests but not for GRPC web.

Once the client makes a request, the status goes to pending, and once the stream closes, the client gets the response. Interim responses are not sent from the server. Requests from the client are logged in the server. They reach the server immediately. But the response it delayed. Sometimes, after 1 minute, the client gets this error - "(failed)net::ERR_INCOMPLETE_CHUNKED_ENCODING" I expect the response to be similar to regular GRPC calls.


问:
ggplot2 - geom_line generating line equal to a ladder
I verified that when using geom_line the resulting graph is not formed by solid lines, the lines look like a ladder.

Would anyone know how to get solid lines?

Here is the code used.

data base
0;0
0.000700;1.050
0.001750;1.100
0.003800;1.150
0.029110;1.200
0.130900;1.240
0.341428;1.303

```<code>`library(tidyverse)
library(reprex)

SAT <- read.delim("Curva_Tipica.txt", header = FALSE, encoding = "UTF-8")
SAT <- str_split(SAT[[1]],";")
length_SAT <- length(SAT) + 1
curva_VxI <- tibble(
  .rows = length_SAT,
  I = 0,
  V = 0,
)

for (linha in 2:length_SAT) {
  curva_VxI$I[linha] <- as.double(SAT[[linha-1]][1])
  curva_VxI$V[linha] <- as.double(SAT[[linha-1]][2])
}

Xac <- (curva_VxI$V[length_SAT] - curva_VxI$V[length_SAT-1])/(curva_VxI$I[length_SAT] - curva_VxI$I[length_SAT-1])
Vj <- curva_VxI$V[length_SAT] - Xac*curva_VxI$I[length_SAT]

Xac_grafico <- tibble(
  x = c(0, 1),
  y = c(0, Xac)
)

Vj_grafico <- tibble(
  x = c(0),
  y = c(Vj)
)

theme_set(theme_bw())

ggplot() +
  geom_point(
    data = curva_VxI,
    aes(x = I, y = V),
    color = "orange",
    size = 2
  ) +
  geom_line(
    data = curva_VxI,
    aes(x = I, y = V),
    color = "orange",
    linewidth = 1
  ) +
  geom_point(
    data = Xac_grafico,
    aes(x = x, y = y),
    color = "blue",
  ) +
  geom_line(
    data = Xac_grafico,
    aes(x = x, y = y),
    color = "blue",
    linewidth = 1,
    linetype = "solid",
  ) +
  labs(
    y = "V (pu)",
    x = "I (pu)"
  ) +
  coord_cartesian(
    xlim = c(0, 1),
    ylim = c(0, 1.5),
    expand = FALSE,
    clip = "off"
  ) +
  scale_y_continuous(sec.axis = sec_axis(~.*1, "Xac (pu)")) +
  theme(
    axis.title.x = element_text(margin = margin(t = 10), size = 12, face = "bold"),
    axis.title.y = element_text(margin = margin(r = 10), size = 12, face = "bold"),
    axis.text.x = element_text(size = 10),
    axis.text.y = element_text(size = 10),
    legend.position = "top",
    # plot.background = element_rect(fill = "gray60"),
    plot.margin = margin(t = 1, r = 1, b = 0.5, l = 0.5, unit = "cm"),

  )`
</code>```

code output

expected result
result obtained

Body:
I verified that when using geom_line the resulting graph is not formed by solid lines, the lines look like a ladder.

Would anyone know how to get solid lines?

Here is the code used.

data base
0;0
0.000700;1.050
0.001750;1.100
0.003800;1.150
0.029110;1.200
0.130900;1.240
0.341428;1.303

`library(tidyverse)
library(reprex)

SAT <- read.delim("Curva_Tipica.txt", header = FALSE, encoding = "UTF-8")
SAT <- str_split(SAT[[1]],";")
length_SAT <- length(SAT) + 1
curva_VxI <- tibble(
  .rows = length_SAT,
  I = 0,
  V = 0,
)

for (linha in 2:length_SAT) {
  curva_VxI$I[linha] <- as.double(SAT[[linha-1]][1])
  curva_VxI$V[linha] <- as.double(SAT[[linha-1]][2])
}

Xac <- (curva_VxI$V[length_SAT] - curva_VxI$V[length_SAT-1])/(curva_VxI$I[length_SAT] - curva_VxI$I[length_SAT-1])
Vj <- curva_VxI$V[length_SAT] - Xac*curva_VxI$I[length_SAT]

Xac_grafico <- tibble(
  x = c(0, 1),
  y = c(0, Xac)
)

Vj_grafico <- tibble(
  x = c(0),
  y = c(Vj)
)

theme_set(theme_bw())

ggplot() +
  geom_point(
    data = curva_VxI,
    aes(x = I, y = V),
    color = "orange",
    size = 2
  ) +
  geom_line(
    data = curva_VxI,
    aes(x = I, y = V),
    color = "orange",
    linewidth = 1
  ) +
  geom_point(
    data = Xac_grafico,
    aes(x = x, y = y),
    color = "blue",
  ) +
  geom_line(
    data = Xac_grafico,
    aes(x = x, y = y),
    color = "blue",
    linewidth = 1,
    linetype = "solid",
  ) +
  labs(
    y = "V (pu)",
    x = "I (pu)"
  ) +
  coord_cartesian(
    xlim = c(0, 1),
    ylim = c(0, 1.5),
    expand = FALSE,
    clip = "off"
  ) +
  scale_y_continuous(sec.axis = sec_axis(~.*1, "Xac (pu)")) +
  theme(
    axis.title.x = element_text(margin = margin(t = 10), size = 12, face = "bold"),
    axis.title.y = element_text(margin = margin(r = 10), size = 12, face = "bold"),
    axis.text.x = element_text(size = 10),
    axis.text.y = element_text(size = 10),
    legend.position = "top",
    # plot.background = element_rect(fill = "gray60"),
    plot.margin = margin(t = 1, r = 1, b = 0.5, l = 0.5, unit = "cm"),

  )`

code output

expected result
result obtained


问:
com.crealytics:spark-excel is taking too long running when it is inside a loop
com.crealytics:spark-excel is taking too long running when it is inside a loop and drops an error at the end of the process although it works fine when I tried to upload one file only. I am using Databricks, pyspark and com.crealytics:spark-excel_2.12:0.13.5

```<code>json_response = access_ids.download_file(site_id, file_id, target_file)
bytes_file_obj = io.BytesIO()
bytes_file_obj.write(json_response)
bytes_file_obj.seek(0) #set file object to start
df = pd.read_excel(bytes_file_obj, header=None) #change in validation
sdf = spark.createDataFrame(df.astype(str))
sdf.write.format('com.crealytics.spark.excel').option("header","true").save(uri,mode="overwrite")
</code>```

It worked successfully to read the json for one file and upload it to the path, but when I tried the exact code but in a loop to read and upload the files, but the cluster on databricks stopped when it started uploading the file and after a while got this error
error

Body:
com.crealytics:spark-excel is taking too long running when it is inside a loop and drops an error at the end of the process although it works fine when I tried to upload one file only. I am using Databricks, pyspark and com.crealytics:spark-excel_2.12:0.13.5

json_response = access_ids.download_file(site_id, file_id, target_file)
bytes_file_obj = io.BytesIO()
bytes_file_obj.write(json_response)
bytes_file_obj.seek(0) #set file object to start
df = pd.read_excel(bytes_file_obj, header=None) #change in validation
sdf = spark.createDataFrame(df.astype(str))
sdf.write.format('com.crealytics.spark.excel').option("header","true").save(uri,mode="overwrite")

It worked successfully to read the json for one file and upload it to the path, but when I tried the exact code but in a loop to read and upload the files, but the cluster on databricks stopped when it started uploading the file and after a while got this error
error


问:
UITextField setText: crashes occasionally
I don't know why it crash only sometimes in some users' phone, but in my phone I never met this...
Here is someone else catch the log in his phone and send to me...

I have try to test many time, but I cannot reappear the error in my phone.Hope someone know what is happen...


问:
Why isn't the new menu page being added?
I added this class to my plugin directory, but when I refresh my dashboard, the admin page doesn't show up and I do not get any errors. Am I doing something wrong in the __construct() method?

```<code>class AA_Admin_Page {

    /**
     * Title of the page.
     */
    public $page_title;

    /**
     * Text to be used for the menu.
     */
    public $menu_title;

    /**
     * Unique slug for the menu page.
     */
    public $slug;

    function __construct() {
        $this->$page_title  = __( 'AA Plugin Page', 'AA-plugin' );
        $this->$menu_title  = __( 'AA Plugin Page', 'AA-plugin' );
        $this->slug         = 'aa_admin_page';

        $this->render_page();
    }

    public function render_page() {
        add_action( 'admin_init', [ $this, 'aa_admin_page' ] );
    }

    public function aa_admin_page() {
        add_menu_page(
            $this->$page_title,
            $this->$menu_title,
            'manage_options',
            $this->$slug,
            [ $this, 'admin_page_callback' ],
        );
    }

    public function admin_page_callback() {
        echo "This page works!";
    }
}
new AA_Admin_Page();
</code>```

Body:
I added this class to my plugin directory, but when I refresh my dashboard, the admin page doesn't show up and I do not get any errors. Am I doing something wrong in the __construct() method?

class AA_Admin_Page {

    /**
     * Title of the page.
     */
    public $page_title;

    /**
     * Text to be used for the menu.
     */
    public $menu_title;

    /**
     * Unique slug for the menu page.
     */
    public $slug;

    function __construct() {
        $this->$page_title  = __( 'AA Plugin Page', 'AA-plugin' );
        $this->$menu_title  = __( 'AA Plugin Page', 'AA-plugin' );
        $this->slug         = 'aa_admin_page';

        $this->render_page();
    }

    public function render_page() {
        add_action( 'admin_init', [ $this, 'aa_admin_page' ] );
    }

    public function aa_admin_page() {
        add_menu_page(
            $this->$page_title,
            $this->$menu_title,
            'manage_options',
            $this->$slug,
            [ $this, 'admin_page_callback' ],
        );
    }

    public function admin_page_callback() {
        echo "This page works!";
    }
}
new AA_Admin_Page();


问:
Datagrid scrollbar buttons
I am practicing with c# WPF DataGrid, when I have many rows, the vertical scrollbar is activated. How to know that I am moving the scrollbar button from top to bottom with the left mouse button?

I'm new with WPF, I don't know how to do.

Title: Datagrid scrollbar buttons


问:
AttributeError: 'function' object has no attribute 'iterrows'
```<code>    import pandas as pd
    from pandas import DataFrame
    import nltk
    import numpy as np
    from sklearn.metrics import accuracy_score
**this is the library**

df = pd.read_csv('spam.csv', encoding='ISO-8859-1')

**the dataframe**

    def get_feature(text):
        if len(text)==2:
            return {'ham':text[-3]}
        elif len(text)>=1:
            return {'spam':text[-3]}
        else:
            return {'ham':'', 'spam':''}

**get future**

    def get_feature_text(text):
        if len(text)==2:
            return {'spam':text[-2], 'ham':text[-1]}

        else:
            return {'spam':DataFrame.rename(text[-2])[0], 'ham':DataFrame.rename(text[-1])[0]}

**get future of text**

    def get_data(df, get_feature=get_feature):
        featrues = []
        for i, row in df.iterrows():
            text = row['v1']; type = row['v2']
            if isinstance(text, str):
                if ' ' in text:
                    text = text.replace(' ', '')
                if '(' not in text:
                    featrues.append((get_feature(text), type.strip('() ')))
                else:
                    text = text.partition('(')[0]
                    featrues.append((get_feature(text), type.strip('() ')))
        return featrues

**get data all**

    def get_train_test(featrues, ratio=0.9):
        N = len(featrues)
        T = int(N * ratio)
        train = featrues[:T]
        test = featrues[T:]
        return train, test

**train and test**

    def text_classifier(df, f=get_feature):
        data = get_data(df, f)
        train, test = get_train_test(data)
        classifier = nltk.NaiveBayesClassifier.train(train)
        acc = nltk.classify.accuracy(classifier, test)
        return classifier, acc

**text classifier**

 def show_type_of_text(text, texts=False, show_acc=False):
        f = get_feature_text if texts else get_feature
        classifier, acc = text_classifier(df, f)
        if show_acc:
            print("The accuracy of prediction is: ", acc)
        clf = classifier.classify(f(text))
        print(f'{text}: {clf}')
        classifier.show_most_informative_features(10)

**show type of text**

    def give_type(type1='spam', type2='ham'):
        data = get_data(df, get_feature)
        classifier = nltk.NaiveBayesClassifier.train(data)
        following = classifier.prob_classify({'ham':type2, 'spam':type1})
        x = following.generate()
        print(f'{type2}: {type1}{x}')

**give type**

    if __name__ == '__main__':
        print('-wait a minute-')
        show_type_of_text("spam")
        print((text_classifier(accuracy_score)))

**i expecting to print the score
</code>```

from this script I want to score the accuracy of the code that I made but here the problem is itterows then what should I do? I've read the documentation about accuracy_score but still the same result doesn't want to come out**

**
from this script I want to score the accuracy of the code that I made but here the problem is itterows then what should I do? I've read the documentation about accuracy_score but still the same result doesn't want to come out**

Body:
    import pandas as pd
    from pandas import DataFrame
    import nltk
    import numpy as np
    from sklearn.metrics import accuracy_score
**this is the library**

df = pd.read_csv('spam.csv', encoding='ISO-8859-1')

**the dataframe**

    def get_feature(text):
        if len(text)==2:
            return {'ham':text[-3]}
        elif len(text)>=1:
            return {'spam':text[-3]}
        else:
            return {'ham':'', 'spam':''}

**get future**

    def get_feature_text(text):
        if len(text)==2:
            return {'spam':text[-2], 'ham':text[-1]}

        else:
            return {'spam':DataFrame.rename(text[-2])[0], 'ham':DataFrame.rename(text[-1])[0]}

**get future of text**

    def get_data(df, get_feature=get_feature):
        featrues = []
        for i, row in df.iterrows():
            text = row['v1']; type = row['v2']
            if isinstance(text, str):
                if ' ' in text:
                    text = text.replace(' ', '')
                if '(' not in text:
                    featrues.append((get_feature(text), type.strip('() ')))
                else:
                    text = text.partition('(')[0]
                    featrues.append((get_feature(text), type.strip('() ')))
        return featrues

**get data all**

    def get_train_test(featrues, ratio=0.9):
        N = len(featrues)
        T = int(N * ratio)
        train = featrues[:T]
        test = featrues[T:]
        return train, test

**train and test**

    def text_classifier(df, f=get_feature):
        data = get_data(df, f)
        train, test = get_train_test(data)
        classifier = nltk.NaiveBayesClassifier.train(train)
        acc = nltk.classify.accuracy(classifier, test)
        return classifier, acc

**text classifier**

 def show_type_of_text(text, texts=False, show_acc=False):
        f = get_feature_text if texts else get_feature
        classifier, acc = text_classifier(df, f)
        if show_acc:
            print("The accuracy of prediction is: ", acc)
        clf = classifier.classify(f(text))
        print(f'{text}: {clf}')
        classifier.show_most_informative_features(10)

**show type of text**

    def give_type(type1='spam', type2='ham'):
        data = get_data(df, get_feature)
        classifier = nltk.NaiveBayesClassifier.train(data)
        following = classifier.prob_classify({'ham':type2, 'spam':type1})
        x = following.generate()
        print(f'{type2}: {type1}{x}')

**give type**

    if __name__ == '__main__':
        print('-wait a minute-')
        show_type_of_text("spam")
        print((text_classifier(accuracy_score)))

**i expecting to print the score

from this script I want to score the accuracy of the code that I made but here the problem is itterows then what should I do? I've read the documentation about accuracy_score but still the same result doesn't want to come out**

**
from this script I want to score the accuracy of the code that I made but here the problem is itterows then what should I do? I've read the documentation about accuracy_score but still the same result doesn't want to come out**


问:
Trying to randomize location values for same animation
I would like to have a css animation for an image but when the animation completes the animation restarts but with a different random starting and finishing position.</p>
```<code><div id="aniBox"></div>
<span id="aniBall"></span>

#aniBox {
    position: absolute;
    right:5px;
    bottom: -9%;
    width:100%;
    height:100%;
}
#aniBall {
    content: url(../../../public/imgs/animations/biden133.png);
    position: absolute;
    width: 40px;
    height: auto;
    transform: translate(-50%, -50%);
    animation: float 20s infinite ease-in-out, spin 5s infinite linear;
}

@keyframes float {
    0% {
        bottom: -9%;
        right: 0;
    }
    100% {
        bottom:108%;
        right: 33%;
    }
}
</code>```

Body:
I would like to have a css animation for an image but when the animation completes the animation restarts but with a different random starting and finishing position.

#aniBox {
    position: absolute;
    right:5px;
    bottom: -9%;
    width:100%;
    height:100%;
}
#aniBall {
    content: url(../../../public/imgs/animations/biden133.png);
    position: absolute;
    width: 40px;
    height: auto;
    transform: translate(-50%, -50%);
    animation: float 20s infinite ease-in-out, spin 5s infinite linear;
}

@keyframes float {
    0% {
        bottom: -9%;
        right: 0;
    }
    100% {
        bottom:108%;
        right: 33%;
    }
}


问:
error executing ImageMagick command 'convert' - xcode
I'm trying to add dev tape and version number in my app following this tutorial, but I'm getting error

"Command PhaseScriptExecution failed with a nonzero exit code"

This error occurs when I execute the command convert betaRibbon.png -resize 120x120 resizedBetaRibbon.png in the Build Phases/Icon Change Script, however when executing the same command through the terminal I do not get any error, understanding that I have the imagemagick and ghostscript are installed correctly. Also I can't execute script files from xcode either. Any ideas?.

I share script code

```<code>PATH=${PATH}:/usr/local/bin
IFS=$'\n'

function generateIcon () {
  BASE_IMAGE_NAME=$1

  TARGET_PATH="${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/${BASE_IMAGE_NAME}"
  BASE_IMAGE_PATH=$(find ${SRCROOT} -name ${BASE_IMAGE_NAME})

  WIDTH=$(identify -format %w ${BASE_IMAGE_PATH})

  /opt/homebrew/bin/convert betaRibbon.png -resize $WIDTHx$WIDTH resizedRibbon.png
  /opt/homebrew/bin/convert ${BASE_IMAGE_PATH} -fill white -font Times-Bold -pointsize 18 -gravity south -annotate 0 "Hello World" - | /opt/homebrew/bin/composite resizedRibbon.png - ${TARGET_PATH}
}

generateIcon "60.png"
generateIcon "120.png"
</code>```

Body:
I'm trying to add dev tape and version number in my app following this tutorial, but I'm getting error

"Command PhaseScriptExecution failed with a nonzero exit code"

This error occurs when I execute the command convert betaRibbon.png -resize 120x120 resizedBetaRibbon.png in the Build Phases/Icon Change Script, however when executing the same command through the terminal I do not get any error, understanding that I have the imagemagick and ghostscript are installed correctly. Also I can't execute script files from xcode either. Any ideas?.

I share script code

PATH=${PATH}:/usr/local/bin
IFS=$'\n'

function generateIcon () {
  BASE_IMAGE_NAME=$1

  TARGET_PATH="${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/${BASE_IMAGE_NAME}"
  BASE_IMAGE_PATH=$(find ${SRCROOT} -name ${BASE_IMAGE_NAME})

  WIDTH=$(identify -format %w ${BASE_IMAGE_PATH})

  /opt/homebrew/bin/convert betaRibbon.png -resize $WIDTHx$WIDTH resizedRibbon.png
  /opt/homebrew/bin/convert ${BASE_IMAGE_PATH} -fill white -font Times-Bold -pointsize 18 -gravity south -annotate 0 "Hello World" - | /opt/homebrew/bin/composite resizedRibbon.png - ${TARGET_PATH}
}

generateIcon "60.png"
generateIcon "120.png"


问:
VS Code is slow and freezing and then not responding
I have a problem with VS Code: whenever I code, debug, or run the code on my physical device using Flutter, it gets very slow, freezes, and shows "Windows is not responding: Reopen!"
I disabled all the extensions, but nothing worked.
I even tried some commands like deleting the user directory and disabling the extensions, but I still faced the same issue .
I deleted the cache in AppData/Roaming/code, but still no luck.
I also deleted the code file, and the same issue still exists!
I even did this:
-Open the Command Palette (Ctrl+Shift+P).
Run the Preferences: Configure Runtime Arguments command.
-Add "disable-hardware-acceleration": true.
-Restart VS Code.
I have looked it up all over the internet, and nothing worked!
Please help me!
these are the extntion:


问:
How to deal with overlapping token matching on syntax highlighting extension?
In vscode extensions for syntax highlighting, the json syntax config has 2 sections: the "patterns" and the "repository".

{
    "patterns": [...],
    "repository": {...}
}
```
<p>The 'patterns' array contains the regexes that vscode will try to match for the current line, to turn chunks of code into tokens. The matches are tried in the order they are present in the array. If an entry matches, then rest are not tried.</p>
<p>The way that matches are performed seem to cause a dilemma. Say that I have a language that has the following syntax:</p>
```fn [public] MyFunction() {}

class [private, abstract] MyClass {}
```

Lets say that I want to match 3 different token types:

Match context sensitive keywords, located between the backets following the introducer keywords 'fn' and 'class'. In this case: 'public', 'private', and 'abstract'.

Match the introducer keywords 'fn' and 'class'.

Match the '[' and ']' as "decoration grouping brackets".

The problem I see is that, because vscode finds a match from the 'patterns' section and then doesn't try to match other entries, whatever is defined first gets precedence, before the internal-matching-cursor is moved to the next token to highlight. In other words:

A. If token type #1 is matched first, then #2 and #3 can't match because the cursor will be like this after match #1: fn [public]^ MyFunction() {}

B. If token type #2 is matched first, then #1 can't match because the cursor will be like this after match #2: fn^ [public] MyFunction() {}

C. If token type #3 is matched first, then #1 and #2 can't match because the cursor will be like this after match #3: fn [public]^ MyFunction() {}

So, how does one deal with performing those types of matches, where the tokens being matched have overlap? Is it by having the regexes do backtracking, like (?<=fn|class)\s*\[ ? Or is there another builtin way?

Body:
In vscode extensions for syntax highlighting, the json syntax config has 2 sections: the "patterns" and the "repository".

{
    "patterns": [...],
    "repository": {...}
}

The 'patterns' array contains the regexes that vscode will try to match for the current line, to turn chunks of code into tokens. The matches are tried in the order they are present in the array. If an entry matches, then rest are not tried.

The way that matches are performed seem to cause a dilemma. Say that I have a language that has the following syntax:

fn [public] MyFunction() {}

class [private, abstract] MyClass {}

Lets say that I want to match 3 different token types:

Match context sensitive keywords, located between the backets following the introducer keywords 'fn' and 'class'. In this case: 'public', 'private', and 'abstract'.

Match the introducer keywords 'fn' and 'class'.

Match the '[' and ']' as "decoration grouping brackets".

The problem I see is that, because vscode finds a match from the 'patterns' section and then doesn't try to match other entries, whatever is defined first gets precedence, before the internal-matching-cursor is moved to the next token to highlight. In other words:

A. If token type #1 is matched first, then #2 and #3 can't match because the cursor will be like this after match #1: fn [public]^ MyFunction() {}

B. If token type #2 is matched first, then #1 can't match because the cursor will be like this after match #2: fn^ [public] MyFunction() {}

C. If token type #3 is matched first, then #1 and #2 can't match because the cursor will be like this after match #3: fn [public]^ MyFunction() {}

So, how does one deal with performing those types of matches, where the tokens being matched have overlap? Is it by having the regexes do backtracking, like (?<=fn|class)\s*\[ ? Or is there another builtin way?


问:
Microsoft Graph API Sharepoint Excel delay when using the usedRange endpoint
When using the Microsoft Graph API to query the contents of a worksheet via the usedRange endpoint:
https://learn.microsoft.com/en-us/graph/api/worksheet-usedrange?view=graph-rest-1.0&tabs=http

When I edit a cell on the spreadsheet via the browser app and then call that endpoint, the contents of that cell isn't present until after a small delay, usually around 5s. In the worksheet itself the header says that it has been saved, however that isn't immediately present when called via the endpoint.

Is there a method to guarantee that when calling the Graph API endpoint that I'm getting the absolute latest contents, or is there a way to force a save via GraphAPI endpoints before querying for the contents of a worksheet?

I tried refreshSession but that had the same issue, I expect that as soon as it says content saved on the excel sharepoint browser app, the results will be the same as the content returned by usedRange


问:
How can I change the size of a pdf in apps script?
Im using this script that creates a pdf of an specific sheet

```<code>     var sheetName = "xxxx"
  var sS = SpreadsheetApp.openById("xxxx");
  var sheets = sS.getSheets();
  //var ssNewName = sS.getRange("d2").getValue();
  var name = sheet.getRange("r3").getValue();

  for (var i = 0; i < sheets.length; i++) {
    if (sheets[i].getSheetName() !== sheetName) {
      sheets[i].hideSheet()
    }
  }
  var newFile = DriveApp.createFile(sS.getBlob());
  for (var i = 0; i < sheets.length; i++) {
    sheets[i].showSheet()
  }
 newFile.setName(name);
</code>```

It works, but there are cases when i need a different size, and its only saved in letter size, you know a way to change the size or to fith with the document?
All your answers are appreciated!

Body:
Im using this script that creates a pdf of an specific sheet

     var sheetName = "xxxx"
  var sS = SpreadsheetApp.openById("xxxx");
  var sheets = sS.getSheets();
  //var ssNewName = sS.getRange("d2").getValue();
  var name = sheet.getRange("r3").getValue();

  for (var i = 0; i < sheets.length; i++) {
    if (sheets[i].getSheetName() !== sheetName) {
      sheets[i].hideSheet()
    }
  }
  var newFile = DriveApp.createFile(sS.getBlob());
  for (var i = 0; i < sheets.length; i++) {
    sheets[i].showSheet()
  }
 newFile.setName(name);

It works, but there are cases when i need a different size, and its only saved in letter size, you know a way to change the size or to fith with the document?
All your answers are appreciated!