问:
How to add accessibility ID to Swipe action configuration in table view row for Automation purpose
I am trying to add accessibility ID to 2 buttons(Delete, Add) which is present in table view row when swipe left. The accessibilityIdentifier is not auto populating for deleteAction when I try to add it. Can somebody take a look.Thank you in advance</p>
```<code> func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {

var contextualAction: [UIContextualAction] = []

// 1st button
    let deleteAction = UIContextualAction(style: .normal , title: "DELETE") {
(action, view, handler) in
// code to remove item
    }
contextualAction.append(deleteAction)

// 2nd button
    let addAction = UIContextualAction(style: .normal , title: "Add") { (action,
view, handler) in
// code to add item
}
    contextualAction.append(addAction)
    let swipeAction = UISwipeActionsConfiguration(actions: contextualAction)
    swipeAction.performsFirstActionWithFullSwipe = false

    return swipeAction
}
</code>```

答:
Here you are</p>
```<code>func tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath) {
        tableView.subviews.forEach { tableSubview in
            if NSStringFromClass(type(of: tableSubview)) == "_UITableViewCellSwipeContainerView" {
                tableSubview.subviews.forEach { swipeContainerSubview in
                    if NSStringFromClass(type(of: swipeContainerSubview)) == "UISwipeActionPullView" {
                        swipeContainerSubview.subviews.enumerated().forEach { index, view in
                            // index 0 => your Delete Button
                            // index 1 => your Add Button
                            if let button = view as? UIButton {
                                button.accessibilityIdentifier = ""
                                button.titleLabel?.accessibilityIdentifier = ""
                            }
                        }
                    }
                }
            }
        }
    }
</code>```

Body:
I am trying to add accessibility ID to 2 buttons(Delete, Add) which is present in table view row when swipe left. The accessibilityIdentifier is not auto populating for deleteAction when I try to add it. Can somebody take a look.Thank you in advance

 func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {

var contextualAction: [UIContextualAction] = []

// 1st button
    let deleteAction = UIContextualAction(style: .normal , title: "DELETE") {
(action, view, handler) in
// code to remove item
    }
contextualAction.append(deleteAction)

// 2nd button
    let addAction = UIContextualAction(style: .normal , title: "Add") { (action,
view, handler) in
// code to add item
}
    contextualAction.append(addAction)
    let swipeAction = UISwipeActionsConfiguration(actions: contextualAction)
    swipeAction.performsFirstActionWithFullSwipe = false

    return swipeAction
}

Body:
Here you are

func tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath) {
        tableView.subviews.forEach { tableSubview in
            if NSStringFromClass(type(of: tableSubview)) == "_UITableViewCellSwipeContainerView" {
                tableSubview.subviews.forEach { swipeContainerSubview in
                    if NSStringFromClass(type(of: swipeContainerSubview)) == "UISwipeActionPullView" {
                        swipeContainerSubview.subviews.enumerated().forEach { index, view in
                            // index 0 => your Delete Button
                            // index 1 => your Add Button
                            if let button = view as? UIButton {
                                button.accessibilityIdentifier = ""
                                button.titleLabel?.accessibilityIdentifier = ""
                            }
                        }
                    }
                }
            }
        }
    }


来源: stackexchange

问:
channel_layer.send not calling handler
I have this signal to dispatch an event when a new message is created

from django.db.models.signals import post_save
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
from django.dispatch import receiver

from .serializers import MessageSerializer
from base.models import Message

@receiver(post_save, sender=Message)
def new_message(sender, instance, created, **kwargs):
    channel_layer = get_channel_layer()

    if created:
        chat_group = instance.channel.chat_group
        for member in chat_group.members:
            async_to_sync(channel_layer.send)(
                f"User-{member.user.id}",
                {
                    "type": "chat_message_create",
                    "payload": MessageSerializer(instance).data,
                },
            )
```
<p>this is the <code>consumers.py</code></p>
<pre class="lang-py prettyprint-override"><code>import json
from channels.generic.websocket import WebsocketConsumer

from api.serializers import UserSerializer

class ChatConsumer(WebsocketConsumer):
    def connect(self):
        user = self.scope["user"]
        self.channel_name = f"User-{user.id}"
        self.send(text_data=json.dumps(UserSerializer(user).data))

    def disconnect(self, close_code):
        pass

    def chat_message_create(self, event):
        print("Created")
        self.send(text_data=json.dumps(event["payload"]))
</code>```

When I create a new message in the admin panel the signal gets called but it does not get dispatched through the websocket, and any debug prints in ChatConsumer.chat_message_create won't even get printed.

答: Fixed the issue, I reworked the Consumers to use Groups instead of single channels</p>

ContentLicense: CC BY-SA 4.0

Title: channel_layer.send not calling handler

Body:
I have this signal to dispatch an event when a new message is created

from django.db.models.signals import post_save
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
from django.dispatch import receiver

from .serializers import MessageSerializer
from base.models import Message

@receiver(post_save, sender=Message)
def new_message(sender, instance, created, **kwargs):
    channel_layer = get_channel_layer()

    if created:
        chat_group = instance.channel.chat_group
        for member in chat_group.members:
            async_to_sync(channel_layer.send)(
                f"User-{member.user.id}",
                {
                    "type": "chat_message_create",
                    "payload": MessageSerializer(instance).data,
                },
            )

this is the consumers.py

import json
from channels.generic.websocket import WebsocketConsumer

from api.serializers import UserSerializer

class ChatConsumer(WebsocketConsumer):
    def connect(self):
        user = self.scope["user"]
        self.channel_name = f"User-{user.id}"
        self.send(text_data=json.dumps(UserSerializer(user).data))

    def disconnect(self, close_code):
        pass

    def chat_message_create(self, event):
        print("Created")
        self.send(text_data=json.dumps(event["payload"]))

When I create a new message in the admin panel the signal gets called but it does not get dispatched through the websocket, and any debug prints in ChatConsumer.chat_message_create won't even get printed.


问:
How to use the duplicated cookie in Jmeter
A request

Response cookie:
content-version:12345678, content-version:98654321

B request

Request Cookie:
content-version:${COOKIE_content-version}

The situation is that I am now using Jmeter to perform the stress test. There are two HTTP requests. In A request, there are two response cookies having the same name but different values. Now, I want to use the second value which is 98654321 in B request. However, if I use ${COOKIE_content-version}, it will use the first value which is 12345678. May I ask how can I take the second value?

Thank you very much.

答:
In reality if multiple cookies have the same name it's the browser who decides which one is to send back.

If you absolutely need to send the "second" cookie - don't rely on the HTTP Cookie Manager, just extract the "second" cookie from the Set-Cookie response header using Regular Expression Extractor configured like:

refer the extracted value as ${cookie} where required


问:
React Native iOS Release build stuck on old code but Debug build works fine
When I try to build my React Native App from XCode in Release mode to check before launch it to production it get stuck in old code. No matter what change I do in my JS file that it won't do it. In Debug mode it doesn't happen, just works fine like it should.

Example:

I change a label in any of my JS files like a title of some menu and it will work when I use react-native run-ios or if I press on "Play" button of XCode if in the scheme "Debug" is checked. If instead, I check "Release" it charge an old version of my app I don't even know with certainly which version is.

I have tried to launch to production but still being the old version.

So, now a day I can't upload new version due to no matter what changes I do, the release mode ignores it.

I have tried to generate a new main.jsbundle, I have cleaned build with Shift + CMD + K and I aso have reinstalled my npm with no solution.

Do you have any idea?

EDIT:

Does the file "AppDelegate.m" have anything to do with it?

This is my AppDelegate:

```<code>#import "AppDelegate.h"

#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
  RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                                   moduleName:@"BottomNavigation"
                                            initialProperties:nil];
  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];
  return YES;
}

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
  return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
#else
  return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}

@end
</code>```

答:
Before archive stop already running node
and start server and now make archive</p>
```<code>npm start -- --reset-cache
</code>```

Body:
When I try to build my React Native App from XCode in Release mode to check before launch it to production it get stuck in old code. No matter what change I do in my JS file that it won't do it. In Debug mode it doesn't happen, just works fine like it should.

Example:

I change a label in any of my JS files like a title of some menu and it will work when I use react-native run-ios or if I press on "Play" button of XCode if in the scheme "Debug" is checked. If instead, I check "Release" it charge an old version of my app I don't even know with certainly which version is.

I have tried to launch to production but still being the old version.

So, now a day I can't upload new version due to no matter what changes I do, the release mode ignores it.

I have tried to generate a new main.jsbundle, I have cleaned build with Shift + CMD + K and I aso have reinstalled my npm with no solution.

Do you have any idea?

EDIT:

Does the file "AppDelegate.m" have anything to do with it?

This is my AppDelegate:

#import "AppDelegate.h"

#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
  RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                                   moduleName:@"BottomNavigation"
                                            initialProperties:nil];
  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];
  return YES;
}

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
  return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
#else
  return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}

@end

Body:
Before archive stop already running node
and start server and now make archive

npm start -- --reset-cache


问:
Is it a good practise to loop through a list and in between the loop you append data to that list?
```<code>a = [1,2,3,4,0]
def looping_thing():
    append_flag = True
    for i in a:
        if i == 0:
            append_flag = False
        if append_flag:
            a.append(i)
        print(i)
looping_thing()
</code>```

So in this code i am trying to move the item to back of the list so that i can deal with them only after i encounter value "0" in the list. So is this way of doing is correct in python?

Edit : So seems like i was not that clear. What i am doing here is....from the list i first want to deal with value 0 and execute some block of code..then move onto other value of the list and execute the same block of code. So i am just so to execute block of code "0" has the priority. Here the assumption is that i cannot sort the list and there will always be a "0" value. I hope this make sense.

答:
In general I would avoid manipulating the list in place while you iterate over it, especially using an iterator i, where it's not explicit how that will behave stepping through elements that could shift, appear, and disappear.

Plus, if you have to program in other languages, iterating over a changing collection/list/array could behave differently. In Java, for example, java.util.ConcurrentModificationException is thrown.

Note also that in your particular case this will iterate and grow the list infinitely if there is no 0 in it.

Two alternatives:

Use external list

a = [1,2,3,4,5,0]

def looping_thing():
    append_flag = True
    changes = []

    for i in a:
        if i == 0:
            append_flag = False
        if append_flag:
            changes.append(i)
        print(i)

    # done iterating over a; apply changes
    a.extend(changes)

looping_thing()
```
<h2>Use explicit index (iterate over range)</h2>
<pre class="lang-py prettyprint-override"><code>a = [1,2,3,4,5,0]

def looping_thing():
    append_flag = True

    # i is index of original a without appended elements
    # n guaranteed not to be recalculated as a changes
    n = len(a)
    for i in range(n):
        if a[i] == 0:
            append_flag = False
        if append_flag:
            a.append(a[i])
        print(a[i])

looping_thing()
</code>```

Body:
a = [1,2,3,4,0]
def looping_thing():
    append_flag = True
    for i in a:
        if i == 0:
            append_flag = False
        if append_flag:
            a.append(i)
        print(i)
looping_thing()

So in this code i am trying to move the item to back of the list so that i can deal with them only after i encounter value "0" in the list. So is this way of doing is correct in python?

Edit : So seems like i was not that clear. What i am doing here is....from the list i first want to deal with value 0 and execute some block of code..then move onto other value of the list and execute the same block of code. So i am just so to execute block of code "0" has the priority. Here the assumption is that i cannot sort the list and there will always be a "0" value. I hope this make sense.

Body:
In general I would avoid manipulating the list in place while you iterate over it, especially using an iterator i, where it's not explicit how that will behave stepping through elements that could shift, appear, and disappear.

Plus, if you have to program in other languages, iterating over a changing collection/list/array could behave differently. In Java, for example, java.util.ConcurrentModificationException is thrown.

Note also that in your particular case this will iterate and grow the list infinitely if there is no 0 in it.

Two alternatives:

Use external list

a = [1,2,3,4,5,0]

def looping_thing():
    append_flag = True
    changes = []

    for i in a:
        if i == 0:
            append_flag = False
        if append_flag:
            changes.append(i)
        print(i)

    # done iterating over a; apply changes
    a.extend(changes)

looping_thing()

Use explicit index (iterate over range)

a = [1,2,3,4,5,0]

def looping_thing():
    append_flag = True

    # i is index of original a without appended elements
    # n guaranteed not to be recalculated as a changes
    n = len(a)
    for i in range(n):
        if a[i] == 0:
            append_flag = False
        if append_flag:
            a.append(a[i])
        print(a[i])

looping_thing()


问:
CSS Drop Shadow Breaks on Mobile | Next.js
Edit: I found out that the issue is exclusive to iPhones. I tested with an android device and it worked fine when I tried viewing the page on two different iPhones it broke on both.

This issue is mobile related, since when I shrink my browser window to the size of a mobile screen, everything looks fine. However, when I view the site on my actual mobile device, the drop shadow "breaks" at seemingly random places. If I zoom in and out these breaks will change their locations.

The current effect being used is

```<code>filter: drop-shadow(20px 10px 4px #707070);
</code>```

答:
After further research into this, I found that the issue was not specific to my website. If you go onto the Mozilla MDN Docs on a recent iPhone device, you'll notice that it gives you the exact same effect when zoomed in. I'm going to post this as an issue on Github as suggested in the docs. Here is what my mobile phone showed when viewing the Firefox Logo drop shadow effect.

As suggested in a comment, changing to a simple box-shadow fixed the issue, although the edges are more hard-lined and slightly less faded (using the same parameters). It's not enough to break this specific project and I know there are CSS features available that enhance this, so all is good!

Body:
Edit: I found out that the issue is exclusive to iPhones. I tested with an android device and it worked fine when I tried viewing the page on two different iPhones it broke on both.

This issue is mobile related, since when I shrink my browser window to the size of a mobile screen, everything looks fine. However, when I view the site on my actual mobile device, the drop shadow "breaks" at seemingly random places. If I zoom in and out these breaks will change their locations.

The current effect being used is

filter: drop-shadow(20px 10px 4px #707070);


问:
How to exclude holidays like saturday, sunday from date using Javascript?
I've found this code online to return the next working day and exclude weekends.

```<code>function nextWorkDay() {
    const date = new Date();
  do {
    date.setDate(date.getDate() + 1);
  } while (!(date.getDay() % 6));
  return date;
}
</code>```

However, the % 6 part in my understanding excludes Saturdays and Sundays.
How can I modify it to only exclude Saturdays?

答:
I would say always go to next day, and if it's Saturday jump to the next day. The sample working code is attached below.

const days = ["SUN", "MON", "TUS", "WED", "THU", "FRI", "SAT"]

function getNextWorkingDate() {
  let now =  new Date();
  let today = new Date(now.setDate(now.getDate() +  1)) // find next day
  // Sunday = 0, Monday = 1, ... (See below):
  if(today.getDay() == 7) { //  if staturday, jump one more day
    today = today.setDate(today.getDate() +  1)
  }
  return today;
}

const nextWorkigDay = getNextWorkingDate();
console.log(nextWorkigDay);
console.log(days[nextWorkigDay.getDay()]);```

Body:
I've found this code online to return the next working day and exclude weekends.

function nextWorkDay() {
    const date = new Date();
  do {
    date.setDate(date.getDate() + 1);
  } while (!(date.getDay() % 6));
  return date;
}

However, the % 6 part in my understanding excludes Saturdays and Sundays.
How can I modify it to only exclude Saturdays?


问:
S3 Objects created using UNLOAD command from the Redshift cluster are not accessible to the bucket owner user of the AWS account
I have one AWS S# and Redshift question:

A company uses two AWS accounts for accessing various AWS services. The analytics team has just configured an Amazon S3 bucket in AWS account A for writing data from the Amazon Redshift cluster provisioned in AWS account B. The team has noticed that the files created in the S3 bucket using UNLOAD command from the Redshift cluster are not accessible to the bucket owner user of the AWS account A that created the S3 bucket.

What could be the reason for this denial of permission for resources belonging to the same AWS account?

I tried to reproduce the scenario for the question, but I can't.

I don't get the S3 Object Ownership and Bucket Ownership.

答: The problem is that the bucket owner in account A does not have access to files that were uploaded by the account B, usually that is solved by specifying acl parameter when uploading files --acl bucket-owner-full-control. Since the upload is done via Redshift you need to tell Redshift to assume a role in the account A for UNLOAD command so files don't change the ownership and continue to belong to account A. Check the following page for more examples on configuring cross account LOAD/UNLOAD https://aws.amazon.com/premiumsupport/knowledge-center/redshift-s3-cross-account/


问:
Elegant Numpy ways to implement this matrix operation
I'm looking to vectorize the following equation:

Where x represents an N x T list of observations, and gamma is an N x K matrix. The intended output, theta, is a K x T matrix. Of course, I have a naive implementation that works by just looping through the elements and setting the array manually, but I just know there's a much cleaner solution lurking out here somewhere.

Below is my naive implementation, however it is much too slow for my purposes.

    theta = np.zeros((K, T))
    for k in range(K):
        numerator = np.zeros((T,))
        denominator = 0
        for i in range(N):
            gamma_ik = r[i,k]
            numerator = numerator + gamma_ik * x[i]
            denominator = denominator + gamma_ik
        theta[k] = numerator / denominator
```

答:
Slightly more explicit answer that may be easier to follow. Again, the key function call is numpy.matmul.

```<code>import numpy as np

# dimensions N, T, K
N = 2
T = 3
K = 4

x = np.cumsum(np.ones([N,T]), axis = 0)
#[[1. 1. 1.]
#[2. 2. 2.]]

gamma = np.cumsum(np.ones([K,N]), axis = 0)
#[[1. 1.]
# [2. 2.]
# [3. 3.]
# [4. 4.]]

y = np.matmul(gamma, x) # numerator
#[[ 3.  3.  3.]
# [ 6.  6.  6.]
# [ 9.  9.  9.]
# [12. 12. 12.]]

# denominator
sumgamma = np.matmul(gamma, np.ones(N))
#[2. 4. 6. 8.]

theta = y / sumgamma[:,None]
#[[1.5 1.5 1.5]
# [1.5 1.5 1.5]
# [1.5 1.5 1.5]
# [1.5 1.5 1.5]]
</code>```

Body:
Slightly more explicit answer that may be easier to follow. Again, the key function call is numpy.matmul.

import numpy as np

# dimensions N, T, K
N = 2
T = 3
K = 4

x = np.cumsum(np.ones([N,T]), axis = 0)
#[[1. 1. 1.]
#[2. 2. 2.]]

gamma = np.cumsum(np.ones([K,N]), axis = 0)
#[[1. 1.]
# [2. 2.]
# [3. 3.]
# [4. 4.]]

y = np.matmul(gamma, x) # numerator
#[[ 3.  3.  3.]
# [ 6.  6.  6.]
# [ 9.  9.  9.]
# [12. 12. 12.]]

# denominator
sumgamma = np.matmul(gamma, np.ones(N))
#[2. 4. 6. 8.]

theta = y / sumgamma[:,None]
#[[1.5 1.5 1.5]
# [1.5 1.5 1.5]
# [1.5 1.5 1.5]
# [1.5 1.5 1.5]]


问:
How to detect the object being double released with Xcode - message sent to deallocated instance?
I am relatively new to Xcode4 and I would like to know how can I identify a double release with it.

In the debugger I see a line like *** -[NSConcreteMutableData release]: message sent to deallocated instance 0x60b63fe0.

The problem is that knowing the address doesn't help a lot identifying the object and also the object type doesn't help too much identifying it.

I read http://www.friday.com/bbum/2010/01/10/using-malloc-to-debug-memory-misuse-in-cocoa/ but I did not found this to be too successful.

答:
You can enable the NSZombieEnabled environment variable - see How do I set up NSZombieEnabled in Xcode 4? for instructions on how to do this on Xcode 4.

What this means is that released objects are kept around in memory, so the debugger can still find out the type of objects. When the crash occurs, you are told of the object in question.

The "Zombies" Instruments tool is great for detecting bugs of this type - it actually enables NZZombieEnabled and you can use it to find out exactly which line of code the crash occurs.

ContentLicense: CC BY-SA 3.0


问:
Complex join between two tables
I'm trying to help on the below complex join scenario. Please guide me.

Table 1

```<code>Patient_ID  Service_code Tablet
-------------------------------
1            120         cnr
1            230         pmr
1            520         ksr
3            212         dnr
3            332         psr
4            412         vrr
4            333         zyr
</code>```

Table 2

```<code>Product_service_cd     Rank
----------------------------
120                    1
230                    2
520                    1
212                    13
332                    5
333                    2
</code>```

Desired output

```<code>patient_id  service_code  Tablet
--------------------------------
1           520           ksr
3           332           psr
4           333           zyr
</code>```

Single patient has multiple tables, so we need to choose one table for each patient based Highest rank (1 being highest) using conditions below:

If both service Id have same ran choose max(service_code)

If a patient has 2 service Id, choose the highest rank among the service IDs

If the service Id is missing in table 2 then have rank default as 100

My query:

```<code>select
    t1.patient_id, t1.service_id
from
    table1 t1
where
    t1.service_code = (select a.service_code, min(b.rank)
                       from table1 a
                       left join table2
                       group by a.service_code);
</code>```

Also trying to find how to assign default rank as 100 if service code is not found in table2. Thanks in advance.

答:
You can use ROW_NUMBER() to sort the rows for each patient, according to the ordering you decide. Then, it's a matter of picking the first one per patient

For example:

```<code>select *
from (
  select
    a.*,
    row_number() over(partition by patient_id
      order by coalesce(b.rank, 100), a.service_code desc
    ) as rn
  from table1 a
  left join table2 b on b.product_service_code = a.service_code
) x
where rn = 1
</code>```

Title: Complex join between two tables

Body:
I'm trying to help on the below complex join scenario. Please guide me.

Table 1

Patient_ID  Service_code Tablet
-------------------------------
1            120         cnr
1            230         pmr
1            520         ksr
3            212         dnr
3            332         psr
4            412         vrr
4            333         zyr

Table 2

Product_service_cd     Rank
----------------------------
120                    1
230                    2
520                    1
212                    13
332                    5
333                    2

Desired output

patient_id  service_code  Tablet
--------------------------------
1           520           ksr
3           332           psr
4           333           zyr

Single patient has multiple tables, so we need to choose one table for each patient based Highest rank (1 being highest) using conditions below:

If both service Id have same ran choose max(service_code)

If a patient has 2 service Id, choose the highest rank among the service IDs

If the service Id is missing in table 2 then have rank default as 100

My query:

select
    t1.patient_id, t1.service_id
from
    table1 t1
where
    t1.service_code = (select a.service_code, min(b.rank)
                       from table1 a
                       left join table2
                       group by a.service_code);

Also trying to find how to assign default rank as 100 if service code is not found in table2. Thanks in advance.

Body:
You can use ROW_NUMBER() to sort the rows for each patient, according to the ordering you decide. Then, it's a matter of picking the first one per patient

For example:

select *
from (
  select
    a.*,
    row_number() over(partition by patient_id
      order by coalesce(b.rank, 100), a.service_code desc
    ) as rn
  from table1 a
  left join table2 b on b.product_service_code = a.service_code
) x
where rn = 1


答:
It generally is not a good idea to append to the same list that you are iterating through without specifying an explicit range.

Unless you are absolutely certain that there will always be one "0" in your list, you will eventually run into an input that will cause an infinite loop. Take the following input for example.

[1, 2, 3]

Notice that there is no stopping condition because there are no elements equal to 0. This will cause you to keep appending 1, 2, 3 until you overflow.

One way to avoid iterating over new elements is to explicitly define your loop's range to be within the length of the original array.

```<code>for index in range(len(a)):
  print(a[index])
</code>```

Title: Is it a good practise to loop through a list and in between the loop you append data to that list?

Body:
It generally is not a good idea to append to the same list that you are iterating through without specifying an explicit range.

Unless you are absolutely certain that there will always be one "0" in your list, you will eventually run into an input that will cause an infinite loop. Take the following input for example.

[1, 2, 3]

Notice that there is no stopping condition because there are no elements equal to 0. This will cause you to keep appending 1, 2, 3 until you overflow.

One way to avoid iterating over new elements is to explicitly define your loop's range to be within the length of the original array.

for index in range(len(a)):
  print(a[index])


答:
Some pre-processing of your dataframe for previous years. First, get the year label by taking the year component of your date with 4-month subtracted. Second, drop March and April.

```<code>from datetime import date
from dateutil.relativedelta import relativedelta
df_prev['year'] = pd.Series(df_prev['date'].dt.to_pydatetime() - relativedelta(months=4)).dt.year

df_prev = df_prev[~df_prev['month'].isin([3,4])]
</code>```

Then convert df_prev into a matrix with years as column and month as index, convert the table for this year into a series with month as index.

```<code>df_prev_vari = df_prev.set_index(['month', 'year'])[['Variation']].unstack().droplevel(0, axis=1)
df_this_vari = df_this.set_index('month')['Variation']
</code>```

Having month as the common index for both data enables us to subtract one another by matching the index, followed by squared, mean, and square-root operations.

```<code>(df_prev_vari.sub(df_this_vari, axis=0)**2).mean()**.5
</code>```

Title: Pandas Calculate RMSE in Date Range Chunks by Year

Body:
I have data in a df and need to calculate the RMSE of a column consisting of rows of months and years data compared to the current month and year rows in a chunk period. I cannot figure out how to set up the sequencing by each year. For example, I need to calculate the RMSE by year from exactly month == 5 to month == 2 and print all the RMSE values in the "Variation" column by start year. My data looks like this:

                     month  mean_mon_flow  ...  std_anomaly  Variation
date                                       ...
1992-04-01 00:00:00      4      12.265100  ...    -1.074586        NaN
1992-05-01 00:00:00      5      12.533220  ...    -1.017388   0.057198
1992-06-01 00:00:00      6      12.491247  ...    -1.117406  -0.100018
1992-07-01 00:00:00      7      12.113165  ...    -1.401221  -0.283815
1992-08-01 00:00:00      8      11.846904  ...    -1.359026   0.042195
1992-09-01 00:00:00      9      11.526178  ...    -0.299250   1.059776
1992-10-01 00:00:00     10      11.555834  ...    -0.628162  -0.328911
1992-11-01 00:00:00     11      11.746104  ...    -1.116374  -0.488213
1992-12-01 00:00:00     12      11.891824  ...    -0.143343   0.973031
1993-01-01 00:00:00      1      11.997252  ...    -0.486450  -0.343107
1993-02-01 00:00:00      2      12.028855  ...    -0.862971  -0.376521
1993-03-01 00:00:00      3      12.063974  ...    -0.596869   0.266102
1993-04-01 00:00:00      4      12.265100  ...    -0.923695  -0.326826
1993-05-01 00:00:00      5      12.533220  ...     0.322987   1.246682
1993-06-01 00:00:00      6      12.491247  ...    -0.478567  -0.801554
1993-07-01 00:00:00      7      12.113165  ...    -0.274119   0.204448
1993-08-01 00:00:00      8      11.846904  ...    -0.707968  -0.433849
1993-09-01 00:00:00      9      11.526178  ...     0.167246   0.875214
1993-10-01 00:00:00     10      11.555834  ...    -0.089410  -0.256656
1993-11-01 00:00:00     11      11.746104  ...    -1.046461  -0.957050
1993-12-01 00:00:00     12      11.891824  ...    -1.293175  -0.246714
1994-01-01 00:00:00      1      11.997252  ...    -1.505133  -0.211959
1994-02-01 00:00:00      2      12.028855  ...    -0.610121   0.895012
1994-03-01 00:00:00      3      12.063974  ...    -0.974184  -0.364063
1994-04-01 00:00:00      4      12.265100  ...    -1.077609  -0.103424

The observed data from the current year looks like this:

                     month  mean_mon_flow  ...  std_anomaly  Variation
date                                       ...
2021-05-01 00:00:00      5      12.533220  ...    -0.935899   0.206586
2021-06-01 00:00:00      6      12.491247  ...    -0.647261   0.288638
2021-07-01 00:00:00      7      12.113165  ...    -0.711730  -0.064469
2021-08-01 00:00:00      8      11.846904  ...    -0.482306   0.229424
2021-09-01 00:00:00      9      11.526178  ...    -0.116989   0.365317
2021-10-01 00:00:00     10      11.555834  ...     0.319614   0.436603
2021-11-01 00:00:00     11      11.746104  ...     0.880379   0.560765
2021-12-01 00:00:00     12      11.891824  ...     0.630541  -0.249838
2022-01-01 00:00:00      1      11.997252  ...    -0.151507  -0.782048
2022-02-01 00:00:00      2      12.028855  ...    -0.237398  -0.085891

The result should be something like this below. I've tried using a groupby statement to calculate RMSE but not sure how to give groupby a range of dates.

year   RMSE Variation
1992   number
1993   number
1994   number
..     ..
2020   number

thank you,

Body:
Some pre-processing of your dataframe for previous years. First, get the year label by taking the year component of your date with 4-month subtracted. Second, drop March and April.

from datetime import date
from dateutil.relativedelta import relativedelta
df_prev['year'] = pd.Series(df_prev['date'].dt.to_pydatetime() - relativedelta(months=4)).dt.year

df_prev = df_prev[~df_prev['month'].isin([3,4])]

Then convert df_prev into a matrix with years as column and month as index, convert the table for this year into a series with month as index.

df_prev_vari = df_prev.set_index(['month', 'year'])[['Variation']].unstack().droplevel(0, axis=1)
df_this_vari = df_this.set_index('month')['Variation']

Having month as the common index for both data enables us to subtract one another by matching the index, followed by squared, mean, and square-root operations.

(df_prev_vari.sub(df_this_vari, axis=0)**2).mean()**.5


问:
How to make query system with PHP and MySQL?
I have some script on my website, when logged user can put some data into form, and then, PHP script will do an exec() function for some time, but webpage is hold still, until that PHP script and exec() command will end. If user close the page - he is resolve nothing, and he need to run script again.
I want to know, if that possible, to do query mode, with existens database with users. What i want:

User put some data and execute script. It will put record to database with id=1 status=running

User can close webpage and script still running

Between that, another user want to put some data too, but webpage checks currently executing scripts from database, and say "I'll do it later, your queue is 1", and add an record in database id=2 status=queue

First script ends executing, return values to database and set up id=1 status=done

Then if in database exist some queue records, it will execute it too.

Users can open back website, and get data from it.

What problem that i have now. PHP function exec() can somehow crash, or return different data, so i need to catch it right, when it executes in background. I don't know, how to correctly do, what i want. Some of the solution is, to create a daemon on PHP, but it can be difficult to control/manage daemon, i suppose.

What is the correct way to use, without any of libraries, from scratch? It can be some examples of this? If the daemon is the correct solution - how can i setup it and control?

答:
What you defines resemble the often used CRON/Background Process/AT(on Windows). i.e.

Create a PHP Form which save to DB as you want.

Then create a new PHP Script, that read from DB. perform action, store data in dB.

This new script is configure to run every minute/5 minute/30 minute or once per day in cron service of your server. that run PHP Script on command line.

It perform operation and you can send email and db update as required.

For Exec crashing it is hard to tell the reason, there are literally 1000s of them and each has there own scope of resolution. So please post that individual as separate question with more detail. Look for your hosting environment cron and hwo to write cron scripts.

EDIT:
Writing Cron is little high level than writing Web script, in cron script you need to consider following

It should not output anything, no echo or print, as there is noone sitting to see it.

If you need output for debugging, you can, but disable in live/production otherwise it might add up to server log and bloat your server.

You need to make script singular depending on need, there are various way of doing it, one I prefer is to drop a lock file for cron and check if file is there don't execute cron else do it, and you need to ensure that lock file gets delete always otherwise crone get stuck.

Sometime error handling is problem in lock file sceanrio, in that case If I know that my crone take say 15-30 minute, I put a check that if a lock file is older than 2 hrs it auto delete. so at most my cron is stuck for 2hrs.


问:
image suddenly not loading anymore
I am working on decentragram. This was working fine a few days ago but now image not load anymore. Giving error as bafybeieq6nyhu7ilorb7dxepo6sexab6oqigkjhzc62dxio6x5xaurge7u.ipfs.infura-ipfs.io/:1   GET https://bafybeieq6nyhu7ilorb7dxepo6sexab6oqigkjhzc62dxio6x5xaurge7u.ipfs.infura-ipfs.io/ net::ERR_NAME_NOT_RESOLVED

This is how I Displayed image in main.js

```<code> <ul id="imageList" className="list-group list-group-flush">
                  <li className="list-group-item">
                    <p className="text-center"><img src={ 'https://ipfs.infura.io/ipfs/${image.hash}' } style={{ maxWidth: '420px'}}/></p>
                    <p>{image.description}</p>
                  </li>
</code>```

and in App.js

```<code>const ipfsClient = require('ipfs-http-client')
const ipfs = ipfsClient({ host: 'ipfs.infura.io', port: 5001, protocol: 'https' }) // leaving out the arguments will default to these values
</code>```

答:
Actually, It worked after I replaced the url with this</p>
```<code><p className="text-center"><img src={`https://gateway.ipfs.io/ipfs/${image.hash}`} style={{ maxWidth: '420px'}}/></p>

</code>```

Title: image suddenly not loading anymore

Body:
I am working on decentragram. This was working fine a few days ago but now image not load anymore. Giving error as bafybeieq6nyhu7ilorb7dxepo6sexab6oqigkjhzc62dxio6x5xaurge7u.ipfs.infura-ipfs.io/:1   GET https://bafybeieq6nyhu7ilorb7dxepo6sexab6oqigkjhzc62dxio6x5xaurge7u.ipfs.infura-ipfs.io/ net::ERR_NAME_NOT_RESOLVED

This is how I Displayed image in main.js

{image.description}

and in App.js

const ipfsClient = require('ipfs-http-client')
const ipfs = ipfsClient({ host: 'ipfs.infura.io', port: 5001, protocol: 'https' }) // leaving out the arguments will default to these values

Body:
Actually, It worked after I replaced the url with this

<p className="text-center"><img src={`https://gateway.ipfs.io/ipfs/${image.hash}`} style={{ maxWidth: '420px'}}/></p>


问:
How to make a tkinter gui and display printed value
This is how far I came.... I got the winner know I want to display it on the gui here is my code:
I tried many google searches and found none I hoped that someone may help me</p>
```<code>import tkinter as tk
import random
from progress.bar import Bar
backroundcolor = '#C46C6C'
class Application(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.geometry('500x500')
        self.title('TheXoGenie')
        self.configure(bg=backroundcolor)
        title = tk.Label(self, text="Welcome to TheXoGenie", font='Helvetica 18 bold', bg=backroundcolor)
        title.pack(pady= 2, padx= 2)
        run = tk.Button(self, text ="Run", command = runn)
        run.pack(pady= 5, padx = 5)

def runn():
    PEOPLE = [
  'Juan',
  'Owen'
]

    print("\n\n")
    bar = Bar('And the winner is...', max=2)
    for i in range(2):
        [x for x in range(999999)]  # short pause...
        bar.next()
    bar.finish()
    print("\n\n\t{}!\n\n".format(random.choice(PEOPLE)))
    print("-" * 60 + "\n")

app = Application()
app.mainloop()
</code>```

答:
You can use tk.Label to replace the print() output, ttk.Progressbar to replace the console progress bar and use .after() to update the progress bar:

import tkinter as tk
from tkinter import ttk
import random

backgroundcolor = '#C46C6C'

class Application(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.geometry('500x500')
        self.title('TheXoGenie')
        self.configure(bg=backgroundcolor)

        title = tk.Label(self, text="Welcome to TheXoGenie", font='Helvetica 18 bold', bg=backgroundcolor)
        title.pack(pady=2, padx=2)

        run = tk.Button(self, text="Run", command=self.runn)
        run.pack(pady=5, padx=5)

        self.msg = tk.Label(self, text='And the winner is...', font='Helvetica 16 bold', bg=backgroundcolor)
        self.bar = ttk.Progressbar(self, orient='horizontal', length=200)
        self.winner = tk.Label(self, font='Helvetica 32 bold', bg=backgroundcolor)

    def runn(self):
        PEOPLE = ['Juan', 'Owen']

        # hide the previous winner
        self.winner.pack_forget()

        # show the message and progress bar
        self.msg.pack(pady=10)
        self.bar.pack()

        def show_winner(n=0):
            # update progress bar
            self.bar['value'] = n
            if n > 100:
                # hide the progress bar
                self.bar.pack_forget()
                # show the winner
                self.winner.config(text=random.choice(PEOPLE))
                self.winner.pack(pady=10)
            else:
                # continue the progress bar animation
                self.after(300, show_winner, n+20)

        show_winner() # start progress bar animation and then show the winner

app = Application()
app.mainloop()
```

Body:
This is how far I came.... I got the winner know I want to display it on the gui here is my code:
I tried many google searches and found none I hoped that someone may help me

import tkinter as tk
import random
from progress.bar import Bar
backroundcolor = '#C46C6C'
class Application(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.geometry('500x500')
        self.title('TheXoGenie')
        self.configure(bg=backroundcolor)
        title = tk.Label(self, text="Welcome to TheXoGenie", font='Helvetica 18 bold', bg=backroundcolor)
        title.pack(pady= 2, padx= 2)
        run = tk.Button(self, text ="Run", command = runn)
        run.pack(pady= 5, padx = 5)

def runn():
    PEOPLE = [
  'Juan',
  'Owen'
]

    print("\n\n")
    bar = Bar('And the winner is...', max=2)
    for i in range(2):
        [x for x in range(999999)]  # short pause...
        bar.next()
    bar.finish()
    print("\n\n\t{}!\n\n".format(random.choice(PEOPLE)))
    print("-" * 60 + "\n")

app = Application()
app.mainloop()


问:
Typescript - Convert from Array of types to Object of types
I need this type

```<code>type Sample = [a: string, b: number]
</code>```

to be converted to

```<code>type Sample2 = { a:string, b:number}
</code>```

I need this to pass arguments of a function in a paramenter, in form of an object

```<code>function example(otherFunctionParameters: Parameters<typeof otherFunction>){}
</code>```

I don't want to pass an array in the parameter.

How can I achieve this ?

答:
Because you can't manipulate tuple labels in the type system, the best you can do is manually supply a tuple of property keys, one for every parameter in the original function.

By adapting some utilities from this answer by jcalz, here's a generic utility that will give you a mapped object for the parameters in a function: You supply the function type and a tuple of labels for each parameter:

TS Playground

type ZipTuples<Keys extends readonly any[], Values extends readonly any[]> = {
  [K in keyof Keys]: [Keys[K], K extends keyof Values ? Values[K] : never];
};

type ZipTuplesAsObject<
  Keys extends readonly PropertyKey[],
  Values extends readonly any[],
> = { [T in ZipTuples<Keys, Values>[number] as T[0]]: T[1] };

type ParamsAsObject<
  Fn extends (...params: readonly any[]) => any,
  Keys extends readonly PropertyKey[],
> = ZipTuplesAsObject<Keys, Parameters<Fn>>;

// Use

declare function otherFunction (
  irrelevantLabel: string,
  alsoNotUsed: number,
  onlyTheTypesMatter: boolean,
): void;

function example (objectParam: ParamsAsObject<typeof otherFunction, ['a', 'b', 'c']>) {
  // objectParam; // { a: string; b: number; c: boolean; }
  const {a, b, c} = objectParam;
  a; // string
  b; // number
  c; // boolean
}

```

Body:
I need this type

type Sample = [a: string, b: number]

to be converted to

type Sample2 = { a:string, b:number}

I need this to pass arguments of a function in a paramenter, in form of an object

function example(otherFunctionParameters: Parameters<typeof otherFunction>){}

I don't want to pass an array in the parameter.

How can I achieve this ?

Body:
Because you can't manipulate tuple labels in the type system, the best you can do is manually supply a tuple of property keys, one for every parameter in the original function.

By adapting some utilities from this answer by jcalz, here's a generic utility that will give you a mapped object for the parameters in a function: You supply the function type and a tuple of labels for each parameter:

<a href="https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&target=99&useUnknownInCatchVariables=true&exactOptionalPropertyTypes=true#code/C4TwDgpgBAWglmAKgVzAGwgZwDwGkIiZQQAewEAdgCZEBOEAhlQPYVohQMUgDaAugBooANQZpkWYmUo0o9Jq3adu-AHxQAvFADeAWABQUKD1xQ4FKAGsCzAGZR8hPgC5jjzCcEOp5akWsgdiJiEkQA-MHiWJ5QrhQQAG4QtHwA3AYAvun6BqCQsAgo6FgAgpgA8gBGAFYQAMbA2AZG7j4ydIwsbBwACrTMkLSgjvwCzZGhbX5ynYocXLyCBupa2saIZhbwSKgYOO5ColGYqjwUyAC2lcl8nESIPAAMfC5QDwCMt1kGueDQPQxaAwLpgylVag0moYoAAxCykXyyAAUADo0WBAcDMK55F0lAt+ABKTTqBZjaGtBHtGYKbpQPoDZLDAijZaaAo7Yqgio1eqNA70zEXCDkWg4OGqVTZH76AD0sqgAFVMBAZVR6mhAdBbMgKA04KwoMxgAALZIw3X6w1I8ZwWj0DAJLjAAAyDGuaFcmGAtHMAHNyUYxJhmAA5Y3KiBUOKXa60QNG7qIM2IP6YACyDGAotclWYzAwXHJhNcCWYcCo0v0Or1wAN8JIwOKUCRzF5DQBQIurk7WLB7caeQgQWNZtoFtr9aEPAA5AwZ0IZ5UF1AZ3UZ3xVMS9ND5UaB72LqkoHu1gwvT7-cfKjGrslj3Vc-nCxRjxlxnVWN6dAwhJUhHUGTsm2ELAIe2RBsee7er6FB+uMlRQQq5x3rQH5IVAeYFowFCZEAA" rel="nofollow noreferrer">TS Playground

type ZipTuples<Keys extends readonly any[], Values extends readonly any[]> = {
  [K in keyof Keys]: [Keys[K], K extends keyof Values ? Values[K] : never];
};

type ZipTuplesAsObject<
  Keys extends readonly PropertyKey[],
  Values extends readonly any[],
> = { [T in ZipTuples<Keys, Values>[number] as T[0]]: T[1] };

type ParamsAsObject<
  Fn extends (...params: readonly any[]) => any,
  Keys extends readonly PropertyKey[],
> = ZipTuplesAsObject<Keys, Parameters<Fn>>;

// Use

declare function otherFunction (
  irrelevantLabel: string,
  alsoNotUsed: number,
  onlyTheTypesMatter: boolean,
): void;

function example (objectParam: ParamsAsObject<typeof otherFunction, ['a', 'b', 'c']>) {
  // objectParam; // { a: string; b: number; c: boolean; }
  const {a, b, c} = objectParam;
  a; // string
  b; // number
  c; // boolean
}


问:
Sbt task to load system environment variables
I have some yaml file with system environment variables needed for service run.

system:
  service: "name"
  port: 123
```
<p>I must have all these variables, loaded to the shell before run service start. But I want to load them by some sbt variable, maybe <code>load-dev-env</code>.</p>
<p>The main problem that I can't import libraries for yaml parsing (<code>circe-yaml</code>) into sbt shell execution and all imports like</p>
```import io.circe._
import cats._
```

are failed due to circe is no the subpackage of io or etc...

I've tried to put libraryDependencies to the ./project/build.sbt - no success

The last one thing - read all key/values manually but it doesn't look correct

Has someone done smth like this?

答:
This SBT build definition works:

Dir structure:

```<code>build.sbt
src/main/resources/config.yml
project/build.sbt
project/build.properties
</code>```

build.sbt:

```<code>ThisBuild / scalaVersion := "2.13.8"

ThisBuild / organization := "com.example"

lazy val hello = (project in file("."))
  .settings(
    name := "Hello",
    //libraryDependencies += "io.circe" %% "circe-yaml" % "0.14.1"
  )

lazy val loadEnv = TaskKey[Unit]("load-dev-env")
loadEnv := {
  import _root_.io.circe._
  import _root_.io.circe.yaml.parser
  import scala.io.Source
  val filename = "src/main/resources/config.yml"
  val confStr = Source.fromFile(filename).getLines.mkString("\n")
  println(confStr)
  val json: Either[ParsingFailure, Json] = parser.parse(confStr)
  println(json)
}
</code>```

project/build.sbt:

```<code>libraryDependencies += "io.circe" %% "circe-yaml" % "0.14.1"
</code>```

project/build.properties:

```<code>sbt.version=1.6.1
</code>```

src/main/resources/config.yml:

```<code>---
system:
  port: 123
  service: name
</code>```

Example of running it:

```<code>sbt:Hello> loadDevEnv
---
system:
  port: 123
  service: name

Right({
  "system" : {
    "port" : 123,
    "service" : "name"
  }
})
</code>```

It prints string from file followed by parsed json.

The important details are:

You need to put library dependency in the other build file in project dir.

You need to use _root_ because otherwise imports don't resolve if they are not part of core Scala or SBT plugins. At least I didn't find the way yet.

You can checkout the code here: https://github.com/izmailoff/sbt-import-test.

--- UPDATE ---:

I've added the full example in the repo. That required some changes since you can't update SBT settings from a Task you need to do it in a Command. Updated files below:

build.sbt:

```<code>ThisBuild / scalaVersion := "2.13.8"

ThisBuild / organization := "com.example"

// This is needed to get new env values from SBT:
fork := true

lazy val hello = (project in file("."))
  .settings(
    name := "Hello",
    //libraryDependencies += "io.circe" %% "circe-yaml" % "0.14.1"
  )

commands += Command.command("loadDevEnv") { state =>
  val env = Config.getEnvFromConf()
  val envStr = Config.prettyPrint(env)
  s"set envVars ++= ${envStr}" :: state
}
</code>```

project/Build.scala:

```<code>case class Service(port: Integer, service: String)

case class System(system: Service)

object Config {

    def getEnvFromConf(): Map[String, String] = {
        val filename = "src/main/resources/config.yml"
        val confStr = readConfig(filename)
        val conf = parseConfig(confStr)
        println(conf)
        val env = toEnv(conf)
        env
    }

    def readConfig(filename: String): String = {
      import scala.io.Source
      Source.fromFile(filename).getLines.mkString("\n") // use better way?
    }

    def parseConfig(conf: String): System = {
      import _root_.io.circe._
      import _root_.io.circe.yaml
      import _root_.io.circe.yaml._
      import _root_.io.circe.yaml.syntax._
      import _root_.io.circe.generic.auto._
      import cats.syntax.either._
      val json: Either[ParsingFailure, Json] = yaml.parser.parse(conf)
      json
        .leftMap(err => err: Error)
        .flatMap(_.as[System])
        .valueOr(throw _)
    }

    def toEnv(conf: System): Map[String, String] = {
      Map(s"service.${conf.system.service}" -> conf.system.port.toString)
    }

    def prettyPrint(x: Map[String, String]): String = {
      "Map(" + (x.map{ case (k, v) => s""""${k}"->"${v}""""}).mkString(", ") + ")"
    }

}
</code>```

project.build.sbt:

```<code>val circeVersion = "0.14.1"

libraryDependencies ++= Seq(
  "io.circe" %% "circe-yaml",
  "io.circe" %% "circe-generic",
  "io.circe" %% "circe-parser"
).map(_ % circeVersion)
</code>```

src/main/scala/Main.scala:

```<code>object Main extends App {
  println("Found the following environment variable:")
  println(System.getenv("service.name"))
}
</code>```

EXAMPLE:

Run SBT from your OS shell:

```<code>ThisBuild / scalaVersion := "2.13.8"

ThisBuild / organization := "com.example"

lazy val hello = (project in file("."))
  .settings(
    name := "Hello",
    //libraryDependencies += "io.circe" %% "circe-yaml" % "0.14.1"
  )

lazy val loadEnv = TaskKey[Unit]("load-dev-env")
loadEnv := {
  import _root_.io.circe._
  import _root_.io.circe.yaml.parser
  import scala.io.Source
  val filename = "src/main/resources/config.yml"
  val confStr = Source.fromFile(filename).getLines.mkString("\n")
  println(confStr)
  val json: Either[ParsingFailure, Json] = parser.parse(confStr)
  println(json)
}
</code>```0

Run the app to check if environment variables are set:

```<code>ThisBuild / scalaVersion := "2.13.8"

ThisBuild / organization := "com.example"

lazy val hello = (project in file("."))
  .settings(
    name := "Hello",
    //libraryDependencies += "io.circe" %% "circe-yaml" % "0.14.1"
  )

lazy val loadEnv = TaskKey[Unit]("load-dev-env")
loadEnv := {
  import _root_.io.circe._
  import _root_.io.circe.yaml.parser
  import scala.io.Source
  val filename = "src/main/resources/config.yml"
  val confStr = Source.fromFile(filename).getLines.mkString("\n")
  println(confStr)
  val json: Either[ParsingFailure, Json] = parser.parse(confStr)
  println(json)
}
</code>```1

Getting null. Load env:

```<code>ThisBuild / scalaVersion := "2.13.8"

ThisBuild / organization := "com.example"

lazy val hello = (project in file("."))
  .settings(
    name := "Hello",
    //libraryDependencies += "io.circe" %% "circe-yaml" % "0.14.1"
  )

lazy val loadEnv = TaskKey[Unit]("load-dev-env")
loadEnv := {
  import _root_.io.circe._
  import _root_.io.circe.yaml.parser
  import scala.io.Source
  val filename = "src/main/resources/config.yml"
  val confStr = Source.fromFile(filename).getLines.mkString("\n")
  println(confStr)
  val json: Either[ParsingFailure, Json] = parser.parse(confStr)
  println(json)
}
</code>```2

Run the app to check again:

```<code>sbt:Hello> run
[info] running (fork) Main
[info] Found the following environment variable:
[info] 123
</code>```

Found value 123.

Body:
I have some yaml file with system environment variables needed for service run.

system:
  service: "name"
  port: 123

I must have all these variables, loaded to the shell before run service start. But I want to load them by some sbt variable, maybe load-dev-env.

The main problem that I can't import libraries for yaml parsing (circe-yaml) into sbt shell execution and all imports like

import io.circe._
import cats._

are failed due to circe is no the subpackage of io or etc...

I've tried to put libraryDependencies to the ./project/build.sbt - no success

The last one thing - read all key/values manually but it doesn't look correct

Has someone done smth like this?

Body:
This SBT build definition works:

Dir structure:

build.sbt
src/main/resources/config.yml
project/build.sbt
project/build.properties

build.sbt:

ThisBuild / scalaVersion := "2.13.8"

ThisBuild / organization := "com.example"

lazy val hello = (project in file("."))
  .settings(
    name := "Hello",
    //libraryDependencies += "io.circe" %% "circe-yaml" % "0.14.1"
  )

lazy val loadEnv = TaskKey[Unit]("load-dev-env")
loadEnv := {
  import _root_.io.circe._
  import _root_.io.circe.yaml.parser
  import scala.io.Source
  val filename = "src/main/resources/config.yml"
  val confStr = Source.fromFile(filename).getLines.mkString("\n")
  println(confStr)
  val json: Either[ParsingFailure, Json] = parser.parse(confStr)
  println(json)
}

project/build.sbt:

libraryDependencies += "io.circe" %% "circe-yaml" % "0.14.1"

project/build.properties:

sbt.version=1.6.1

src/main/resources/config.yml:

---
system:
  port: 123
  service: name

Example of running it:

sbt:Hello> loadDevEnv
---
system:
  port: 123
  service: name

Right({
  "system" : {
    "port" : 123,
    "service" : "name"
  }
})

It prints string from file followed by parsed json.

The important details are:

You need to put library dependency in the other build file in project dir.

You need to use _root_ because otherwise imports don't resolve if they are not part of core Scala or SBT plugins. At least I didn't find the way yet.

You can checkout the code here: https://github.com/izmailoff/sbt-import-test.

--- UPDATE ---:

I've added the full example in the repo. That required some changes since you can't update SBT settings from a Task you need to do it in a Command. Updated files below:

build.sbt:

ThisBuild / scalaVersion := "2.13.8"

ThisBuild / organization := "com.example"

// This is needed to get new env values from SBT:
fork := true

lazy val hello = (project in file("."))
  .settings(
    name := "Hello",
    //libraryDependencies += "io.circe" %% "circe-yaml" % "0.14.1"
  )

commands += Command.command("loadDevEnv") { state =>
  val env = Config.getEnvFromConf()
  val envStr = Config.prettyPrint(env)
  s"set envVars ++= ${envStr}" :: state
}

project/Build.scala:

case class Service(port: Integer, service: String)

case class System(system: Service)

object Config {

    def getEnvFromConf(): Map[String, String] = {
        val filename = "src/main/resources/config.yml"
        val confStr = readConfig(filename)
        val conf = parseConfig(confStr)
        println(conf)
        val env = toEnv(conf)
        env
    }

    def readConfig(filename: String): String = {
      import scala.io.Source
      Source.fromFile(filename).getLines.mkString("\n") // use better way?
    }

    def parseConfig(conf: String): System = {
      import _root_.io.circe._
      import _root_.io.circe.yaml
      import _root_.io.circe.yaml._
      import _root_.io.circe.yaml.syntax._
      import _root_.io.circe.generic.auto._
      import cats.syntax.either._
      val json: Either[ParsingFailure, Json] = yaml.parser.parse(conf)
      json
        .leftMap(err => err: Error)
        .flatMap(_.as[System])
        .valueOr(throw _)
    }

    def toEnv(conf: System): Map[String, String] = {
      Map(s"service.${conf.system.service}" -> conf.system.port.toString)
    }

    def prettyPrint(x: Map[String, String]): String = {
      "Map(" + (x.map{ case (k, v) => s""""${k}"->"${v}""""}).mkString(", ") + ")"
    }

}

project.build.sbt:

val circeVersion = "0.14.1"

libraryDependencies ++= Seq(
  "io.circe" %% "circe-yaml",
  "io.circe" %% "circe-generic",
  "io.circe" %% "circe-parser"
).map(_ % circeVersion)

src/main/scala/Main.scala:

object Main extends App {
  println("Found the following environment variable:")
  println(System.getenv("service.name"))
}

EXAMPLE:

Run SBT from your OS shell:

> sbt

Run the app to check if environment variables are set:

sbt:Hello> run
[info] running (fork) Main
[info] Found the following environment variable:
[info] null

Getting null. Load env:

sbt:Hello> loadDevEnv
[info] Defining envVars
[info] The new value will be used by Compile / bspBuildTargetRun, Compile / bspScalaMainClassesItem and 6 others.
[info]  Run `last` for details.
[info] Reapplying settings...
[info] set current project to Hello (in build file:/home/tvc/repos/sbt_test/)

Run the app to check again:

sbt:Hello> run
[info] running (fork) Main
[info] Found the following environment variable:
[info] 123

Found value 123.


问:
Filtering elements of array on the basis of dates
I have a array as follows:

data = [
    {
      "startDate": "2021-08-18T00:00:04.498059"
      "endDate": "2021-08-19T00:00:04.4962889"
    },
    {
      "startDate": "2021-08-18T00:00:04.498059"
      "endDate": "2021-08-19T00:00:04.4962889"
    }
    ]

    newArray = [];
    this.data.foreach(element => {
       if((element.startDate - element.endDate) > 7) {
           this.newArray.push(element);
       }
    })```

I want to traverse the above array and check if difference between startDate and endDate is greater than 7 days for any element, than push that element to a new array.

Because of the date format I don't know my approach is correct or not. How can I do this correctly?

答:
You can check using moment.js library

let data = [
{
  startDate: "2021-08-18T00:00:04.498059",
  endDate: "2021-08-19T00:00:04.4962889",
},
{
  startDate: "2021-08-11T00:00:04.498059",
  endDate: "2021-08-19T00:00:04.4962889",
}
];
let newArray = [];
for(let i of data){
let end= moment(i['endDate']);
let start= moment(i['startDate']);
let diff = end.diff(start, 'days')
console.log(diff);
if(diff >= 7){
newArray.push(i);
}
}
console.log(newArray);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://momentjs.com/downloads/moment.js"></script></code>```

Body:
I have a array as follows:

data = [
    {
      "startDate": "2021-08-18T00:00:04.498059"
      "endDate": "2021-08-19T00:00:04.4962889"
    },
    {
      "startDate": "2021-08-18T00:00:04.498059"
      "endDate": "2021-08-19T00:00:04.4962889"
    }
    ]

    newArray = [];
    this.data.foreach(element => {
       if((element.startDate - element.endDate) > 7) {
           this.newArray.push(element);
       }
    })

I want to traverse the above array and check if difference between startDate and endDate is greater than 7 days for any element, than push that element to a new array.

Because of the date format I don't know my approach is correct or not. How can I do this correctly?

Body:
You can check using moment.js library

let data = [
{
  startDate: "2021-08-18T00:00:04.498059",
  endDate: "2021-08-19T00:00:04.4962889",
},
{
  startDate: "2021-08-11T00:00:04.498059",
  endDate: "2021-08-19T00:00:04.4962889",
}
];
let newArray = [];
for(let i of data){
let end= moment(i['endDate']);
let start= moment(i['startDate']);
let diff = end.diff(start, 'days')
console.log(diff);
if(diff >= 7){
newArray.push(i);
}
}
console.log(newArray);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://momentjs.com/downloads/moment.js"></script>


问:
Resolve conflict between System.Drawing and System.Drawing.Common
I am trying to add SpreadSheetLight to a new Dnn v9.10.2 project running on Windows Server 2019, but I get a runtime error saying

CS0433: The type 'Image' exists in both 'System.Drawing.Common,
Version=4.0.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' and
'System.Drawing, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a'

when I copy the dlls into the bin folder. I have a file that was using System.Drawing, but it was using the full namespace in it's references. I tried updating those to System.Drawing.Common, but it instead throws the error

CS0234: The type or namespace name 'Common' does not exist in the
namespace 'System.Drawing' (are you missing an assembly reference?)

Commenting out the lines of code using System.Drawing resolved the runtime error, but ultimately when trying a simple test of just opening and closing a blank workbook it throws the exception

System.PlatformNotSupportedException: System.Drawing is not supported
on this platform.

I haven't been able to find much on how to fix this so any help would be appreciated.

答:
Upon first glance it seems that this library is a .NET 3.5 library and DNN Platform 9.10.2 is .NET Framework 4.7.2 you are most likely hitting a compatibility issue with changes in .NET 4.7.

It looks like the source for SpereadSheetLight is available, you could try to recompile it for .NET 4.7.2 and see if you can clear the issue.


问:
Pandas json_normalize and null values in JSON
I have this sample JSON

```<code>{
    "name":"John",
    "age":30,
    "cars": [
        { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
        { "name":"BMW", "models":[ "320", "X3", "X5" ] },
        { "name":"Fiat", "models":[ "500", "Panda" ] }
    ]
 }
</code>```

When I need to convert JSON to pandas DataFrame I use following code

```<code>import json
from pandas.io.json import json_normalize
from pprint import pprint

with open('example.json', encoding="utf8") as data_file:
    data = json.load(data_file)
normalized = json_normalize(data['cars'])
</code>```

This code works well but in the case of some empty cars (null values) I'm not possible to normalize_json.

Example of json

```<code>{
    "name":"John",
    "age":30,
    "cars": [
        { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
        null,
        { "name":"Fiat", "models":[ "500", "Panda" ] }
    ]
 }
</code>```

Error that was thrown

```<code>AttributeError: 'NoneType' object has no attribute 'keys'
</code>```

I tried to ignore errors in json_normalize, but didn't help

```<code>normalized = json_normalize(data['cars'], errors='ignore')
</code>```

How should I handle null values in JSON?

答:
How is Another Answer?</p>
```<code>data['cars'].fillna('{}')
</code>```

Body:
I have this sample JSON

{
    "name":"John",
    "age":30,
    "cars": [
        { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
        { "name":"BMW", "models":[ "320", "X3", "X5" ] },
        { "name":"Fiat", "models":[ "500", "Panda" ] }
    ]
 }

When I need to convert JSON to pandas DataFrame I use following code

import json
from pandas.io.json import json_normalize
from pprint import pprint

with open('example.json', encoding="utf8") as data_file:
    data = json.load(data_file)
normalized = json_normalize(data['cars'])

This code works well but in the case of some empty cars (null values) I'm not possible to normalize_json.

Example of json

{
    "name":"John",
    "age":30,
    "cars": [
        { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
        null,
        { "name":"Fiat", "models":[ "500", "Panda" ] }
    ]
 }

Error that was thrown

AttributeError: 'NoneType' object has no attribute 'keys'

I tried to ignore errors in json_normalize, but didn't help

normalized = json_normalize(data['cars'], errors='ignore')

How should I handle null values in JSON?

Body:
How is Another Answer?

data['cars'].fillna('{}')


问:
How do I generate this report by importing the hostname to a list or csv?
I had this script, but the format was in HTML and I cleaned up all the code and changed the commands that were "gwmi" to "Get-CimInstance" to have good practices. My goal is to transform this script that handles a hostname to a list of hostnames.

Can someone help me?

The idea I had would be to have a window that has a "browse" button to import the list, be it in txt or csv and for each hostname in that list it would do these commands and in the end it would export to an xlsx file (I tried with Export-Excel, but you need to download the module separately, and you need to trust the repository, authorize the import of the module for later use, so I would have to make this standalone, without any request, because I would convert this ps1 into an exe file) and the data, would need to be side by side with the headers, e.g. Hostname, Last User Logged, Type Of Chassis etc.

I would be very grateful if someone can help me, I've been building part 1 of this script for a few hours now, and now I need to go to part 2 (that is this process to create and export csv results) which is the part where I feel stuck.

```<code>Add-Type -AssemblyName Microsoft.VisualBasic
$ComputerName = [Microsoft.VisualBasic.Interaction]::InputBox("Insert the hostname Name", "Hardware Report")
If ($ComputerName -eq "")
{
    break
}

#Check computer online in network, if is not online, the hostname will be skipped but necessary add in log entry which computers is offline
$ProgressPreference = 'SilentlyContinue'
try {
    $ErrorActionPreference = "Stop";
    $TestComputerHost = Test-Connection $ComputerName -Count 1 -InformationAction Continue -WarningAction SilentlyContinue;
    } catch {
    #Hostname will be skipped
    } finally {
    $ProgressPreference = 'Continue'
    $ErrorActionPreference = "Continue"
    }

#Validade crucial service that is crucial for get remote data, and if is not possible to get this information, the hostname will be skipped
try {
$ErrorActionPreference = "Stop"
Get-CimInstance win32_operatingsystem -ComputerName $ComputerName | Out-Null }
catch [System.Runtime.InteropServices.COMException]
    {
    #Hostname will be skipped
    }

#Validate if the WS Management service is enabled on the remote device
$ProgressPreference = 'SilentlyContinue'
$TestComputerHost = Test-NetConnection $ComputerName -Port 5985 -InformationLevel Quiet -WarningAction SilentlyContinue
If ($TestComputerHost -ne "False"){

}
$ProgressPreference = 'Continue'

#Function to create the Get-WUChassisType that is performed to find out if the Chassis of the equipment is Notebook or Desktop, and it is not configured to detect virtual machine
Function Get-WUChassisType {

    [CmdletBinding()]
    param (
    )
    Set-StrictMode -Version 'Latest'
    [int[]]$chassisType = try {
    $ErrorActionPreference = "Stop";
    Get-CimInstance Win32_SystemEnclosure -ComputerName $ComputerName | Select-Object -ExpandProperty ChassisTypes;
    } catch {
    #Here need to be blank result or skip this result but keep the rest results
    } finally {
    $ErrorActionPreference = "Continue";
    }
    switch ($chassisType) {
        { $_ -in 3, 4, 5, 6, 7, 15, 16 } {
            return 'Desktop'
        }
        { $_ -in 8, 9, 10, 11, 12, 14, 18, 21, 31, 32 } {
            return 'Notebook'
        }
        { $_ -in 30 } {
            return 'Tablet'
        }
        { $_ -in 17, 23 } {
            return 'Servidor'
        }
        Default {
        }
    }
}

#Function to get last logged user on remote computer
Function Get-LastUser {
try {
$ErrorActionPreference = "Stop"
Get-WmiObject Win32_LoggedOnUser -ComputerName $ComputerName |
    Select Antecedent -Unique |
    % {
        $domain = $_.Antecedent.Split('"')[1]
        if($domain -eq "DOMAIN") {
            "{0}\{1}" -f $domain, $_.Antecedent.Split('"')[3]
        }
    } | Select-Object -First 1
    } catch [System.Runtime.InteropServices.COMException]
    {

    }
    }

#Name of remote computer
$Name = 'Hostname' + $ComputerName

#Get last logged user (by function)
$LastLoggedUser = ((Get-LastUser).Split('\')[1])

#Last Boot Time
$LastBoot = (Get-CimInstance win32_operatingsystem -ComputerName $ComputerName |Select-Object CSName, LastBootUpTime | Select -ExpandProperty LastBootUpTime).tostring("dd/MM/yyyy hh:mm:ss")

#Chassis Type Of Computer
$ChassisType = Get-WUChassisType

#Operating System
$OS = (Get-CimInstance win32_operatingsystem -ComputerName $ComputerName).caption

#System Installed On
$SystemInstalledOn = ((Get-CimInstance Win32_OperatingSystem -ComputerName $ComputerName).InstallDate).tostring("dd/MM/yyyy hh:mm:ss")

#Processor
$Processor = (Get-CimInstance win32_processor -ComputerName $ComputerName -filter "deviceid='CPU0'").Name

#Disk
$Disk = (Get-CimInstance Win32_LogicalDisk -ComputerName $ComputerName | Select-Object @{Name="Size"; Expression={"$([math]::round($_.Size / 1GB,2))GB"}}).Size

#Ram Memory
$Ram = (Get-CimInstance Win32_PhysicalMemory -ComputerName $ComputerName | Select-Object @{Name="Capacity"; Expression={"$([math]::round($_.Capacity / 1GB,2))GB"}}).Capacity

#Serial Number
$SerialNumber = Get-CimInstance win32_bios -ComputerName $ComputerName | Select-Object -ExpandProperty SerialNumber

#Manufacturer
$Manufacturer = Get-CimInstance win32_ComputerSystemProduct -ComputerName $ComputerName | Select-Object -ExpandProperty Vendor

#Model
$Model = Get-CimInstance win32_ComputerSystemProduct -ComputerName $ComputerName | Select-Object -ExpandProperty Name

#Export to CSV
$Name + $LastLoggedUser + $ChassisType + $LastBoot + $OS + $SystemInstalledOn + $Processor + $Disk + $Ram + $SerialNumber + $Manufacturer + $Model | Export-Csv

#Dialog box to information finish script
[Microsoft.VisualBasic.Interaction]::MsgBox("Report is finished", "OKOnly,SystemModal,Information", "Success") | Out-Null```
```

答:
Here is an example of how I'd make an initial pass at changing your function with the primary changes being:

Multiple calls were being made to the same class, remotely.  This is really inefficient.  The calls were consolidated to store the result of the first call in a single variable and then reference the variable's properties for the additional information.

Your script is setting preferences, globally, a lot.  All PowerShell cmdlets allow you to set the ErrorActionPreference inline, so setting it globally back and forth is unnecessary.

By prestaging an output object ($temp) and emitting it where the code quits processing, you can see the results of partial communications failures (e.g. pingable but WinRM off, etc.).

Your chassis function shouldn't have worked.  Since chassisTypes returns an array, you can't use the -in operator to check if an array exists in an array.  I used some code from another SO article that shows some pretty cool PowerShell on how to make this value report the chassis values accurately.

The CIM instance of Win32_LoggedOnUser returns the 'domain' and 'name' properties directly so you don't need to string-parse the values using splits and array references.

Examples of using it in the desired states you specified in the question are at the bottom (accepting multiple computer names and accepting them from the contents of a file (not with a popup, but I hope you'll see how not using GUIs will be more helpful)).

For the amount of independent remote calls you're making, if you identify that the code runs slower than you'd like, you might think about adapting it to use Invoke-Command.  This would pass all of your code to the remote machine once, process it on the remote machine, and just return the output object.  In my experience, this dramatically reduces the execution time of the script (e.g. I was able to pull information from thousands of servers spanning the globe in about 15 minutes using Invoke-Command, whereas individual remote calls took 12 hours or more).

```<code>Function Generate-ComputerHwReport {
    param(
        [Parameter(Mandatory=$true)] [string[]] [ValidateNotNullOrEmpty()] $ComputerNames ## This lines requires the passed in value to be an array of strings
    )

        ## Modification -- Looping through the array to check all computers passed in
        foreach ($ComputerName in $ComputerNames) {

            $temp = [pscustomobject] @{
                TestPing     = $false
                TestWinRM    = $false
                TestWSMan    = $false
                Hostname     = $ComputerName
                LastUser     = ''
                LastBootTime = ''
                ChassisType  = ''
                OS           = ''
                InstallDate  = ''
                Processor    = ''
                Disk         = ''
                Ram          = ''
                SerialNumber = ''
                Manufacturer = ''
                Model        = ''
                ErrorLog     = ''
            }

            #Check computer online in network, if is not online, the hostname will be skipped but necessary add in log entry which computers is offline
            if (Test-Connection $ComputerName -Count 1 -Quiet) {
                $temp.TestPing = $true
            } else {
                $temp
                continue
            }

            #Validade crucial service that is crucial for get remote data, and if is not possible to get this information, the hostname will be skipped
            try {
                $Win32_OS = Get-CimInstance win32_operatingsystem -ComputerName $ComputerName -ErrorAction Stop
                $temp.TestWinRM = $true
                $temp.LastBootTime = $Win32_OS.LastBootUpTime.ToString("dd/MM/yyyy hh:mm:ss")
                $temp.OS = $Win32_OS.Caption
                $temp.InstallDate = $Win32_OS.InstallDate.ToString("dd/MM/yyyy hh:mm:ss")
            } catch {
                #Hostname will be skipped
                $temp
                continue
            }

            #Validate if the WS Management service is enabled on the remote device
            if ((Test-NetConnection $ComputerName -Port 5985).TcpTestSucceeded) {
                $temp.TestWSMan = $true
            } else {
                $temp
                continue
            }

            #Function to create the Get-WUChassisType that is performed to find out if the Chassis of the equipment is Notebook or Desktop, and it is not configured to detect virtual machine

            ## https://stackoverflow.com/questions/55184682/powershell-getting-chassis-types-info
            $ChassisTypes = @{
                Name = 'ChassisType'
                Expression = {
                    # property is an array, so process all values
                    $result = foreach($value in $_.ChassisTypes)
                    {
                        switch([int]$value)
                        {
                            1          {'Other'}
                            2          {'Unknown'}
                            3          {'Desktop'}
                            4          {'Low Profile Desktop'}
                            5          {'Pizza Box'}
                            6          {'Mini Tower'}
                            7          {'Tower'}
                            8          {'Portable'}
                            9          {'Laptop'}
                            10         {'Notebook'}
                            11         {'Hand Held'}
                            12         {'Docking Station'}
                            13         {'All in One'}
                            14         {'Sub Notebook'}
                            15         {'Space-Saving'}
                            16         {'Lunch Box'}
                            17         {'Main System Chassis'}
                            18         {'Expansion Chassis'}
                            19         {'SubChassis'}
                            20         {'Bus Expansion Chassis'}
                            21         {'Peripheral Chassis'}
                            22         {'Storage Chassis'}
                            23         {'Rack Mount Chassis'}
                            24         {'Sealed-Case PC'}
                            default    {"$value"}
                        }

                    }
                    $result
                }
            }

            $temp.ChassisType = (Get-CimInstance -ClassName Win32_SystemEnclosure -ComputerName $ComputerName | Select-Object -Property $ChassisTypes).ChassisType

            #Function to get last logged user on remote computer
            try {
                $t = Get-CimInstance win32_loggedonuser -ComputerName $ComputerName -ErrorAction Stop | Select Antecedent -Unique

                $temp.LastUser = "{0}\{1}" -f $t.Antecedent.Domain, $t.Antecedent.Name
            } catch {
                $temp.ErrorLog += $_
            }

            #Processor
            $temp.Processor = (Get-CimInstance win32_processor -ComputerName $ComputerName -filter "deviceid='CPU0'").Name

            #Disk
            $temp.Disk = ((Get-CimInstance Win32_LogicalDisk -ComputerName $ComputerName | Select-Object @{Name="Size"; Expression={"$([math]::round($_.Size / 1GB,2))GB"}}).Size) -join ', '

            #Ram Memory
            $temp.Ram = ((Get-CimInstance Win32_PhysicalMemory -ComputerName $ComputerName | Select-Object @{Name="Capacity"; Expression={"$([math]::round($_.Capacity / 1GB,2))GB"}}).Capacity) -join ', '

            #Serial Number
            $temp.SerialNumber = Get-CimInstance win32_bios -ComputerName $ComputerName | Select-Object -ExpandProperty SerialNumber

            #Manufacturer
            $temp.Manufacturer = Get-CimInstance win32_ComputerSystemProduct -ComputerName $ComputerName | Select-Object -ExpandProperty Vendor

            #Model
            $temp.Model = Get-CimInstance win32_ComputerSystemProduct -ComputerName $ComputerName | Select-Object -ExpandProperty Name

            $temp
        }
    }

    ## Output to console
    Generate-ComputerHwReport -ComputerNames localhost, pc2

    ## Output to console reading in the computer names from a file
    Generate-ComputerHwReport -ComputerNames (gc listofcomputernames.txt)

    ## Output to CSV reading in the computer names from a file
    Generate-ComputerHwReport -ComputerNames (gc listofcomputernames.txt) | Export-Csv -NoTypeInformation ComputerHwReport.csv
</code>```

Body:
I had this script, but the format was in HTML and I cleaned up all the code and changed the commands that were "gwmi" to "Get-CimInstance" to have good practices. My goal is to transform this script that handles a hostname to a list of hostnames.

Can someone help me?

The idea I had would be to have a window that has a "browse" button to import the list, be it in txt or csv and for each hostname in that list it would do these commands and in the end it would export to an xlsx file (I tried with Export-Excel, but you need to download the module separately, and you need to trust the repository, authorize the import of the module for later use, so I would have to make this standalone, without any request, because I would convert this ps1 into an exe file) and the data, would need to be side by side with the headers, e.g. Hostname, Last User Logged, Type Of Chassis etc.

I would be very grateful if someone can help me, I've been building part 1 of this script for a few hours now, and now I need to go to part 2 (that is this process to create and export csv results) which is the part where I feel stuck.

Add-Type -AssemblyName Microsoft.VisualBasic
$ComputerName = [Microsoft.VisualBasic.Interaction]::InputBox("Insert the hostname Name", "Hardware Report")
If ($ComputerName -eq "")
{
    break
}

#Check computer online in network, if is not online, the hostname will be skipped but necessary add in log entry which computers is offline
$ProgressPreference = 'SilentlyContinue'
try {
    $ErrorActionPreference = "Stop";
    $TestComputerHost = Test-Connection $ComputerName -Count 1 -InformationAction Continue -WarningAction SilentlyContinue;
    } catch {
    #Hostname will be skipped
    } finally {
    $ProgressPreference = 'Continue'
    $ErrorActionPreference = "Continue"
    }

#Validade crucial service that is crucial for get remote data, and if is not possible to get this information, the hostname will be skipped
try {
$ErrorActionPreference = "Stop"
Get-CimInstance win32_operatingsystem -ComputerName $ComputerName | Out-Null }
catch [System.Runtime.InteropServices.COMException]
    {
    #Hostname will be skipped
    }

#Validate if the WS Management service is enabled on the remote device
$ProgressPreference = 'SilentlyContinue'
$TestComputerHost = Test-NetConnection $ComputerName -Port 5985 -InformationLevel Quiet -WarningAction SilentlyContinue
If ($TestComputerHost -ne "False"){

}
$ProgressPreference = 'Continue'

#Function to create the Get-WUChassisType that is performed to find out if the Chassis of the equipment is Notebook or Desktop, and it is not configured to detect virtual machine
Function Get-WUChassisType {

    [CmdletBinding()]
    param (
    )
    Set-StrictMode -Version 'Latest'
    [int[]]$chassisType = try {
    $ErrorActionPreference = "Stop";
    Get-CimInstance Win32_SystemEnclosure -ComputerName $ComputerName | Select-Object -ExpandProperty ChassisTypes;
    } catch {
    #Here need to be blank result or skip this result but keep the rest results
    } finally {
    $ErrorActionPreference = "Continue";
    }
    switch ($chassisType) {
        { $_ -in 3, 4, 5, 6, 7, 15, 16 } {
            return 'Desktop'
        }
        { $_ -in 8, 9, 10, 11, 12, 14, 18, 21, 31, 32 } {
            return 'Notebook'
        }
        { $_ -in 30 } {
            return 'Tablet'
        }
        { $_ -in 17, 23 } {
            return 'Servidor'
        }
        Default {
        }
    }
}

#Function to get last logged user on remote computer
Function Get-LastUser {
try {
$ErrorActionPreference = "Stop"
Get-WmiObject Win32_LoggedOnUser -ComputerName $ComputerName |
    Select Antecedent -Unique |
    % {
        $domain = $_.Antecedent.Split('"')[1]
        if($domain -eq "DOMAIN") {
            "{0}\{1}" -f $domain, $_.Antecedent.Split('"')[3]
        }
    } | Select-Object -First 1
    } catch [System.Runtime.InteropServices.COMException]
    {

    }
    }

#Name of remote computer
$Name = 'Hostname' + $ComputerName

#Get last logged user (by function)
$LastLoggedUser = ((Get-LastUser).Split('\')[1])

#Last Boot Time
$LastBoot = (Get-CimInstance win32_operatingsystem -ComputerName $ComputerName |Select-Object CSName, LastBootUpTime | Select -ExpandProperty LastBootUpTime).tostring("dd/MM/yyyy hh:mm:ss")

#Chassis Type Of Computer
$ChassisType = Get-WUChassisType

#Operating System
$OS = (Get-CimInstance win32_operatingsystem -ComputerName $ComputerName).caption

#System Installed On
$SystemInstalledOn = ((Get-CimInstance Win32_OperatingSystem -ComputerName $ComputerName).InstallDate).tostring("dd/MM/yyyy hh:mm:ss")

#Processor
$Processor = (Get-CimInstance win32_processor -ComputerName $ComputerName -filter "deviceid='CPU0'").Name

#Disk
$Disk = (Get-CimInstance Win32_LogicalDisk -ComputerName $ComputerName | Select-Object @{Name="Size"; Expression={"$([math]::round($_.Size / 1GB,2))GB"}}).Size

#Ram Memory
$Ram = (Get-CimInstance Win32_PhysicalMemory -ComputerName $ComputerName | Select-Object @{Name="Capacity"; Expression={"$([math]::round($_.Capacity / 1GB,2))GB"}}).Capacity

#Serial Number
$SerialNumber = Get-CimInstance win32_bios -ComputerName $ComputerName | Select-Object -ExpandProperty SerialNumber

#Manufacturer
$Manufacturer = Get-CimInstance win32_ComputerSystemProduct -ComputerName $ComputerName | Select-Object -ExpandProperty Vendor

#Model
$Model = Get-CimInstance win32_ComputerSystemProduct -ComputerName $ComputerName | Select-Object -ExpandProperty Name

#Export to CSV
$Name + $LastLoggedUser + $ChassisType + $LastBoot + $OS + $SystemInstalledOn + $Processor + $Disk + $Ram + $SerialNumber + $Manufacturer + $Model | Export-Csv

#Dialog box to information finish script
[Microsoft.VisualBasic.Interaction]::MsgBox("Report is finished", "OKOnly,SystemModal,Information", "Success") | Out-Null```

Body:
Here is an example of how I'd make an initial pass at changing your function with the primary changes being:

Multiple calls were being made to the same class, remotely.  This is really inefficient.  The calls were consolidated to store the result of the first call in a single variable and then reference the variable's properties for the additional information.

Your script is setting preferences, globally, a lot.  All PowerShell cmdlets allow you to set the ErrorActionPreference inline, so setting it globally back and forth is unnecessary.

By prestaging an output object ($temp) and emitting it where the code quits processing, you can see the results of partial communications failures (e.g. pingable but WinRM off, etc.).

Your chassis function shouldn't have worked.  Since chassisTypes returns an array, you can't use the -in operator to check if an array exists in an array.  I used some code from another SO article that shows some pretty cool PowerShell on how to make this value report the chassis values accurately.

The CIM instance of Win32_LoggedOnUser returns the 'domain' and 'name' properties directly so you don't need to string-parse the values using splits and array references.

Examples of using it in the desired states you specified in the question are at the bottom (accepting multiple computer names and accepting them from the contents of a file (not with a popup, but I hope you'll see how not using GUIs will be more helpful)).

For the amount of independent remote calls you're making, if you identify that the code runs slower than you'd like, you might think about adapting it to use Invoke-Command.  This would pass all of your code to the remote machine once, process it on the remote machine, and just return the output object.  In my experience, this dramatically reduces the execution time of the script (e.g. I was able to pull information from thousands of servers spanning the globe in about 15 minutes using Invoke-Command, whereas individual remote calls took 12 hours or more).

Function Generate-ComputerHwReport {
    param(
        [Parameter(Mandatory=$true)] [string[]] [ValidateNotNullOrEmpty()] $ComputerNames ## This lines requires the passed in value to be an array of strings
    )

        ## Modification -- Looping through the array to check all computers passed in
        foreach ($ComputerName in $ComputerNames) {

            $temp = [pscustomobject] @{
                TestPing     = $false
                TestWinRM    = $false
                TestWSMan    = $false
                Hostname     = $ComputerName
                LastUser     = ''
                LastBootTime = ''
                ChassisType  = ''
                OS           = ''
                InstallDate  = ''
                Processor    = ''
                Disk         = ''
                Ram          = ''
                SerialNumber = ''
                Manufacturer = ''
                Model        = ''
                ErrorLog     = ''
            }

            #Check computer online in network, if is not online, the hostname will be skipped but necessary add in log entry which computers is offline
            if (Test-Connection $ComputerName -Count 1 -Quiet) {
                $temp.TestPing = $true
            } else {
                $temp
                continue
            }

            #Validade crucial service that is crucial for get remote data, and if is not possible to get this information, the hostname will be skipped
            try {
                $Win32_OS = Get-CimInstance win32_operatingsystem -ComputerName $ComputerName -ErrorAction Stop
                $temp.TestWinRM = $true
                $temp.LastBootTime = $Win32_OS.LastBootUpTime.ToString("dd/MM/yyyy hh:mm:ss")
                $temp.OS = $Win32_OS.Caption
                $temp.InstallDate = $Win32_OS.InstallDate.ToString("dd/MM/yyyy hh:mm:ss")
            } catch {
                #Hostname will be skipped
                $temp
                continue
            }

            #Validate if the WS Management service is enabled on the remote device
            if ((Test-NetConnection $ComputerName -Port 5985).TcpTestSucceeded) {
                $temp.TestWSMan = $true
            } else {
                $temp
                continue
            }

            #Function to create the Get-WUChassisType that is performed to find out if the Chassis of the equipment is Notebook or Desktop, and it is not configured to detect virtual machine

            ## https://stackoverflow.com/questions/55184682/powershell-getting-chassis-types-info
            $ChassisTypes = @{
                Name = 'ChassisType'
                Expression = {
                    # property is an array, so process all values
                    $result = foreach($value in $_.ChassisTypes)
                    {
                        switch([int]$value)
                        {
                            1          {'Other'}
                            2          {'Unknown'}
                            3          {'Desktop'}
                            4          {'Low Profile Desktop'}
                            5          {'Pizza Box'}
                            6          {'Mini Tower'}
                            7          {'Tower'}
                            8          {'Portable'}
                            9          {'Laptop'}
                            10         {'Notebook'}
                            11         {'Hand Held'}
                            12         {'Docking Station'}
                            13         {'All in One'}
                            14         {'Sub Notebook'}
                            15         {'Space-Saving'}
                            16         {'Lunch Box'}
                            17         {'Main System Chassis'}
                            18         {'Expansion Chassis'}
                            19         {'SubChassis'}
                            20         {'Bus Expansion Chassis'}
                            21         {'Peripheral Chassis'}
                            22         {'Storage Chassis'}
                            23         {'Rack Mount Chassis'}
                            24         {'Sealed-Case PC'}
                            default    {"$value"}
                        }

                    }
                    $result
                }
            }

            $temp.ChassisType = (Get-CimInstance -ClassName Win32_SystemEnclosure -ComputerName $ComputerName | Select-Object -Property $ChassisTypes).ChassisType

            #Function to get last logged user on remote computer
            try {
                $t = Get-CimInstance win32_loggedonuser -ComputerName $ComputerName -ErrorAction Stop | Select Antecedent -Unique

                $temp.LastUser = "{0}\{1}" -f $t.Antecedent.Domain, $t.Antecedent.Name
            } catch {
                $temp.ErrorLog += $_
            }

            #Processor
            $temp.Processor = (Get-CimInstance win32_processor -ComputerName $ComputerName -filter "deviceid='CPU0'").Name

            #Disk
            $temp.Disk = ((Get-CimInstance Win32_LogicalDisk -ComputerName $ComputerName | Select-Object @{Name="Size"; Expression={"$([math]::round($_.Size / 1GB,2))GB"}}).Size) -join ', '

            #Ram Memory
            $temp.Ram = ((Get-CimInstance Win32_PhysicalMemory -ComputerName $ComputerName | Select-Object @{Name="Capacity"; Expression={"$([math]::round($_.Capacity / 1GB,2))GB"}}).Capacity) -join ', '

            #Serial Number
            $temp.SerialNumber = Get-CimInstance win32_bios -ComputerName $ComputerName | Select-Object -ExpandProperty SerialNumber

            #Manufacturer
            $temp.Manufacturer = Get-CimInstance win32_ComputerSystemProduct -ComputerName $ComputerName | Select-Object -ExpandProperty Vendor

            #Model
            $temp.Model = Get-CimInstance win32_ComputerSystemProduct -ComputerName $ComputerName | Select-Object -ExpandProperty Name

            $temp
        }
    }

    ## Output to console
    Generate-ComputerHwReport -ComputerNames localhost, pc2

    ## Output to console reading in the computer names from a file
    Generate-ComputerHwReport -ComputerNames (gc listofcomputernames.txt)

    ## Output to CSV reading in the computer names from a file
    Generate-ComputerHwReport -ComputerNames (gc listofcomputernames.txt) | Export-Csv -NoTypeInformation ComputerHwReport.csv