问:
Why all permissions checks?
I am new in django and drf

in my project I have two group of permissions

1.normal_user group : with view_issue,view_project,view_analyzeissue

2.manager_user : with all permission as possible

i have some views that check some permissions

for example IssuesViewApi view, this view need to NormalUserPermissions

so i created new group with  composition of permissions in my tests and send request to the view

my new group have view_issue,change_issue

when i send request to the IssuesViewApi i get 403 response

i have a NormalUserPermissions class

```<code>
class NormalUserPermissions(permissions.BasePermission):
    def has_permission(self, request: Request, view):
        if request.user.has_perms(get_group_permissions("normal_user")):
            return True
        return False
</code>```
```<code>class IssuesViewApi(generics.ListAPIView):
    class IssueFilter(FilterSet):
        labels = CharFilter(field_name="labels", lookup_expr='contains')
        project_id = NumberFilter(field_name="project__id", lookup_expr='exact')
        user_name = CharFilter(field_name="users__username", lookup_expr='exact')
        start_date = DateFilter(field_name="updated_at", lookup_expr='gte')
        end_date = DateFilter(field_name="updated_at", lookup_expr='lte')

        class Meta:
            model = Issue
            fields = ["iid", 'is_analyzed', 'project_id', 'labels', 'user_name', 'start_date', 'end_date']

    permission_classes = [IsAuthenticated, NormalUserPermissions]
    http_method_names = ['get']
    pagination_class = StandardPagination
    queryset = Issue.objects.all()
    serializer_class = IssueSerialize
    filter_backends = [OrderingFilter, DjangoFilterBackend]
    filterset_class = IssueFilter
    ordering_fields = ['iid', 'weight']  # order fields depend on user request
    ordering = ['iid']  # default order value

    def get(self, request, *args, **kwargs):
        response = super(IssuesViewApi, self).get(request, *args, **kwargs)
        return Response({
            'data': {
                'issues': response.data['results'],
            },
            'paginationInfo': {
                "count": response.data['count'],
                "next_page": response.data['next'],
                "previous_page": response.data['previous'],
                "total_pages": self.paginator.page.paginator.num_pages
            }
        })
</code>```
```<code>    def test_create_custom_group_and_filter_issues_and_update_issue(self):
        self.run_fake_discovery()
        user = self.get_user()
        user.groups.add(Group.objects.get_by_natural_key("manager_user"))
        self.login(username=user.username, password="123456789")
        add_group_url = reverse('group-add')
        group_name = "new_group"
        group_permissions = list(Permission.objects.filter(codename__in=['view_issue', 'change_issue']).all().values_list('id', flat=True))
        response = self.client.post(add_group_url, data=json.dumps({'name': group_name, 'permissions': group_permissions}), content_type=self.CONTENT_TYPE)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertTrue(Group.objects.filter(name=group_name).exists())
        sync_user_groups_url = reverse('sync-users-and-groups')
        test_user = User.objects.get(username='testuser')
        response = self.client.post(sync_user_groups_url, data=json.dumps({'group_name': group_name, 'users': [test_user.id]}), content_type=self.CONTENT_TYPE)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertTrue(test_user.groups.filter(name=group_name).exists())
        response=self.logout()
        self.assertEqual(response.status_code,status.HTTP_200_OK)
        self.login(username=test_user.username, password='123456789')
        filter_issue_url = reverse('issue-filter')
        filter_issue_response = self.client.get(filter_issue_url, data={'username': user.username}, content_type=self.CONTENT_TYPE)
        self.assertEqual(filter_issue_response.status_code, status.HTTP_200_OK)
</code>```

Why all permissions checks ?

Im going to when user has view_issue permission then get response with 200 status

Title: Why all permissions checks?

Body:
I am new in django and drf

in my project I have two group of permissions

1.normal_user group : with view_issue,view_project,view_analyzeissue

2.manager_user : with all permission as possible

i have some views that check some permissions

for example IssuesViewApi view, this view need to NormalUserPermissions

so i created new group with  composition of permissions in my tests and send request to the view

my new group have view_issue,change_issue

when i send request to the IssuesViewApi i get 403 response

i have a NormalUserPermissions class

class NormalUserPermissions(permissions.BasePermission):
    def has_permission(self, request: Request, view):
        if request.user.has_perms(get_group_permissions("normal_user")):
            return True
        return False

class IssuesViewApi(generics.ListAPIView):
    class IssueFilter(FilterSet):
        labels = CharFilter(field_name="labels", lookup_expr='contains')
        project_id = NumberFilter(field_name="project__id", lookup_expr='exact')
        user_name = CharFilter(field_name="users__username", lookup_expr='exact')
        start_date = DateFilter(field_name="updated_at", lookup_expr='gte')
        end_date = DateFilter(field_name="updated_at", lookup_expr='lte')

        class Meta:
            model = Issue
            fields = ["iid", 'is_analyzed', 'project_id', 'labels', 'user_name', 'start_date', 'end_date']

    permission_classes = [IsAuthenticated, NormalUserPermissions]
    http_method_names = ['get']
    pagination_class = StandardPagination
    queryset = Issue.objects.all()
    serializer_class = IssueSerialize
    filter_backends = [OrderingFilter, DjangoFilterBackend]
    filterset_class = IssueFilter
    ordering_fields = ['iid', 'weight']  # order fields depend on user request
    ordering = ['iid']  # default order value

    def get(self, request, *args, **kwargs):
        response = super(IssuesViewApi, self).get(request, *args, **kwargs)
        return Response({
            'data': {
                'issues': response.data['results'],
            },
            'paginationInfo': {
                "count": response.data['count'],
                "next_page": response.data['next'],
                "previous_page": response.data['previous'],
                "total_pages": self.paginator.page.paginator.num_pages
            }
        })

    def test_create_custom_group_and_filter_issues_and_update_issue(self):
        self.run_fake_discovery()
        user = self.get_user()
        user.groups.add(Group.objects.get_by_natural_key("manager_user"))
        self.login(username=user.username, password="123456789")
        add_group_url = reverse('group-add')
        group_name = "new_group"
        group_permissions = list(Permission.objects.filter(codename__in=['view_issue', 'change_issue']).all().values_list('id', flat=True))
        response = self.client.post(add_group_url, data=json.dumps({'name': group_name, 'permissions': group_permissions}), content_type=self.CONTENT_TYPE)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertTrue(Group.objects.filter(name=group_name).exists())
        sync_user_groups_url = reverse('sync-users-and-groups')
        test_user = User.objects.get(username='testuser')
        response = self.client.post(sync_user_groups_url, data=json.dumps({'group_name': group_name, 'users': [test_user.id]}), content_type=self.CONTENT_TYPE)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertTrue(test_user.groups.filter(name=group_name).exists())
        response=self.logout()
        self.assertEqual(response.status_code,status.HTTP_200_OK)
        self.login(username=test_user.username, password='123456789')
        filter_issue_url = reverse('issue-filter')
        filter_issue_response = self.client.get(filter_issue_url, data={'username': user.username}, content_type=self.CONTENT_TYPE)
        self.assertEqual(filter_issue_response.status_code, status.HTTP_200_OK)

Why all permissions checks ?

Im going to when user has view_issue permission then get response with 200 status


来源: stackexchange

问:
Elastic- While developing "notcontains" handlebars is not working
I am new to elastic connector development and using reference in link. I am trying to create  agent/stream/aws-s3.yml.hbs file, which will check if user has entered(while doing Add integration) valid SQS queue_url IF YES then run for SQS queue data ELSE consider it as S3 bucket ARN/name and hit S3.

Please find agent/stream/aws-s3.yml.hbs file as below:

```<code>{{#contains "sqs" s3_sqs_endpoint}}
queue_url: {{s3_sqs_endpoint}}
{{#if visibility_timeout}}
visibility_timeout: {{visibility_timeout}}
{{/if}}
{{#if api_timeout}}
api_timeout: {{api_timeout}}
{{/if}}
{{#if max_number_of_messages}}
max_number_of_messages: {{max_number_of_messages}}
{{/if}}
{{#if file_selectors}}
file_selectors:
{{file_selectors}}
{{/if}}
{{/contains}}
{{#notcontains "sqs" s3_sqs_endpoint}}
bucket_arn: {{s3_sqs_endpoint}}
{{#if number_of_workers}}
number_of_workers: {{number_of_workers}}
{{/if}}
{{#if interval}}
bucket_list_interval: {{interval}}
{{/if}}
{{#if bucket_list_prefix}}
bucket_list_prefix: {{bucket_list_prefix}}
{{/if}}
{{/contains}}
{{#if access_key_id}}
access_key_id: {{access_key_id}}
{{/if}}
{{#if secret_access_key}}
secret_access_key: {{secret_access_key}}
{{/if}}
{{#if session_token}}
session_token: {{session_token}}
{{/if}}
{{#if shared_credential_file}}
shared_credential_file: {{shared_credential_file}}
{{/if}}
{{#if credential_profile_name}}
credential_profile_name: {{credential_profile_name}}
{{/if}}
{{#if role_arn}}
role_arn: {{role_arn}}
{{/if}}
{{#if fips_enabled}}
fips_enabled: {{fips_enabled}}
{{/if}}
{{#if proxy_url}}
proxy_url: {{proxy_url}}
{{/if}}
tags:
{{#if preserve_original_event}}
  - preserve_original_event
{{/if}}
{{#if preserve_duplicate_custom_fields}}
  - preserve_duplicate_custom_fields
{{/if}}
{{#each tags as |tag|}}
  - {{tag}}
{{/each}}
{{#contains "forwarded" tags}}
publisher_pipeline.disable_host: true
{{/contains}}
{{#if processors}}
processors:
{{processors}}
{{/if}}
</code>```

It's working fine for SQS as we have to mandatorily provide queue url as an input, but when I want to check for S3 bucket name it will go fail with error as below:

```<code>notcontains doesn't match contains - 17:3
</code>```

I am aware that it's because elastic is not able to identify

#notcontains

handlebars.

What could be other possible way to work around this. I don't want to use any toggle at UI side to check what user has mentioned in text field.

ContentLicense: CC BY-SA 4.0

Body:
I am new to elastic connector development and using reference in link. I am trying to create  agent/stream/aws-s3.yml.hbs file, which will check if user has entered(while doing Add integration) valid SQS queue_url IF YES then run for SQS queue data ELSE consider it as S3 bucket ARN/name and hit S3.

Please find agent/stream/aws-s3.yml.hbs file as below:

{{#contains "sqs" s3_sqs_endpoint}}
queue_url: {{s3_sqs_endpoint}}
{{#if visibility_timeout}}
visibility_timeout: {{visibility_timeout}}
{{/if}}
{{#if api_timeout}}
api_timeout: {{api_timeout}}
{{/if}}
{{#if max_number_of_messages}}
max_number_of_messages: {{max_number_of_messages}}
{{/if}}
{{#if file_selectors}}
file_selectors:
{{file_selectors}}
{{/if}}
{{/contains}}
{{#notcontains "sqs" s3_sqs_endpoint}}
bucket_arn: {{s3_sqs_endpoint}}
{{#if number_of_workers}}
number_of_workers: {{number_of_workers}}
{{/if}}
{{#if interval}}
bucket_list_interval: {{interval}}
{{/if}}
{{#if bucket_list_prefix}}
bucket_list_prefix: {{bucket_list_prefix}}
{{/if}}
{{/contains}}
{{#if access_key_id}}
access_key_id: {{access_key_id}}
{{/if}}
{{#if secret_access_key}}
secret_access_key: {{secret_access_key}}
{{/if}}
{{#if session_token}}
session_token: {{session_token}}
{{/if}}
{{#if shared_credential_file}}
shared_credential_file: {{shared_credential_file}}
{{/if}}
{{#if credential_profile_name}}
credential_profile_name: {{credential_profile_name}}
{{/if}}
{{#if role_arn}}
role_arn: {{role_arn}}
{{/if}}
{{#if fips_enabled}}
fips_enabled: {{fips_enabled}}
{{/if}}
{{#if proxy_url}}
proxy_url: {{proxy_url}}
{{/if}}
tags:
{{#if preserve_original_event}}
  - preserve_original_event
{{/if}}
{{#if preserve_duplicate_custom_fields}}
  - preserve_duplicate_custom_fields
{{/if}}
{{#each tags as |tag|}}
  - {{tag}}
{{/each}}
{{#contains "forwarded" tags}}
publisher_pipeline.disable_host: true
{{/contains}}
{{#if processors}}
processors:
{{processors}}
{{/if}}

It's working fine for SQS as we have to mandatorily provide queue url as an input, but when I want to check for S3 bucket name it will go fail with error as below:

notcontains doesn't match contains - 17:3

I am aware that it's because elastic is not able to identify

#notcontains

handlebars.

What could be other possible way to work around this. I don't want to use any toggle at UI side to check what user has mentioned in text field.


问:
Forbidden for Azure Storage Table with managed identity contributor access to Storage Account through Azure Powershell Function
I am creating an Azure Powershell Function and am trying to access Tables in a Storage Account for which I have given contributor access to the Azure Function managed Identity.

I am able to get the storage account using Get-AzStorageAccount and thus get the Context. However, all access to tables gives me forbidden error. I am not able to create tables either. I have tried using Get-AzStorageTable, Get-AzTableTable but no success.

```<code>    2022-12-20T12:52:04Z   [Error]   ERROR: Forbidden

Exception             :
    Type               : Microsoft.Azure.Cosmos.Table.StorageException
    RequestInformation : Microsoft.Azure.Cosmos.Table.RequestResult
    TargetSite         :
        Name          : CreateTableIfNotExists
        DeclaringType : Microsoft.WindowsAzure.Commands.Storage.Model.Contract.StorageTableManagement
        MemberType    : Method
        Module        : Microsoft.Azure.PowerShell.Cmdlets.Storage.dll
    Message            : Forbidden
    Source             : Microsoft.Azure.PowerShell.Cmdlets.Storage
    HResult            : -2146233088
</code>```

I am also having issues adding Powershell modules using the requirements.psd1 file. I am usually getting a 503 error.

Please help.

Edit 1
I tried this with SAS token as well but this did not work.

Edit 2
I am adding the code with the Mananged Identity

```<code>$storageAccount = Get-AzStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccountName
$storageCtx = $storageAccount.Context
Write-Host $storageCtx.Name
New-AzStorageTable -Name 'TestTable' -Context $storageCtx
</code>```

The storage context name is correctly displayed but the next line to create the table fails.

Body:
I am creating an Azure Powershell Function and am trying to access Tables in a Storage Account for which I have given contributor access to the Azure Function managed Identity.

I am able to get the storage account using Get-AzStorageAccount and thus get the Context. However, all access to tables gives me forbidden error. I am not able to create tables either. I have tried using Get-AzStorageTable, Get-AzTableTable but no success.

    2022-12-20T12:52:04Z   [Error]   ERROR: Forbidden

Exception             :
    Type               : Microsoft.Azure.Cosmos.Table.StorageException
    RequestInformation : Microsoft.Azure.Cosmos.Table.RequestResult
    TargetSite         :
        Name          : CreateTableIfNotExists
        DeclaringType : Microsoft.WindowsAzure.Commands.Storage.Model.Contract.StorageTableManagement
        MemberType    : Method
        Module        : Microsoft.Azure.PowerShell.Cmdlets.Storage.dll
    Message            : Forbidden
    Source             : Microsoft.Azure.PowerShell.Cmdlets.Storage
    HResult            : -2146233088

I am also having issues adding Powershell modules using the requirements.psd1 file. I am usually getting a 503 error.

Please help.

Edit 1
I tried this with SAS token as well but this did not work.

Edit 2
I am adding the code with the Mananged Identity

$storageAccount = Get-AzStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccountName
$storageCtx = $storageAccount.Context
Write-Host $storageCtx.Name
New-AzStorageTable -Name 'TestTable' -Context $storageCtx

The storage context name is correctly displayed but the next line to create the table fails.


问:
When try to get access to Active Directory a few times I'm blocked
I work in a company and in one of the projects(Nodejs as backend), I need to get the details of userNT.
I try to get access to Active Directory and the action is successful, but after a few times the request is made, the access was blocked for a 1 hour +- and I get this error :

"errno":-4039,"code":"ETIMEDOUT","syscall":"connect","address":"192.*..**","port":389


问:
Delay in Microsoft.Office.Interop.Word.Application object creation
I've one windows forms application developed in VB.NET which is using Microsoft.Office.Interop.Word.Application to read a doc file.

But the application is slow and on debugging its found that delay is with this line
Dim obj As Word.Application = New Word.Application

Could you please tell me is there any fix without code change.


问:
tzset() from time.h sets tzname[0] as CET for TZ=Europe/Lisbon
I/m using glibc 2.31, the standard time for Europe/Lisbon is WET. In a C program where I'm trying to change the timezone to Europe/Lisbon. First I'm setting the env variable TZ="Europe/Lisbon" then I call tzset() function. When I print tzname[0] extern variable it prints CET instead of WET.

Please can someone help me solve this issue?

I tried the same in python time library there I get WET when I print time.tzname[0].
Also when I change timezone with timedatectl set-timezone Europe/Lisbon, in timedatectl status I get WET.

Only in the C program where I'm using time.h I get CET in tzname[0] instead of WET.


问:
Node.js Sqlite serialize function do not serialize the db function calls inside it
I have inside a db.serialize function (node-sqlite3 package) this definition:

```<code>  db.serialize(() => {
    db.exec("begin");

    // Some prepare statements here

    // Some local functions here
    function errorFunc(err) {
      if (err) insertError = err;
    }
    // and finally the problematic code:

    db.run(deleteImgs,[id],errorFunc); //this delete rows from "images" table
    db.run(updateImg,[currentsize,id],errorFunc); // this update another table.

    //  I run this prepared statement that insert some rows into a table.
    for (const o of toProcess) stImage.run([o.id],errorFunc);

    // This query retrieves all previous insertions in the previous loop, but finds nothing: no rows.
    // It seems queries have been run in parallel instead of sequentially
    db.all(allImg,[id],processCalc);
   )};
</code>```

To solve this problem I had to move the "for loop" and the db.all call into a callback inside the db.run(updateImg... call, to ensure to be executed after the deletion of rows and find the inserted rows in the "for loop".

Any idea why the execution is not sequential??

Body:
I have inside a db.serialize function (node-sqlite3 package) this definition:

  db.serialize(() => {
    db.exec("begin");

    // Some prepare statements here

    // Some local functions here
    function errorFunc(err) {
      if (err) insertError = err;
    }
    // and finally the problematic code:

    db.run(deleteImgs,[id],errorFunc); //this delete rows from "images" table
    db.run(updateImg,[currentsize,id],errorFunc); // this update another table.

    //  I run this prepared statement that insert some rows into a table.
    for (const o of toProcess) stImage.run([o.id],errorFunc);

    // This query retrieves all previous insertions in the previous loop, but finds nothing: no rows.
    // It seems queries have been run in parallel instead of sequentially
    db.all(allImg,[id],processCalc);
   )};

To solve this problem I had to move the "for loop" and the db.all call into a callback inside the db.run(updateImg... call, to ensure to be executed after the deletion of rows and find the inserted rows in the "for loop".

Any idea why the execution is not sequential??


问:
Make .py file wait for files in directory and make function work if is more then 0
i wrote a function that filters out all files in a certain directory by the first digit to make my work easier. How can i leave the code in standby mode until files appear in the data folder, and after executive the code will return to standby mode?

I tried to make it with while and time.sleep, also tried make it with apscheduler but i failed(


问:
Angular Universal not running any functions after Refresh
This is my server.ts
I want to implement universal only in signin page.
Everything (Universal and all functionalitites) is working fine unless I refresh signin page.
Then page becomes pure static, even 'view password' functionality is also not working, any JavaScript is not executed at all.
Can someone please suggest me something, I would be highly grateful.

```<code>
export function app(): express.Express {
  const server = express();
  const distFolder = join(process.cwd(), 'dist/cpaVaultUI/browser');
  const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';
  server.engine('html', ngExpressEngine({
    bootstrap: AppServerModule,
  }));

  server.set('view engine', 'html');
  server.set('views', distFolder);

  server.get('*.*', express.static(distFolder, {
    maxAge: '1y'
  }));

  // All regular routes use the Universal engine
  server.get('/auth/signin', (req, res) => {
    res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
  });

  server.get('*', (req, res) => {
    res.sendFile(distFolder+'/index.html');
  });
  return server;
}

function run(): void {
  const port = process.env.PORT || 4000;
  const server = app();
  server.listen(port, () => {
    console.log(`Node Express server listening on http://localhost:${port}`);
  });
}

declare const __non_webpack_require__: NodeRequire;
const mainModule = __non_webpack_require__.main;
const moduleFilename = mainModule && mainModule.filename || '';
if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
  run();
}

export * from './src/main.server';

</code>```

Edit

I found out that when I implement Universal in whole application, then from start only no java script is executing.
In short from start only client side is not able to takeover.

Please help!

Body:
This is my server.ts
I want to implement universal only in signin page.
Everything (Universal and all functionalitites) is working fine unless I refresh signin page.
Then page becomes pure static, even 'view password' functionality is also not working, any JavaScript is not executed at all.
Can someone please suggest me something, I would be highly grateful.

export function app(): express.Express {
  const server = express();
  const distFolder = join(process.cwd(), 'dist/cpaVaultUI/browser');
  const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';
  server.engine('html', ngExpressEngine({
    bootstrap: AppServerModule,
  }));

  server.set('view engine', 'html');
  server.set('views', distFolder);

  server.get('*.*', express.static(distFolder, {
    maxAge: '1y'
  }));

  // All regular routes use the Universal engine
  server.get('/auth/signin', (req, res) => {
    res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
  });

  server.get('*', (req, res) => {
    res.sendFile(distFolder+'/index.html');
  });
  return server;
}

function run(): void {
  const port = process.env.PORT || 4000;
  const server = app();
  server.listen(port, () => {
    console.log(`Node Express server listening on http://localhost:${port}`);
  });
}

declare const __non_webpack_require__: NodeRequire;
const mainModule = __non_webpack_require__.main;
const moduleFilename = mainModule && mainModule.filename || '';
if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
  run();
}

export * from './src/main.server';

Edit

I found out that when I implement Universal in whole application, then from start only no java script is executing.
In short from start only client side is not able to takeover.

Please help!


问:
Connecting singnalR through Ocelot gateway in .Net 6
I am trying to connect my signalR to my frontend app through Ocelot gateway but failing to achieve it. The rest of the endpoints are completely accessible through the gateway but when I am trying to connect the signalR through gateway it throws localhost is currently unable to handle this request error.

My Ocelot configuration for signalR hub is

```<code>{
  "DownstreamPathTemplate": "/{everything}",
  "DownstreamScheme": "ws",
  "DownstreamHostAndPorts": [
    {
      "Host": "localhost",
      "Port": 5001
    }
  ],
  "UpstreamPathTemplate": "/{everything}",
  "UpstreamHttpMethod": [ "GET", "POST", "PUT", "DELETE", "OPTIONS" ]
}
</code>```

here is how I register the Ocelot in the program.cs

```<code>builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);
builder.Services.AddOcelot(builder.Configuration);

app.UseWebSockets();
app.UseOcelot();
</code>```

here is my signalR hub endpoint

```<code>app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        endpoints.MapHub<NotificationHub>("/notifications");
    });
</code>```

I just followed the ocelot documentation but could not make it work until now.

here is error ss,

Body:
I am trying to connect my signalR to my frontend app through Ocelot gateway but failing to achieve it. The rest of the endpoints are completely accessible through the gateway but when I am trying to connect the signalR through gateway it throws localhost is currently unable to handle this request error.

My Ocelot configuration for signalR hub is

{
  "DownstreamPathTemplate": "/{everything}",
  "DownstreamScheme": "ws",
  "DownstreamHostAndPorts": [
    {
      "Host": "localhost",
      "Port": 5001
    }
  ],
  "UpstreamPathTemplate": "/{everything}",
  "UpstreamHttpMethod": [ "GET", "POST", "PUT", "DELETE", "OPTIONS" ]
}

here is how I register the Ocelot in the program.cs

builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);
builder.Services.AddOcelot(builder.Configuration);

app.UseWebSockets();
app.UseOcelot();

here is my signalR hub endpoint

app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        endpoints.MapHub<NotificationHub>("/notifications");
    });

I just followed the ocelot documentation but could not make it work until now.

here is error ss,


问:
How to solve the "RR_HTTP_HEADERS_SENT" error when using res.redirect?
I am following a todolist website tutorial and am stuck on this. Here's the full code:

```<code>//jshint esversion:6

// Database Code
const mongoose = require("mongoose")

main().catch(err => console.log(err));

async function main() {
  mongoose.set('strictQuery', false);
  await mongoose.connect('mongodb://0.0.0.0:27017/todolistDB');
}

// For the main list
const itemSchema = {
  itemName: {
    type: String,
    required: true
  }
}

const Item = mongoose.model("Item", itemSchema)

const buyFood = new Item({
  itemName: "Buy Food"
})

const cookFood = new Item({
  itemName: "Cook Food"
})

const eatFood = new Item({
  itemName: "Eat Food"
})

const defaultItems = [buyFood, cookFood, eatFood]

// For the custom listTitle
const listSchema = {
  listName: String,
  items: [itemSchema]
}

const List = mongoose.model("list", listSchema)

function makeNewList(name) {
  list = new List({
    listName: name,
    items: defaultItems
  })

  list.save()
}

// Server Code
const express = require("express");
const bodyParser = require("body-parser");
const date = require(__dirname + "/date.js");
const _ = require("lodash")

const app = express();

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));

const workItems = [];

app.get("/", function(req, res) {

  const day = date.getDate();

  Item.find(function(err, item) {

    if (item.length === 0) {
      Item.insertMany(defaultItems, function(err) {
        if (err) {
          console.log(err);
        } else {
          console.log("Items added successfully.");
        }
      })
    }

    else if (err) {
      console.log(err);
    }

    else {
      res.render("list", {listTitle: day, newListItems: item});
    }
  })
});

app.post("/", function(req, res){

  const item = req.body.newItem;

  const newItem = new Item ({
    itemName: item
  })

  newItem.save()
  });

app.post("/delete", function(req, res) {
  deletedItem = String(req.body.box)

  Item.deleteOne({_id: deletedItem}, function(err) {
    if (err) {
      console.log(err);
    } else {
      console.log("Item deleted successfully");
    }
  })

  res.redirect("/")
})

app.get("/:listName", function(req, res) {
  newList = req.params.listName.toLowerCase()

  List.findOne({listName: newList}, function(err, list) {

    if (!err) {
      if (list) {
        console.log(newList + " exist");

        res.render("list", {listTitle: list.listName, newListItems: list.items});
        }

      else {
        console.log(newList + " not exist")}

        makeNewList(newList)
        res.redirect('/' + list)
}})})

app.get("/about", function(req, res){
  res.render("about");
});

app.listen(2000, function() {
  console.log("Server started on port 2000");
});

</code>```

I downloaded the full code solution for this project and analyzed it but still can't find anything to solve this issue. Here's the solution code:

```<code>//jshint esversion:6

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const _ = require("lodash");

const app = express();

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));

main().catch(err => console.log(err));

async function main() {
  mongoose.set('strictQuery', false);
  await mongoose.connect('mongodb://0.0.0.0:27017/todolistDB');
}

const itemsSchema = {
  name: String
};

const Item = mongoose.model("Item", itemsSchema);

const item1 = new Item({
  name: "Welcome to your todolist!"
});

const item2 = new Item({
  name: "Hit the + button to add a new item."
});

const item3 = new Item({
  name: "<-- Hit this to delete an item."
});

const defaultItems = [item1, item2, item3];

const listSchema = {
  name: String,
  items: [itemsSchema]
};

const List = mongoose.model("List", listSchema);

app.get("/", function(req, res) {

  Item.find({}, function(err, foundItems){

    if (foundItems.length === 0) {
      Item.insertMany(defaultItems, function(err){
        if (err) {
          console.log(err);
        } else {
          console.log("Successfully savevd default items to DB.");
        }
      });
      res.redirect("/");
    } else {
      res.render("list", {listTitle: "Today", newListItems: foundItems});
    }
  });

});

app.get("/:customListName", function(req, res){
  const customListName = _.capitalize(req.params.customListName);

  List.findOne({name: customListName}, function(err, foundList){
    if (!err){
      if (!foundList){
        //Create a new list
        const list = new List({
          name: customListName,
          items: defaultItems
        });
        list.save();
        res.redirect("/" + customListName);
      } else {
        //Show an existing list

        res.render("list", {listTitle: foundList.name, newListItems: foundList.items});
      }
    }
  });

});

app.post("/", function(req, res){

  const itemName = req.body.newItem;
  const listName = req.body.list;

  const item = new Item({
    name: itemName
  });

  if (listName === "Today"){
    item.save();
    res.redirect("/");
  } else {
    List.findOne({name: listName}, function(err, foundList){
      foundList.items.push(item);
      foundList.save();
      res.redirect("/" + listName);
    });
  }
});

app.post("/delete", function(req, res){
  const checkedItemId = req.body.checkbox;
  const listName = req.body.listName;

  if (listName === "Today") {
    Item.findByIdAndRemove(checkedItemId, function(err){
      if (!err) {
        console.log("Successfully deleted checked item.");
        res.redirect("/");
      }
    });
  } else {
    List.findOneAndUpdate({name: listName}, {$pull: {items: {_id: checkedItemId}}}, function(err, foundList){
      if (!err){
        res.redirect("/" + listName);
      }
    });
  }

});

app.get("/about", function(req, res){
  res.render("about");
});

app.listen(3000, function() {
  console.log("Server started on port 3000");
});

</code>```

And there might be some differences in this compared to mine as this code utilized older versions of Mongoose and MongoDB.

UPDATE: I tried something and now it's a hit or a miss. Basically I replaced "list" inside res.redirect("/" + list) with
res.redirect("/" + newlist) and now it works when I open the website for the first time but when I try to do it the second time, I get the same error.

Body:
I am following a todolist website tutorial and am stuck on this. Here's the full code:

//jshint esversion:6

// Database Code
const mongoose = require("mongoose")

main().catch(err => console.log(err));

async function main() {
  mongoose.set('strictQuery', false);
  await mongoose.connect('mongodb://0.0.0.0:27017/todolistDB');
}

// For the main list
const itemSchema = {
  itemName: {
    type: String,
    required: true
  }
}

const Item = mongoose.model("Item", itemSchema)

const buyFood = new Item({
  itemName: "Buy Food"
})

const cookFood = new Item({
  itemName: "Cook Food"
})

const eatFood = new Item({
  itemName: "Eat Food"
})

const defaultItems = [buyFood, cookFood, eatFood]

// For the custom listTitle
const listSchema = {
  listName: String,
  items: [itemSchema]
}

const List = mongoose.model("list", listSchema)

function makeNewList(name) {
  list = new List({
    listName: name,
    items: defaultItems
  })

  list.save()
}

// Server Code
const express = require("express");
const bodyParser = require("body-parser");
const date = require(__dirname + "/date.js");
const _ = require("lodash")

const app = express();

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));

const workItems = [];

app.get("/", function(req, res) {

  const day = date.getDate();

  Item.find(function(err, item) {

    if (item.length === 0) {
      Item.insertMany(defaultItems, function(err) {
        if (err) {
          console.log(err);
        } else {
          console.log("Items added successfully.");
        }
      })
    }

    else if (err) {
      console.log(err);
    }

    else {
      res.render("list", {listTitle: day, newListItems: item});
    }
  })
});

app.post("/", function(req, res){

  const item = req.body.newItem;

  const newItem = new Item ({
    itemName: item
  })

  newItem.save()
  });

app.post("/delete", function(req, res) {
  deletedItem = String(req.body.box)

  Item.deleteOne({_id: deletedItem}, function(err) {
    if (err) {
      console.log(err);
    } else {
      console.log("Item deleted successfully");
    }
  })

  res.redirect("/")
})

app.get("/:listName", function(req, res) {
  newList = req.params.listName.toLowerCase()

  List.findOne({listName: newList}, function(err, list) {

    if (!err) {
      if (list) {
        console.log(newList + " exist");

        res.render("list", {listTitle: list.listName, newListItems: list.items});
        }

      else {
        console.log(newList + " not exist")}

        makeNewList(newList)
        res.redirect('/' + list)
}})})

app.get("/about", function(req, res){
  res.render("about");
});

app.listen(2000, function() {
  console.log("Server started on port 2000");
});

I downloaded the full code solution for this project and analyzed it but still can't find anything to solve this issue. Here's the solution code:

//jshint esversion:6

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const _ = require("lodash");

const app = express();

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));

main().catch(err => console.log(err));

async function main() {
  mongoose.set('strictQuery', false);
  await mongoose.connect('mongodb://0.0.0.0:27017/todolistDB');
}

const itemsSchema = {
  name: String
};

const Item = mongoose.model("Item", itemsSchema);

const item1 = new Item({
  name: "Welcome to your todolist!"
});

const item2 = new Item({
  name: "Hit the + button to add a new item."
});

const item3 = new Item({
  name: "<-- Hit this to delete an item."
});

const defaultItems = [item1, item2, item3];

const listSchema = {
  name: String,
  items: [itemsSchema]
};

const List = mongoose.model("List", listSchema);

app.get("/", function(req, res) {

  Item.find({}, function(err, foundItems){

    if (foundItems.length === 0) {
      Item.insertMany(defaultItems, function(err){
        if (err) {
          console.log(err);
        } else {
          console.log("Successfully savevd default items to DB.");
        }
      });
      res.redirect("/");
    } else {
      res.render("list", {listTitle: "Today", newListItems: foundItems});
    }
  });

});

app.get("/:customListName", function(req, res){
  const customListName = _.capitalize(req.params.customListName);

  List.findOne({name: customListName}, function(err, foundList){
    if (!err){
      if (!foundList){
        //Create a new list
        const list = new List({
          name: customListName,
          items: defaultItems
        });
        list.save();
        res.redirect("/" + customListName);
      } else {
        //Show an existing list

        res.render("list", {listTitle: foundList.name, newListItems: foundList.items});
      }
    }
  });

});

app.post("/", function(req, res){

  const itemName = req.body.newItem;
  const listName = req.body.list;

  const item = new Item({
    name: itemName
  });

  if (listName === "Today"){
    item.save();
    res.redirect("/");
  } else {
    List.findOne({name: listName}, function(err, foundList){
      foundList.items.push(item);
      foundList.save();
      res.redirect("/" + listName);
    });
  }
});

app.post("/delete", function(req, res){
  const checkedItemId = req.body.checkbox;
  const listName = req.body.listName;

  if (listName === "Today") {
    Item.findByIdAndRemove(checkedItemId, function(err){
      if (!err) {
        console.log("Successfully deleted checked item.");
        res.redirect("/");
      }
    });
  } else {
    List.findOneAndUpdate({name: listName}, {$pull: {items: {_id: checkedItemId}}}, function(err, foundList){
      if (!err){
        res.redirect("/" + listName);
      }
    });
  }

});

app.get("/about", function(req, res){
  res.render("about");
});

app.listen(3000, function() {
  console.log("Server started on port 3000");
});

And there might be some differences in this compared to mine as this code utilized older versions of Mongoose and MongoDB.

UPDATE: I tried something and now it's a hit or a miss. Basically I replaced "list" inside res.redirect("/" + list) with
res.redirect("/" + newlist) and now it works when I open the website for the first time but when I try to do it the second time, I get the same error.


问:
How to show relation table column name in laravel?
I have 2 tables "users" and "blogs".
The blogs table has a custom column named "created_by". I want to make a relation like while showing the list of blogs, I want to show the "name" column of the "users" table. I am getting error as "Trying to get property 'name' of non-object". Can anyone help?

Model(blog.php)

```<code><?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Blog extends Model
{
    use HasFactory;

    public function UserCreatedBy(){
        return $this->belongsTo(User::class, 'created_by');
    }
}
</code>```

Controller(Blogcontroller.php)

```<code>public function index(){

        $blogs = Blog::with('UserCreatedBy')->get();
        return view('blog.bloglist', ['bloglist'=>$blogs]);
    }
</code>```

View(bloglist.blade.php)

```<code>@foreach($bloglist as $list)
{{$list->UserCreatedBy->name}}
@endforeach
</code>```

Body:
I have 2 tables "users" and "blogs".
The blogs table has a custom column named "created_by". I want to make a relation like while showing the list of blogs, I want to show the "name" column of the "users" table. I am getting error as "Trying to get property 'name' of non-object". Can anyone help?

Model(blog.php)

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Blog extends Model
{
    use HasFactory;

    public function UserCreatedBy(){
        return $this->belongsTo(User::class, 'created_by');
    }
}

Controller(Blogcontroller.php)

public function index(){

        $blogs = Blog::with('UserCreatedBy')->get();
        return view('blog.bloglist', ['bloglist'=>$blogs]);
    }

View(bloglist.blade.php)

@foreach($bloglist as $list)
{{$list->UserCreatedBy->name}}
@endforeach


问:
Is there a way to force parallel run of a function in Postgresql?
i have a function write in Plpgsql that does some thing like:

```<code>CREATE OR REPLACE FUNCTION myfunc(rowid integer,mytable regclass,parama integer, paramb
integer)
RETURNS SETOF mytype
AS $$

BEGIN
    RETURN QUERY
    EXECUTE format('SELECT * FROM ' || mytable || 'WHERE foo = $1 and bar = $2' USING
parama, paramb;
END
$$ LANGUAGE plpgsql;
</code>```

I then have another function that insert the result of myfunc in a table (that have the same columns as mytype)

```<code>CREATE OR REPLACE FUNCTION myinsertfunc( mytable regclass,parama integer, paramb
integer,desttable regclass, rowid_min integer, row_id_max integer)
RETURNS void
AS $$
BEGIN
    FOR rowid  IN rowidmin..rowidmax LOOP
            BEGIN
                 EXECUTE format('INSERT INTO '|| desttable ||' SELECT * FROM
myfunc($1,$2, $3,$4,)')
                 USING rowid,mytable,parama, paramb;
            END;
    END LOOP;
END :
$$ LANGUAGE plpgsql;
</code>```

I have like thousand of thousand of insert to do so at this time i perfform like this :

```<code>open one session on my postgresql instance and run :
select myinsertfunc(tablea,parama,paramb,1,1000)

Open a second session on my postgresl instance and run
select myinsertfunc(tablea,parama,paramb,1001,2000)

Open a third session on my postgresl instance and run
select myinsertfunc(tabledest,tablea,parama,paramb,2001,3000)

And so on until i reach quite a bottleneck in term of CPU or I/O disk
</code>```

I wonder how i could force myinsertfunc to do the insert in parallel using max of the hardware/software capacity rather than just wait for the previous insert to being finish to start a new one (i know that i asked it with a loop so i just get what i asked for...).

Thanks for your help !

PS: The job done by myfunc is far more complex that in my example and has to be done per rowid so the solution can't be "don't use loop in SQL it's not why it is designed for"

Body:
i have a function write in Plpgsql that does some thing like:

CREATE OR REPLACE FUNCTION myfunc(rowid integer,mytable regclass,parama integer, paramb
integer)
RETURNS SETOF mytype
AS $$

BEGIN
    RETURN QUERY
    EXECUTE format('SELECT * FROM ' || mytable || 'WHERE foo = $1 and bar = $2' USING
parama, paramb;
END
$$ LANGUAGE plpgsql;

I then have another function that insert the result of myfunc in a table (that have the same columns as mytype)

CREATE OR REPLACE FUNCTION myinsertfunc( mytable regclass,parama integer, paramb
integer,desttable regclass, rowid_min integer, row_id_max integer)
RETURNS void
AS $$
BEGIN
    FOR rowid  IN rowidmin..rowidmax LOOP
            BEGIN
                 EXECUTE format('INSERT INTO '|| desttable ||' SELECT * FROM
myfunc($1,$2, $3,$4,)')
                 USING rowid,mytable,parama, paramb;
            END;
    END LOOP;
END :
$$ LANGUAGE plpgsql;

I have like thousand of thousand of insert to do so at this time i perfform like this :

open one session on my postgresql instance and run :
select myinsertfunc(tablea,parama,paramb,1,1000)

Open a second session on my postgresl instance and run
select myinsertfunc(tablea,parama,paramb,1001,2000)

Open a third session on my postgresl instance and run
select myinsertfunc(tabledest,tablea,parama,paramb,2001,3000)

And so on until i reach quite a bottleneck in term of CPU or I/O disk

I wonder how i could force myinsertfunc to do the insert in parallel using max of the hardware/software capacity rather than just wait for the previous insert to being finish to start a new one (i know that i asked it with a loop so i just get what i asked for...).

Thanks for your help !

PS: The job done by myfunc is far more complex that in my example and has to be done per rowid so the solution can't be "don't use loop in SQL it's not why it is designed for"


问:
Flask Web App with Windows Authentication
I have Flask app on IIS similiar to this tutorial : https://medium.com/@nerdijoe/how-to-deploy-flask-on-iis-with-windows-authentication-733839d657b7 but I'm using httpPlatformHandler instead of FastCGI.
With web.config as below I get None in  REMOTE_USER  :

```<code>request.environ.get('REMOTE_USER')
</code>```

web.config:

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <handlers>
            <add name="httpPlatformHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" requireAccess="Script" />
        </handlers>
        <httpPlatform stdoutLogEnabled="true" stdoutLogFile=".\python.log" startupTimeLimit="20" processPath="C:\python3\python.exe" arguments="-m flask run --port %HTTP_PLATFORM_PORT%">
        </httpPlatform>
        <httpErrors errorMode="DetailedLocalOnly" />
        <security>
            <authentication>
                <anonymousAuthentication enabled="false" />
                <windowsAuthentication enabled="true" />
            </authentication>
        </security>
    </system.webServer>
</configuration>
</code>```

How to get username of a user logged to a site using Flask on IIS?

Body:
I have Flask app on IIS similiar to this tutorial : https://medium.com/@nerdijoe/how-to-deploy-flask-on-iis-with-windows-authentication-733839d657b7 but I'm using httpPlatformHandler instead of FastCGI.
With web.config as below I get None in  REMOTE_USER  :

request.environ.get('REMOTE_USER')

web.config:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <handlers>
            <add name="httpPlatformHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" requireAccess="Script" />
        </handlers>
        <httpPlatform stdoutLogEnabled="true" stdoutLogFile=".\python.log" startupTimeLimit="20" processPath="C:\python3\python.exe" arguments="-m flask run --port %HTTP_PLATFORM_PORT%">
        </httpPlatform>
        <httpErrors errorMode="DetailedLocalOnly" />
        <security>
            <authentication>
                <anonymousAuthentication enabled="false" />
                <windowsAuthentication enabled="true" />
            </authentication>
        </security>
    </system.webServer>
</configuration>

How to get username of a user logged to a site using Flask on IIS?


问:
Typescript - is Rename symbol possible when "keyof" is used?
I'm trying the concept of using TypeScript with "AsciiDoc" as a DSL.

////
interface Login {
  "User name":  "OK" | "KO"
  "Password":   string
  "Sign In":    any
}
interface Agenda {
  "Message":    "Welcome" | "Invalid credentials"
}
////

AsciiDoc `

# AC: I can sign in with valid credentials

. given `<Login>`

. when I set ${ "User name" }, ${ "Password" } and apply ${ "Sign In" }

. then I expect `<Agenda>` and ${ "Message" }

`

CSV `

,===
`<[ L ["User name"] , L ["Password"] , A ["Message"]          ]>`
${[ "OK"            , "valid"        , "Welcome"              ]}
${[ "KO"            , "invalid"      , "Invalid credentials"  ]}
,===

`

////
type L = Login
type A = Agenda

declare function AsciiDoc ( _: _ ): typeof DSL
declare function DSL <Context> ( _: _, ...$: (keyof Context)[] ): typeof DSL
declare function CSV ( _: _ ) :(  ( _: _, ...rows: [...Header][] ) => string )

type _ = TemplateStringsArray
////
```

And here I am missing Rename symbol support in the "AsciiDoc" part - for${ "User name" } by example. I think, it is related to the keyof Context within declare function DSL ...

TS Playground

The question is - how can I achieve Rename support everywhere ?

Or how to change the concept to achieve maximum TypeScript TypeSafety, Autocomplete and Rename Symbol support ?

Or maybe you know similar DSL "tool" - already done ?

Regards.

Body:
I'm trying the concept of using TypeScript with "AsciiDoc" as a DSL.

////
interface Login {
  "User name":  "OK" | "KO"
  "Password":   string
  "Sign In":    any
}
interface Agenda {
  "Message":    "Welcome" | "Invalid credentials"
}
////

AsciiDoc `

# AC: I can sign in with valid credentials

. given `<Login>`

. when I set ${ "User name" }, ${ "Password" } and apply ${ "Sign In" }

. then I expect `<Agenda>` and ${ "Message" }

`

CSV `

,===
`<[ L ["User name"] , L ["Password"] , A ["Message"]          ]>`
${[ "OK"            , "valid"        , "Welcome"              ]}
${[ "KO"            , "invalid"      , "Invalid credentials"  ]}
,===

`

////
type L = Login
type A = Agenda

declare function AsciiDoc ( _: _ ): typeof DSL
declare function DSL <Context> ( _: _, ...$: (keyof Context)[] ): typeof DSL
declare function CSV ( _: _ ) :(  ( _: _, ...rows: [...Header][] ) => string )

type _ = TemplateStringsArray
////

And here I am missing Rename symbol support in the "AsciiDoc" part - for${ "User name" } by example. I think, it is related to the keyof Context within declare function DSL ...

TS Playground

The question is - how can I achieve Rename support everywhere ?

Or how to change the concept to achieve maximum TypeScript TypeSafety, Autocomplete and Rename Symbol support ?

Or maybe you know similar DSL "tool" - already done ?

Regards.


问:
How to get the latest module stream of a package using dnf command
I am trying to get the latest available module stream version of nginx package. with dnf module list nginx command, I see all the available versions which is [d]efault, [e]nabled, [x]disabled, [i]nstalled. I need to fetch only the latest stream and I did as below and worked. But I am not sure whether I am missing anything while doing grep nginx and taking the last line.

```<code>>> dnf module list nginx
Name                         Stream                          Profiles                          Summary
nginx                        1.14 [d]                        common [d]                        nginx webserver
nginx                        1.16                            common [d]                        nginx webserver
nginx                        1.18                            common [d]                        nginx webserver
nginx                        1.20                            common [d]                        nginx webserver

Hint: [d]efault, [e]nabled, [x]disabled, [i]nstalled

>> dnf module list nginx | grep nginx | awk 'END {print $2}'
1.20
</code>```

but is there any other way we can fetch the latest module version using dnf command options or any other better approach than the above one?

It would really helpful if someone helps me with this. Thanks in advance!

Body:
I am trying to get the latest available module stream version of nginx package. with dnf module list nginx command, I see all the available versions which is [d]efault, [e]nabled, [x]disabled, [i]nstalled. I need to fetch only the latest stream and I did as below and worked. But I am not sure whether I am missing anything while doing grep nginx and taking the last line.

>> dnf module list nginx
Name                         Stream                          Profiles                          Summary
nginx                        1.14 [d]                        common [d]                        nginx webserver
nginx                        1.16                            common [d]                        nginx webserver
nginx                        1.18                            common [d]                        nginx webserver
nginx                        1.20                            common [d]                        nginx webserver

Hint: [d]efault, [e]nabled, [x]disabled, [i]nstalled

>> dnf module list nginx | grep nginx | awk 'END {print $2}'
1.20

but is there any other way we can fetch the latest module version using dnf command options or any other better approach than the above one?

It would really helpful if someone helps me with this. Thanks in advance!


问:
trying to make a animation fully play out before a second animation starts upon a certain condition being met
So I've got a script attached to a trigger below a double door which open upon the character entering the trigger and closing when the character leaves the trigger. With my first iteration of the code, the animations would reset upon me leaving the trigger before the opening animation was finished. I attempted modifying the code so that the opening animation would finish before the closing animation started when I left the trigger. This left me with the following code.

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TriggerDoorController : MonoBehaviour
{
    [SerializeField] private Animator Door1;
    [SerializeField] private Animator Door2;

    private void OnTriggerEnter(Collider other) {
        if (other.CompareTag("Player")){
            if (!Door1.GetCurrentAnimatorStateInfo(0).IsName("DoorSlideOpen") && !Door1.GetCurrentAnimatorStateInfo(0).IsName("DoorSlideClose")) {
                Door1.Play("DoorSlideOpen", 0, 0.0f);
                Door2.Play("DoorSlideOpen2", 0, 0.0f);
            }
        }
    }
    private void OnTriggerExit(Collider other) {
        if (other.CompareTag("Player")){
            if (!Door1.GetCurrentAnimatorStateInfo(0).IsName("DoorSlideOpen") && !Door1.GetCurrentAnimatorStateInfo(0).IsName("DoorSlideClose")) {
                Door1.Play("DoorSlideClose", 0, 0.0f);
                Door2.Play("DoorSlideClose2", 0, 0.0f);
            }
        }
    }

}
</code>```

Now the door only opens when I enter the trigger, but doesn't close when I leave it. I tried searching online but can't really find much. Honestly, I don't really understand why it doesn't work. Could someone guide as to why it doesn't and to on how I could fix this? I'm also open to any other method if there's an easier one. Thanks.

Body:
So I've got a script attached to a trigger below a double door which open upon the character entering the trigger and closing when the character leaves the trigger. With my first iteration of the code, the animations would reset upon me leaving the trigger before the opening animation was finished. I attempted modifying the code so that the opening animation would finish before the closing animation started when I left the trigger. This left me with the following code.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TriggerDoorController : MonoBehaviour
{
    [SerializeField] private Animator Door1;
    [SerializeField] private Animator Door2;

    private void OnTriggerEnter(Collider other) {
        if (other.CompareTag("Player")){
            if (!Door1.GetCurrentAnimatorStateInfo(0).IsName("DoorSlideOpen") && !Door1.GetCurrentAnimatorStateInfo(0).IsName("DoorSlideClose")) {
                Door1.Play("DoorSlideOpen", 0, 0.0f);
                Door2.Play("DoorSlideOpen2", 0, 0.0f);
            }
        }
    }
    private void OnTriggerExit(Collider other) {
        if (other.CompareTag("Player")){
            if (!Door1.GetCurrentAnimatorStateInfo(0).IsName("DoorSlideOpen") && !Door1.GetCurrentAnimatorStateInfo(0).IsName("DoorSlideClose")) {
                Door1.Play("DoorSlideClose", 0, 0.0f);
                Door2.Play("DoorSlideClose2", 0, 0.0f);
            }
        }
    }

}

Now the door only opens when I enter the trigger, but doesn't close when I leave it. I tried searching online but can't really find much. Honestly, I don't really understand why it doesn't work. Could someone guide as to why it doesn't and to on how I could fix this? I'm also open to any other method if there's an easier one. Thanks.


问:
pyqt5 produces errors wsl2
I am trying to use Ubuntu under WSL 2 for work with imaging.  I see the following errors...

```<code>python3 pyqt5_test.py
qt.qpa.xcb: X server does not support XInput 2
failed to get the current screen resources
qt.qpa.xcb: QXcbConnection: XCB error: 1 (BadRequest), sequence: 165, resource id: 90, major code: 130 (Unknown), minor code: 47
qt.qpa.xcb: QXcbConnection: XCB error: 170 (Unknown), sequence: 180, resource id: 90, major code: 146 (Unknown), minor code: 20
</code>```

I send graphical output through Xming, am using this for WSL:

wsl -l -v
NAME            STATE           VERSION

Ubuntu-20.04    Running         2

and this Windows version:
Microsoft Windows [Version 10.0.19045.2364]

Tasks that produce this error (I presume they are using pyqt since they produce this error) can continue on successfully  (TexStudio for instance).  Other graphical tasks do not produce any error (xeyes, tkinter GUI) and successfully produce output on Xming.

Should I be worried?  If so, how do I get rid of these errors?

Thanks so much!

Title: pyqt5 produces errors wsl2

Body:
I am trying to use Ubuntu under WSL 2 for work with imaging.  I see the following errors...

python3 pyqt5_test.py
qt.qpa.xcb: X server does not support XInput 2
failed to get the current screen resources
qt.qpa.xcb: QXcbConnection: XCB error: 1 (BadRequest), sequence: 165, resource id: 90, major code: 130 (Unknown), minor code: 47
qt.qpa.xcb: QXcbConnection: XCB error: 170 (Unknown), sequence: 180, resource id: 90, major code: 146 (Unknown), minor code: 20

I send graphical output through Xming, am using this for WSL:

wsl -l -v
NAME            STATE           VERSION

Ubuntu-20.04    Running         2

and this Windows version:
Microsoft Windows [Version 10.0.19045.2364]

Tasks that produce this error (I presume they are using pyqt since they produce this error) can continue on successfully  (TexStudio for instance).  Other graphical tasks do not produce any error (xeyes, tkinter GUI) and successfully produce output on Xming.

Should I be worried?  If so, how do I get rid of these errors?

Thanks so much!


问:
Pyenv-installed Python creates virtualenv with empty include dir, no python-config in bin
Note: There are several similar questions, which I have seen and read. None of them are the precise problem I'm having, and none of their answers work for me.

I have installed several Python versions (Python 2.7, 3.8, 3.9, and 3.10) on my macOS Ventura system using Pyenv. The installed directories include a python-config file in /bin and an /include directory with many header files, so I do not need to install python-devel or similar:

```<code>$ ls -al /Users/williamsn/.pyenv/versions/3.10.9/bin/*-config
lrwxr-xr-x  1 williamsn  staff    17 Dec 19 17:24
/Users/williamsn/.pyenv/versions/3.10.9/bin/python-config -> python3.10-config
lrwxr-xr-x  1 williamsn  staff    17 Dec 19 17:24
/Users/williamsn/.pyenv/versions/3.10.9/bin/python3-config -> python3.10-config
-rwxr-xr-x  1 williamsn  staff  2073 Dec 19 17:24
/Users/williamsn/.pyenv/versions/3.10.9/bin/python3.10-config
$ ls -al /Users/williamsn/.pyenv/versions/3.10.9/include/python3.10/
total 1192
drwxr-xr-x  86 williamsn  staff   2752 Dec 19 17:24 .
drwxr-xr-x   3 williamsn  staff     96 Dec 19 17:24 ..
-rw-r--r--   1 williamsn  staff   3224 Dec 19 17:24 Python.h
...
-rw-r--r--   1 williamsn  staff   3026 Dec 19 17:24 import.h
...
-rw-r--r--   1 williamsn  staff  48878 Dec 19 17:24 pyconfig.h
...
-rw-r--r--   1 williamsn  staff   2863 Dec 19 17:24 weakrefobject.h
</code>```

As a best practice, I work exclusively in virtualenvs to keep the base Python installation clean and pristine. I create my virtualenvs using the venv module built in to Python 3:

```<code>$ python3.10 -m venv my_venv
</code>```

After doing so, there are two problems:

The my_venv/include directory is empty (does not contain the python3.10 directory or any of the header files from the parent Python and does not symlink to the parent Python)

There is no python-config / python3-config / python3.10-config in my_venv/bin.

So, for things requiring the Python headers:

If it tries to find the headers using python-config (which many projects do), it will fail.

If it tries to find the headers using the Python prefix and adding /include to it (which many projects do, notably Boost), it will fail.

If it tries to find the headers by importing sysconfig and calling sysconfig.get_paths(), it will succeed, albeit with paths outside the virtualenv.

Now, on a case-by-case basis, I can work around this, and already have. I can manually copy over python_config and then either export CPATH to add /Users/williamsn/.pyenv/versions/3.10.9/include/python3.10 or modify the virtualenv to symlink to /Users/williamsn/.pyenv/versions/3.10.9/include. These work, but they don't seem right to me. I can't make a global workaround anywhere (such as exporting CPATH in my Bash profile), because I'm working with multiple Python versions, and I'd end up with the wrong headers half the time. It seems to me like a virtualenv that has an empty include directory and is missing python-config when its parent has a full include directory and contains python-config is a broken virtualenv.

Is there an option I'm missing to include these pieces? Is this a bug I need to file against Python/venv?

Body:
Note: There are several similar questions, which I have seen and read. None of them are the precise problem I'm having, and none of their answers work for me.

I have installed several Python versions (Python 2.7, 3.8, 3.9, and 3.10) on my macOS Ventura system using Pyenv. The installed directories include a python-config file in /bin and an /include directory with many header files, so I do not need to install python-devel or similar:

$ ls -al /Users/williamsn/.pyenv/versions/3.10.9/bin/*-config
lrwxr-xr-x  1 williamsn  staff    17 Dec 19 17:24
/Users/williamsn/.pyenv/versions/3.10.9/bin/python-config -> python3.10-config
lrwxr-xr-x  1 williamsn  staff    17 Dec 19 17:24
/Users/williamsn/.pyenv/versions/3.10.9/bin/python3-config -> python3.10-config
-rwxr-xr-x  1 williamsn  staff  2073 Dec 19 17:24
/Users/williamsn/.pyenv/versions/3.10.9/bin/python3.10-config
$ ls -al /Users/williamsn/.pyenv/versions/3.10.9/include/python3.10/
total 1192
drwxr-xr-x  86 williamsn  staff   2752 Dec 19 17:24 .
drwxr-xr-x   3 williamsn  staff     96 Dec 19 17:24 ..
-rw-r--r--   1 williamsn  staff   3224 Dec 19 17:24 Python.h
...
-rw-r--r--   1 williamsn  staff   3026 Dec 19 17:24 import.h
...
-rw-r--r--   1 williamsn  staff  48878 Dec 19 17:24 pyconfig.h
...
-rw-r--r--   1 williamsn  staff   2863 Dec 19 17:24 weakrefobject.h

As a best practice, I work exclusively in virtualenvs to keep the base Python installation clean and pristine. I create my virtualenvs using the venv module built in to Python 3:

$ python3.10 -m venv my_venv

After doing so, there are two problems:

The my_venv/include directory is empty (does not contain the python3.10 directory or any of the header files from the parent Python and does not symlink to the parent Python)

There is no python-config / python3-config / python3.10-config in my_venv/bin.

So, for things requiring the Python headers:

If it tries to find the headers using python-config (which many projects do), it will fail.

If it tries to find the headers using the Python prefix and adding /include to it (which many projects do, notably Boost), it will fail.

If it tries to find the headers by importing sysconfig and calling sysconfig.get_paths(), it will succeed, albeit with paths outside the virtualenv.

Now, on a case-by-case basis, I can work around this, and already have. I can manually copy over python_config and then either export CPATH to add /Users/williamsn/.pyenv/versions/3.10.9/include/python3.10 or modify the virtualenv to symlink to /Users/williamsn/.pyenv/versions/3.10.9/include. These work, but they don't seem right to me. I can't make a global workaround anywhere (such as exporting CPATH in my Bash profile), because I'm working with multiple Python versions, and I'd end up with the wrong headers half the time. It seems to me like a virtualenv that has an empty include directory and is missing python-config when its parent has a full include directory and contains python-config is a broken virtualenv.

Is there an option I'm missing to include these pieces? Is this a bug I need to file against Python/venv?


问:
Problem Downloading a CSV file React frontend
I have a problem linking between front & backend , at the backend i have the csv file ready to be downloaded with nomation & 2 parameters of start_date & end_date .
`

```<code>import fileSaver from 'file-saver';
import {useaApi} from './Api';
import {ApiScope} from './const.api'

interface Props{
  start_date: Date;
  end_date: Date;
}

export const useCsvDownloader = () => {
  const { loading, error, exec } = useApi(ApiScope.scope, ApiScope.api);

  const getCsvFile = async ({ start_date, end_date }: Props) => {
    const options = {
      url:`${API_URL}/csvdownload/?start=${start_date.toISOString()}&end=${end_date.toISOString()}`,
      method: 'POST',
      data: Request,
      responseType: 'blob',
      headers: {
        'content-type': 'text/csv',
      },
    };
    try {
      (response: { data: BlobPart }) => {
        fileSaver.saveAs(new Blob([response.data]), __filename);
        return true;
      };
    } catch (error) {
      (function (error: any) {
        console.error('Failed ', error);
        console.error('Failed ', error);
        console.log('Failed ', error);
      });
    }
    const data = await exec(options);
    return {
      data,
    };
  };
  return {
    loading,
    error,
    getCsvFile,
  };
};
</code>```

`

i tried implementing this function but the page don't load up , i expect to download the file directly , is there any method ? any solution ?

the image represent the file ready to be downloaded at backend , i need to link it with front 'react'

Body:
I have a problem linking between front & backend , at the backend i have the csv file ready to be downloaded with nomation & 2 parameters of start_date & end_date .
`

import fileSaver from 'file-saver';
import {useaApi} from './Api';
import {ApiScope} from './const.api'

interface Props{
  start_date: Date;
  end_date: Date;
}

export const useCsvDownloader = () => {
  const { loading, error, exec } = useApi(ApiScope.scope, ApiScope.api);

  const getCsvFile = async ({ start_date, end_date }: Props) => {
    const options = {
      url:`${API_URL}/csvdownload/?start=${start_date.toISOString()}&end=${end_date.toISOString()}`,
      method: 'POST',
      data: Request,
      responseType: 'blob',
      headers: {
        'content-type': 'text/csv',
      },
    };
    try {
      (response: { data: BlobPart }) => {
        fileSaver.saveAs(new Blob([response.data]), __filename);
        return true;
      };
    } catch (error) {
      (function (error: any) {
        console.error('Failed ', error);
        console.error('Failed ', error);
        console.log('Failed ', error);
      });
    }
    const data = await exec(options);
    return {
      data,
    };
  };
  return {
    loading,
    error,
    getCsvFile,
  };
};

`

i tried implementing this function but the page don't load up , i expect to download the file directly , is there any method ? any solution ?

the image represent the file ready to be downloaded at backend , i need to link it with front 'react'


问:
How to read file on server sent with Apollo GraphQL Rest Link?
I'm trying to upload a file from a React component using Apollo GraphQL's rest link ( which allows us to call REST APIs inside GraphQL queries). I'm able to send the file from the client to the server using FormData in the bodySerializer option of the query, but I'm unable to extract the file on the server side. I'm using tornado on the server btw.

My graphql query looks like this:

const UPLOAD_AVATAR = gql`
  mutation UploadAvatar($serialNumber: String!, $file: File!) {
    profile(serialNumber: $serialNumber, file: $file)
      @rest(
        method: "POST"
        path: "/v2/profile/avatar-upload?serial_number={args.serialNumber}"
        bodyKey: "file"
        bodySerializer: $bodySerializer
      ) {
      data
    }
  }
`;

const [uploadAvatar, { loading: uploadLoading }] = useMutation(
  UPLOAD_AVATAR,
  {
    onCompleted: () => {
      setIsEditMode(false);
        refetch();
    },
  }
);
```
<p>When calling the <code>uploadAvatar</code> function, I'm passing in a <code>bodySerializer</code> variable, which creates a new <code>FormData</code> object inside, appends the file to it, and returns the result along with the headers:</p>
<p>and I'm using <code>FormData</code> to add the file to the query like this:</p>
<pre class="lang-js prettyprint-override"><code>  function handleUploadFile(selectedFile) {
    uploadAvatar({
      variables: {
        serialNumber: serialNumber,
        file: selectedFile,
        bodySerializer: (data: any, headers: Headers) => {
          const formData = new FormData();
          formData.append("file", data);
          return { body: formData, headers };
        },
      },
    });
  }
</code>```

On the server side, I first tried to look for the file inside self.request.files, but found nothing there. The file is actually inside self.request.body, but I'm not sure how to extract it.

@gen.coroutine
@tornado.web.authenticated
def post(self):
    target_file = self.request.body
    print(target_file)
```
<p>This is what <code>self.request.body</code> looks like:</p>
<p><code>b'------WebKitFormBoundaryiE73JY38ydKyAVYU\r\nContent-Disposition: form-data; name="file"; filename="Screenshot 2022-12-16 at 22.31.07.png"\r\nContent-Type: image/png\r\n\r\n\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x01\x96\x00\x00\x01j\x08\x06\x00\x00 ... 0\x00\x00IEND\xaeB\x82\r\n------WebKitFormBoundaryiE73JY38ydKyAVYU--\r\n'</code></p>
<p>I tried to decode the file</p>
<pre class="lang-py prettyprint-override"><code>decoded_file = json.loads(target_file.decode("utf-8"))
</code>```

but got an error: 'utf-8' codec can't decode byte 0x89 in position 164: invalid start byte.

How do I correctly extract the file from self.request.body?

Appreciate the help!

Body:
I'm trying to upload a file from a React component using Apollo GraphQL's rest link ( which allows us to call REST APIs inside GraphQL queries). I'm able to send the file from the client to the server using FormData in the bodySerializer option of the query, but I'm unable to extract the file on the server side. I'm using tornado on the server btw.

My graphql query looks like this:

const UPLOAD_AVATAR = gql`
  mutation UploadAvatar($serialNumber: String!, $file: File!) {
    profile(serialNumber: $serialNumber, file: $file)
      @rest(
        method: "POST"
        path: "/v2/profile/avatar-upload?serial_number={args.serialNumber}"
        bodyKey: "file"
        bodySerializer: $bodySerializer
      ) {
      data
    }
  }
`;

const [uploadAvatar, { loading: uploadLoading }] = useMutation(
  UPLOAD_AVATAR,
  {
    onCompleted: () => {
      setIsEditMode(false);
        refetch();
    },
  }
);

When calling the uploadAvatar function, I'm passing in a bodySerializer variable, which creates a new FormData object inside, appends the file to it, and returns the result along with the headers:

and I'm using FormData to add the file to the query like this:

  function handleUploadFile(selectedFile) {
    uploadAvatar({
      variables: {
        serialNumber: serialNumber,
        file: selectedFile,
        bodySerializer: (data: any, headers: Headers) => {
          const formData = new FormData();
          formData.append("file", data);
          return { body: formData, headers };
        },
      },
    });
  }

On the server side, I first tried to look for the file inside self.request.files, but found nothing there. The file is actually inside self.request.body, but I'm not sure how to extract it.

@gen.coroutine
@tornado.web.authenticated
def post(self):
    target_file = self.request.body
    print(target_file)

This is what self.request.body looks like:

b'------WebKitFormBoundaryiE73JY38ydKyAVYU\r\nContent-Disposition: form-data; name="file"; filename="Screenshot 2022-12-16 at 22.31.07.png"\r\nContent-Type: image/png\r\n\r\n\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x01\x96\x00\x00\x01j\x08\x06\x00\x00 ... 0\x00\x00IEND\xaeB\x82\r\n------WebKitFormBoundaryiE73JY38ydKyAVYU--\r\n'

I tried to decode the file

decoded_file = json.loads(target_file.decode("utf-8"))

but got an error: 'utf-8' codec can't decode byte 0x89 in position 164: invalid start byte.

How do I correctly extract the file from self.request.body?

Appreciate the help!


问:
without page refresh dropdown selected value to get data form api vue3
topbar.vue

```<code><script setup>
import { ref, computed, onMounted, onBeforeUnmount ,reactive} from 'vue';
import { useLayout } from '@/layout/composables/layout';
import { useRouter } from 'vue-router';
import ApiService from '../services/api.service';

const { layoutConfig, onMenuToggle, contextPath } = useLayout();
//const state = ref(null);
const outsideClickListener = ref(null);
const topbarMenuActive = ref(false);
const router = useRouter();
const items =[];

const dropdownItems = ref(items);
const dropdownItem = ref(null);

onMounted(() => {

  ApiService.getStores().then((data) => {
    data.forEach((value) => {
      items.push({ name: value.shop,value:value.id });
    });
  });
});

const onSelectChange  = () => {
    localStorage.setItem('shop-id',dropdownItem.value);
  //console.log(dropdownItem.value);
}
</script>

<Dropdown id="state" v-model="dropdownItem" :options="dropdownItems" :filter="true"
            optionLabel="name" optionValue="value" @change="onSelectChange()"></Dropdown>

</code>```

api.service

```<code>async getProduct() {
    if(!shop)
    {
      return axios.get(API_URL+'/product/all?id=1', { headers: authHeader() })
      .then((res) => res.data);
    }
    else{
      return axios.get(API_URL+'/product/all?id='+shop, { headers: authHeader() })
      .then((res) => res.data);
    }

  }

</code>```

here dropdown selcted value to id set localstorage after pass axios services api its working fine only
when i page refresh.
but i want to without page refresh dropdown selected value to get data form api.
how to solve this?

Body:
topbar.vue

<Dropdown id="state" v-model="dropdownItem" :options="dropdownItems" :filter="true"
            optionLabel="name" optionValue="value" @change="onSelectChange()"></Dropdown>

api.service

async getProduct() {
    if(!shop)
    {
      return axios.get(API_URL+'/product/all?id=1', { headers: authHeader() })
      .then((res) => res.data);
    }
    else{
      return axios.get(API_URL+'/product/all?id='+shop, { headers: authHeader() })
      .then((res) => res.data);
    }

  }

here dropdown selcted value to id set localstorage after pass axios services api its working fine only
when i page refresh.
but i want to without page refresh dropdown selected value to get data form api.
how to solve this?


问:
Deploy FastAPI with gunicorn and uvicorn in docker
I have built a FastAPI service that I deploy with the next DockerFile:

```<code>FROM python:3.8.10

RUN mkdir /code

WORKDIR /code

COPY requirements.txt .

RUN pip install -r requirements.txt

COPY . .

CMD ["uvicorn", "main:app", "--proxy-headers","--host=0.0.0.0", "--port=80"]
</code>```

Because I am going to use docker compose to deploy the image in a server, i want to gunicorn to manage it all.

My question is how I adapt the Dockerfile to include the gunicorn. I have seen that to run the api with both I should use the following command but i do not how to translate this to the docker file:

```<code>gunicorn -k uvicorn.workers.UvicornWorker
</code>```

Thanks

Body:
I have built a FastAPI service that I deploy with the next DockerFile:

FROM python:3.8.10

RUN mkdir /code

WORKDIR /code

COPY requirements.txt .

RUN pip install -r requirements.txt

COPY . .

CMD ["uvicorn", "main:app", "--proxy-headers","--host=0.0.0.0", "--port=80"]

Because I am going to use docker compose to deploy the image in a server, i want to gunicorn to manage it all.

My question is how I adapt the Dockerfile to include the gunicorn. I have seen that to run the api with both I should use the following command but i do not how to translate this to the docker file:

gunicorn -k uvicorn.workers.UvicornWorker

Thanks


问:
d3: To add inner grey dotted line in Gauge Chart
I'm new in d3.js graph. I have developed a d3 Gauge Chart with version 5.16.0. But I need to add inner grey dotted line as shown in the attached image. I have attached the image. Can you help me to achieve that inner grey dotted line?

My .cshtml file:

```<code>Script version 5.16.0
<div id="OverviewChart"></div>
</code>```

My css file:

```<code>.chart-gauge {
}
.chart-first {
    fill: #1A9AD4
}
.chart-second {
    fill: #10B981
}
.chart-third {
    fill: #F59E0B
}
.chart-fourth {
    fill: #EF4444
}
.needle, .needle-center {
    fill: #464A4F
}
</code>```

My Js file:

```<code>var width = 288;
var height = 288;
var radius = Math.min(width, height) / 2;
var chartInset = 10;
var barWidth = 20;
var innerRadius = radius - chartInset - barWidth;
var outerRadius = radius - chartInset;
var color = "#66AB8C";
var totalPercent = .75;
var padRad = 0.025;
//****Utility methods****
var percToRad = function (perc) {
    return degToRad(percToDeg(perc));
};
var degToRad = function (deg) {
    return deg * Math.PI / 180;
};
var percToDeg = function (perc) {
    return perc * 360;
};
var margin = {
    top: 20,
    right: 20,
    bottom: 20,
    left: 20
};

//****Set up the SVG container****
const svg = d3.select("#OverviewChart")
    .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height / 1.5 + margin.top + margin.bottom);

// Add layer for the panel
chart = svg.append('g').attr('transform', "translate(" + ((width + margin.left) / 2) + ", " + ((height + margin.top) / 2) + ")");

chart.append('path').attr('class', "arc chart-first");
chart.append('path').attr('class', "arc chart-second");
chart.append('path').attr('class', "arc chart-third");
chart.append('path').attr('class', "arc chart-fourth");

//****Set up the scales****
const scale = d3.scaleLinear()
    .domain([0, 100]) // The range of possible values
    .range([0, 2 * Math.PI]); // The range of angles in radians

//****Set up the arc generator*****
perc = 0.5;
perc1 = 0.25;
perc2 = 0.25;
perc3 = 0.5;
var next_start = totalPercent;

arcStartRad = percToRad(next_start);
arcEndRad = arcStartRad + percToRad(perc / 3);
next_start += perc / 3;
const arc1 = d3.arc().innerRadius(innerRadius).outerRadius(outerRadius).startAngle(arcStartRad).endAngle(arcEndRad);

arcStartRad = percToRad(next_start);
arcEndRad = arcStartRad + percToRad(perc1 / 3);
next_start += perc1 / 3;
const arc2 = d3.arc().innerRadius(innerRadius).outerRadius(outerRadius).startAngle(arcStartRad + padRad).endAngle(arcEndRad);

arcStartRad = percToRad(next_start);
arcEndRad = arcStartRad + percToRad(perc2 / 3);
next_start += perc2 / 3;
const arc3 = d3.arc().innerRadius(innerRadius).outerRadius(outerRadius).startAngle(arcStartRad + padRad).endAngle(arcEndRad);

arcStartRad = percToRad(next_start);
arcEndRad = arcStartRad + percToRad(perc3 / 3);
const arc4 = d3.arc().innerRadius(innerRadius).outerRadius(outerRadius).startAngle(arcStartRad + padRad).endAngle(arcEndRad);

////****Add the gauge to the SVG****
chart.select(".chart-first").attr('d', arc1);
chart.select(".chart-second").attr('d', arc2);
chart.select(".chart-third").attr('d', arc3);
chart.select(".chart-fourth").attr('d', arc4);

//svg.append("path")
//  .attr('class', 'arc chart-first')
//  .attr("d", arc1)
//  .style("fill", color);

//****Add the value text to the center of the gauge****
//svg.append("text")
//  .attr("x", width / 2)
//  .attr("y", height / 2)
//  .text("Hi")
//  .style("text-anchor", "middle")
//  .style("font-size", "24px");

var dataset = [{
    metric: "Overall Task",//name,
    //value: value
}]

var texts = svg.selectAll("text")
    .data(dataset)
    .enter();

texts.append("text")
    .text(function () {
        return "388";
    })
    .attr('id', "Name")
    .attr('transform', "translate(" + ((width + margin.left) / 2.3) + ", " + ((height + margin.top) / 2.5) + ")")
    .attr("font-family", "Open Sans")
    .attr("font-size", 28)
    .attr("font-weight", 600)
    .attr("line-height", 34)
    .attr("letter-spacing", -0.02)
    .attr("text-align", "center")
    .style("fill", "#000000");

texts.append("text")
    .text(function () {
        return dataset[0].metric;
    })
    .attr('id', "Name")
    .attr('transform', "translate(" + ((width + margin.left) / 3) + ", " + ((height + margin.top) / 1.5) + ")")
    .attr("font-family", "Open Sans")
    .attr("font-size", 18)
    .attr("font-weight", 600)
    .attr("line-height", 22)
    .attr("letter-spacing", 0)
    .attr("text-align", "left")
    .style("fill", "#000000");

texts.append("text")
    .text(function () {
        return "Updated on 07/11/2022";
    })
    .attr('id', "Name")
    .attr('transform', "translate(" + ((width + margin.left) / 3.5) + ", " + ((height + margin.top) / 1.37) + ")")
    .attr("font-family", "Open Sans")
    .attr("font-size", 12)
    .attr("font-weight", 400)
    .attr("line-height", 18)
    .attr("letter-spacing", 0)
    .attr("text-align", "left")
    .style("fill", "#000000");
</code>```

Body:
I'm new in d3.js graph. I have developed a d3 Gauge Chart with version 5.16.0. But I need to add inner grey dotted line as shown in the attached image. I have attached the image. Can you help me to achieve that inner grey dotted line?

My .cshtml file:

Script version 5.16.0

My css file:

.chart-gauge {
}
.chart-first {
    fill: #1A9AD4
}
.chart-second {
    fill: #10B981
}
.chart-third {
    fill: #F59E0B
}
.chart-fourth {
    fill: #EF4444
}
.needle, .needle-center {
    fill: #464A4F
}

My Js file:

var width = 288;
var height = 288;
var radius = Math.min(width, height) / 2;
var chartInset = 10;
var barWidth = 20;
var innerRadius = radius - chartInset - barWidth;
var outerRadius = radius - chartInset;
var color = "#66AB8C";
var totalPercent = .75;
var padRad = 0.025;
//****Utility methods****
var percToRad = function (perc) {
    return degToRad(percToDeg(perc));
};
var degToRad = function (deg) {
    return deg * Math.PI / 180;
};
var percToDeg = function (perc) {
    return perc * 360;
};
var margin = {
    top: 20,
    right: 20,
    bottom: 20,
    left: 20
};

//****Set up the SVG container****
const svg = d3.select("#OverviewChart")
    .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height / 1.5 + margin.top + margin.bottom);

// Add layer for the panel
chart = svg.append('g').attr('transform', "translate(" + ((width + margin.left) / 2) + ", " + ((height + margin.top) / 2) + ")");

chart.append('path').attr('class', "arc chart-first");
chart.append('path').attr('class', "arc chart-second");
chart.append('path').attr('class', "arc chart-third");
chart.append('path').attr('class', "arc chart-fourth");

//****Set up the scales****
const scale = d3.scaleLinear()
    .domain([0, 100]) // The range of possible values
    .range([0, 2 * Math.PI]); // The range of angles in radians

//****Set up the arc generator*****
perc = 0.5;
perc1 = 0.25;
perc2 = 0.25;
perc3 = 0.5;
var next_start = totalPercent;

arcStartRad = percToRad(next_start);
arcEndRad = arcStartRad + percToRad(perc / 3);
next_start += perc / 3;
const arc1 = d3.arc().innerRadius(innerRadius).outerRadius(outerRadius).startAngle(arcStartRad).endAngle(arcEndRad);

arcStartRad = percToRad(next_start);
arcEndRad = arcStartRad + percToRad(perc1 / 3);
next_start += perc1 / 3;
const arc2 = d3.arc().innerRadius(innerRadius).outerRadius(outerRadius).startAngle(arcStartRad + padRad).endAngle(arcEndRad);

arcStartRad = percToRad(next_start);
arcEndRad = arcStartRad + percToRad(perc2 / 3);
next_start += perc2 / 3;
const arc3 = d3.arc().innerRadius(innerRadius).outerRadius(outerRadius).startAngle(arcStartRad + padRad).endAngle(arcEndRad);

arcStartRad = percToRad(next_start);
arcEndRad = arcStartRad + percToRad(perc3 / 3);
const arc4 = d3.arc().innerRadius(innerRadius).outerRadius(outerRadius).startAngle(arcStartRad + padRad).endAngle(arcEndRad);

////****Add the gauge to the SVG****
chart.select(".chart-first").attr('d', arc1);
chart.select(".chart-second").attr('d', arc2);
chart.select(".chart-third").attr('d', arc3);
chart.select(".chart-fourth").attr('d', arc4);

//svg.append("path")
//  .attr('class', 'arc chart-first')
//  .attr("d", arc1)
//  .style("fill", color);

//****Add the value text to the center of the gauge****
//svg.append("text")
//  .attr("x", width / 2)
//  .attr("y", height / 2)
//  .text("Hi")
//  .style("text-anchor", "middle")
//  .style("font-size", "24px");

var dataset = [{
    metric: "Overall Task",//name,
    //value: value
}]

var texts = svg.selectAll("text")
    .data(dataset)
    .enter();

texts.append("text")
    .text(function () {
        return "388";
    })
    .attr('id', "Name")
    .attr('transform', "translate(" + ((width + margin.left) / 2.3) + ", " + ((height + margin.top) / 2.5) + ")")
    .attr("font-family", "Open Sans")
    .attr("font-size", 28)
    .attr("font-weight", 600)
    .attr("line-height", 34)
    .attr("letter-spacing", -0.02)
    .attr("text-align", "center")
    .style("fill", "#000000");

texts.append("text")
    .text(function () {
        return dataset[0].metric;
    })
    .attr('id', "Name")
    .attr('transform', "translate(" + ((width + margin.left) / 3) + ", " + ((height + margin.top) / 1.5) + ")")
    .attr("font-family", "Open Sans")
    .attr("font-size", 18)
    .attr("font-weight", 600)
    .attr("line-height", 22)
    .attr("letter-spacing", 0)
    .attr("text-align", "left")
    .style("fill", "#000000");

texts.append("text")
    .text(function () {
        return "Updated on 07/11/2022";
    })
    .attr('id', "Name")
    .attr('transform', "translate(" + ((width + margin.left) / 3.5) + ", " + ((height + margin.top) / 1.37) + ")")
    .attr("font-family", "Open Sans")
    .attr("font-size", 12)
    .attr("font-weight", 400)
    .attr("line-height", 18)
    .attr("letter-spacing", 0)
    .attr("text-align", "left")
    .style("fill", "#000000");


问:
AAB file size increase after download from playstore. UNITY
I am facing an issue of increase in size when aab is downloaded from playstore. When I make an apk it is 360mbs and aab file have size of 190mbs. When I upload and download from store it is taking more than 1 gb in storage. I have tried different compressions but it doesnot seems to work. I cannnot figure the issue will appreciate any help. Thanks

using Unity 2021.3.15f1 LTS.

I have tried all three compressions

Default

Lz4hc

lz4
Tried to make aab PAD method as well. I have attached screenshot of build settings.


问:
How can I compare the properties of a vertice, to the properties of another vertice
I'm using Gremlin to interact with a Graph in CosmosDB.

I have some data about employees, data they have access to and departments where both originate from. See below for an example.

I want to retrieve information from my graph about which employees have access to data, but doesn't belong in their department. Basically, I want to see where the department columns are not equal, but the column data_access and data_id are equal, for every database the employee has access to. From the example below I would return information employee_id 1 and 2.

employee_id
name
department
data_access

1
john
A
4

2
rick
B
5

3
nick
A
5

dataset_id
name
department

4
apples
B

5
oranges
A

So far I tried to construct queries using traversal steps like "has", "as", "where" but I couldn't achieve the result I want. I'm very new to Gremlin, so I have no idea if what I'm doing is even the right way to do it.


问:
Should I standardize the second datset with the same scaling as in the first dataset?
I am in very much confusion.

I have two datasets. One dataset is considered a source domain (Dataset A) and other dataset is considered a target domain (Dataset B).

First, I standardized each column of Dataset A using mean and standard deviation value of respective columns. I have 600 points in the dataset A. Then I splitted my dataset into Training, Validation and Testing dataset. I trained CNN model and then I tested model using testing dataset. I gives pretty accurate results (prediction).

I have calculated mean and standard deviation of each column available in Dataset A as follow,

```<code>thicknessMean = np.mean(thick_SD)
MaxForceMean = np.mean(maxF_SD)
MeanForceMean = np.mean(meanF_SD)

thicknessstd = np.std(thick_SD)
MaxForcestd = np.std(maxF_SD)
MeanForcestd = np.std(meanF_SD)

thick_SD_scaled = (thick_SD - thicknessMean)/thicknessstd
maxF_SD_scaled = (maxF_SD - MaxForceMean)/MaxForcestd
meanF_SD_scaled = (meanF_SD - MeanForceMean)/MeanForcestd
</code>```

Now, I want to make prediction from the model by feeding the Dataset B. Therefore, I saved the already trained model (with .pth file). Then I standardize the dataset B, but this time I have transformed the dataset using 'mean' and 'standard deviation' of the dataset A. After doing this, I evaluate the already trained model using dataset B. But it is giving a worse prediction.

```<code>thick_TD_scaled = (thick_TD - thicknessMean)/thicknessstd
maxF_TD_scaled = (maxF_TD - MaxForceMean)/MaxForcestd
meanF_TD_scaled = (meanF_TD - MeanForceMean)/MeanForcestd
</code>```

You can see, to scale my dataset B, I have used mean value for eg.thicknessMean and standard deviation for eg. thicknessstd value of the Dataset A .

My question is:

(1) where I am doing wrong? What should I do to make my prediction near to accurate?

(2) When I check prediction's accuracy on two different dataset, should I standardize the second dataset at a same scaling as in the first dataset?

Body:
I am in very much confusion.

I have two datasets. One dataset is considered a source domain (Dataset A) and other dataset is considered a target domain (Dataset B).

First, I standardized each column of Dataset A using mean and standard deviation value of respective columns. I have 600 points in the dataset A. Then I splitted my dataset into Training, Validation and Testing dataset. I trained CNN model and then I tested model using testing dataset. I gives pretty accurate results (prediction).

I have calculated mean and standard deviation of each column available in Dataset A as follow,

thicknessMean = np.mean(thick_SD)
MaxForceMean = np.mean(maxF_SD)
MeanForceMean = np.mean(meanF_SD)

thicknessstd = np.std(thick_SD)
MaxForcestd = np.std(maxF_SD)
MeanForcestd = np.std(meanF_SD)

thick_SD_scaled = (thick_SD - thicknessMean)/thicknessstd
maxF_SD_scaled = (maxF_SD - MaxForceMean)/MaxForcestd
meanF_SD_scaled = (meanF_SD - MeanForceMean)/MeanForcestd

Now, I want to make prediction from the model by feeding the Dataset B. Therefore, I saved the already trained model (with .pth file). Then I standardize the dataset B, but this time I have transformed the dataset using 'mean' and 'standard deviation' of the dataset A. After doing this, I evaluate the already trained model using dataset B. But it is giving a worse prediction.

thick_TD_scaled = (thick_TD - thicknessMean)/thicknessstd
maxF_TD_scaled = (maxF_TD - MaxForceMean)/MaxForcestd
meanF_TD_scaled = (meanF_TD - MeanForceMean)/MeanForcestd

You can see, to scale my dataset B, I have used mean value for eg.thicknessMean and standard deviation for eg. thicknessstd value of the Dataset A .

My question is:

(1) where I am doing wrong? What should I do to make my prediction near to accurate?

(2) When I check prediction's accuracy on two different dataset, should I standardize the second dataset at a same scaling as in the first dataset?