问:
Changing the Default Database in a Stored Procedure at Runtime
I have a stored procedure in a database called DEV1 which exists in a Schema called BI.

I am connecting with an ODBC connection that sets the default database of the session to a databased called DEV2.  I am unable to modify the ODBC connection of this service account due to how it is setup in key vaults/secrets managers for various environments.

When calling the stored procedure in the format of call DEV1.BI.StoredProcedureName() from the service account which has it's session database set to DEV2, StoredProcedureName() the query fails if the stored procedure attempts to read from Views which do not fully qualify the database name and exist in the DEV1 database, which are only referenced by a Schema.Table reference instead of database.schema.table.  In my case this service account looks in DEV2 for these objects, which fails due to them not existing.

Is there functionality within Stored Procedures to overcome this issue?

It has been an architectural decision to leave database names out of our views and stored procedures, which enables us to CLONE COPY a higher environment (Prod) to a lower one (UAT) for testing.  This process breaks if we hard code views with CI/CD variables swapped at deployment time.

It's understood that using a different service account can overcome this issue by setting the default database, but when this requires creating somewhat redundant artifacts in key vaults, it seems unnecessary if there exists syntax that can set the Stored Procedure to the right database before execution.  I have tried adding a USE [database]; statement as a first-step in the stored proc, unsuccessfully.

Are we chasing dragons or is it possible to achieve what we're looking for without additional service accounts?

We've tried overcoming this by wrapping the uncallable SP in a wrapper Stored Procedure which first changes the database context similar to this:

```<code>CREATE OR REPLACE PROCEDURE DEV1.BI.AStoredProcedure()
    RETURNS VARCHAR(16777216)
    LANGUAGE SQL
    EXECUTE AS CALLER
AS 'begin
 use DATABASE DEV1;
 call BI.AStoredProcedure()
end';
</code>```

This executes successfully but does not return the data produced by the AStoredProcedure() execution.  It feels like we're close but there's no documentation on such behaviour in the Snowflake documentation (that I've been able to find).

Thanks in advance for everyone's input!

Body:
I have a stored procedure in a database called DEV1 which exists in a Schema called BI.

I am connecting with an ODBC connection that sets the default database of the session to a databased called DEV2.  I am unable to modify the ODBC connection of this service account due to how it is setup in key vaults/secrets managers for various environments.

When calling the stored procedure in the format of call DEV1.BI.StoredProcedureName() from the service account which has it's session database set to DEV2, StoredProcedureName() the query fails if the stored procedure attempts to read from Views which do not fully qualify the database name and exist in the DEV1 database, which are only referenced by a Schema.Table reference instead of database.schema.table.  In my case this service account looks in DEV2 for these objects, which fails due to them not existing.

Is there functionality within Stored Procedures to overcome this issue?

It has been an architectural decision to leave database names out of our views and stored procedures, which enables us to CLONE COPY a higher environment (Prod) to a lower one (UAT) for testing.  This process breaks if we hard code views with CI/CD variables swapped at deployment time.

It's understood that using a different service account can overcome this issue by setting the default database, but when this requires creating somewhat redundant artifacts in key vaults, it seems unnecessary if there exists syntax that can set the Stored Procedure to the right database before execution.  I have tried adding a USE [database]; statement as a first-step in the stored proc, unsuccessfully.

Are we chasing dragons or is it possible to achieve what we're looking for without additional service accounts?

We've tried overcoming this by wrapping the uncallable SP in a wrapper Stored Procedure which first changes the database context similar to this:

CREATE OR REPLACE PROCEDURE DEV1.BI.AStoredProcedure()
    RETURNS VARCHAR(16777216)
    LANGUAGE SQL
    EXECUTE AS CALLER
AS 'begin
 use DATABASE DEV1;
 call BI.AStoredProcedure()
end';

This executes successfully but does not return the data produced by the AStoredProcedure() execution.  It feels like we're close but there's no documentation on such behaviour in the Snowflake documentation (that I've been able to find).

Thanks in advance for everyone's input!


来源: stackexchange

问:
How do I make vite ignore a directory?
I have a directory service-worker at the very top level of my project, that contains one file.

```<code>$ ls service-worker/
helpers.ts  service-worker.ts
</code>```

I wish to make vite ignore this directory, and have researched this discussion (which turned out to be an unrelated cause) and the optimizeDeps.exclude() function.

I am using a minimal vite.config.ts:

```<code>// https://vitejs.dev/config/
import { defineConfig } from "vite";

export default defineConfig({
  optimizeDeps: {
    exclude: ["service-worker/*"],
  },
});
</code>```

But the service-worker is always built:

```<code>$ rm dist/service-worker.js; npx vite build; ls -la dist/service-worker.js

vite v3.0.9 building for production...
✓ 3 modules transformed.
dist/index.html                 0.38 KiB
dist/assets/index.891d93e6.js   0.69 KiB / gzip: 0.39 KiB
-rw-r--r-- 1 mike mike 1544 Dec 12 19:46 dist/service-worker.js
</code>```

How do I make vite ignore a directory?

ContentLicense: CC BY-SA 4.0

Title: How do I make vite ignore a directory?

Body:
I have a directory service-worker at the very top level of my project, that contains one file.

$ ls service-worker/
helpers.ts  service-worker.ts

I wish to make vite ignore this directory, and have researched this discussion (which turned out to be an unrelated cause) and the optimizeDeps.exclude() function.

I am using a minimal vite.config.ts:

// https://vitejs.dev/config/
import { defineConfig } from "vite";

export default defineConfig({
  optimizeDeps: {
    exclude: ["service-worker/*"],
  },
});

But the service-worker is always built:

$ rm dist/service-worker.js; npx vite build; ls -la dist/service-worker.js

vite v3.0.9 building for production...
✓ 3 modules transformed.
dist/index.html                 0.38 KiB
dist/assets/index.891d93e6.js   0.69 KiB / gzip: 0.39 KiB
-rw-r--r-- 1 mike mike 1544 Dec 12 19:46 dist/service-worker.js

How do I make vite ignore a directory?


问:
Why don't we use numpy structured arrays to do data analysis ? I
Why is it so that we use pandas for data cleaning and analysis ? I understand that it has the import csv functions and other convenience methods, but could we do most or all of the work only using numpy ?</p>


问:
Webpacker error in rails 7 , <%= javascript_pack_tag 'application' %> not working
I've been having this issue some time since I've started this course, however only now it became a problem.

I'm fairly new to rails and I have this issue with webpacker:

webpacker error page

The problem is with the <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>  If I simply delete it, there is no problem and everything is working as it should, however as expected JavaScript is not included to file.

So far I've spend some time on fixing error and tried those solutions:

->  Reinstalling webpacker

-> Reinstalling RoR and all gems

-> trying to change application.js  path, to make sure rails sees it

-> Trying to run a Completly new RoR project - had the same error

-> Tried to use some work-around code for <%= javascript_pack_tag 'application' %> , also with no succsess

Ive tried all solutions that mentioned above on rails 6.06 and on rails 7.0.4

Im using Rails 7.0.4 , ruby 3.1.2 and webpacker 4.0, on windows 10

I really hope someone will help me out w this. I can even paypal if ud make it work lol

PS. Sorry for my grammar, except RoR I'm also learning English :)

Below all the files and info that might be needed:

CONSOLE ERROR

console err

GEMFILE

```<code>> source 'https://rubygems.org'
> git_source(:github) { |repo| "https://github.com/#{repo}.git" }
>
> ruby '3.1.2'
>
> Bundle edge Rails instead: gem 'rails', github: 'rails/rails', branch: 'main'
> gem 'rails', '~> 7.0.4'
> Use sqlite3 as the database for Active Record
> gem 'sqlite3', '~> 1.4'
> Use Puma as the app server
> gem 'puma', '~> 4.1'
> changed by mua
> gem 'tzinfo-data'
>
> Use SCSS for stylesheets
> gem 'sass-rails', '>= 6'
> Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker
> gem 'webpacker', '~> 4.0'
> Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
> gem 'turbolinks', '~> 5'
> Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
> gem 'jbuilder', '~> 2.7'
> Use Redis adapter to run Action Cable in production
> gem 'redis', '~> 4.0'
> Use Active Model has_secure_password
> gem 'bcrypt', '~> 3.1.7'
> gem 'psych', '< 4'
> Use Active Storage varianti
> gem 'image_processing', '~> 1.2'
>
> Reduces boot times through caching; required in config/boot.rb
> gem 'bootsnap', '>= 1.4.2', require: false
>
> group :development, :test do
> Call 'byebug' anywhere in the code to stop execution and get a debugger console
> gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
> end
>
> group :development do
> Access an interactive console on exception pages or by calling 'console' anywhere in the code.
> gem 'web-console', '>= 3.3.0'
> end
>
> group :test do
> Adds support for Capybara system testing and selenium driver
> gem 'capybara', '>= 2.15'
> gem 'selenium-webdriver'
> Easy installation and use of web drivers to run system tests with browsers
> gem 'webdrivers'
> end
>
> Windows does not include zoneinfo files, so bundle the tzinfo-data gem
> gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
</code>```

APPLICATION JS

```<code>// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")

// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
// const images = require.context('../images', true)
// const imagePath = (name) => images(name, true)
import "bootstrap"
</code>```

PACKAGE.JSON

```<code>{
  "name": "alpha_blog",
  "private": true,
  "dependencies": {
    "@rails/actioncable": "^6.0.0",
    "@rails/activestorage": "^6.0.0",
    "@rails/ujs": "^6.0.0",
    "@rails/webpacker": "4.2.2",
    "bootstrap": "5.2",
    "jquery": "^3.6.1",
    "popper.js": "^1.16.1",
    "turbolinks": "^5.2.0"
  },
  "version": "0.1.0",
  "devDependencies": {
    "webpack-dev-server": "^3.10.3"
  }
}
</code>```

Body:
I've been having this issue some time since I've started this course, however only now it became a problem.

I'm fairly new to rails and I have this issue with webpacker:

webpacker error page

The problem is with the <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>  If I simply delete it, there is no problem and everything is working as it should, however as expected JavaScript is not included to file.

So far I've spend some time on fixing error and tried those solutions:

->  Reinstalling webpacker

-> Reinstalling RoR and all gems

-> trying to change application.js  path, to make sure rails sees it

-> Trying to run a Completly new RoR project - had the same error

-> Tried to use some work-around code for <%= javascript_pack_tag 'application' %> , also with no succsess

Ive tried all solutions that mentioned above on rails 6.06 and on rails 7.0.4

Im using Rails 7.0.4 , ruby 3.1.2 and webpacker 4.0, on windows 10

I really hope someone will help me out w this. I can even paypal if ud make it work lol

PS. Sorry for my grammar, except RoR I'm also learning English :)

Below all the files and info that might be needed:

CONSOLE ERROR

console err

GEMFILE

> source 'https://rubygems.org'
> git_source(:github) { |repo| "https://github.com/#{repo}.git" }
>
> ruby '3.1.2'
>
> Bundle edge Rails instead: gem 'rails', github: 'rails/rails', branch: 'main'
> gem 'rails', '~> 7.0.4'
> Use sqlite3 as the database for Active Record
> gem 'sqlite3', '~> 1.4'
> Use Puma as the app server
> gem 'puma', '~> 4.1'
> changed by mua
> gem 'tzinfo-data'
>
> Use SCSS for stylesheets
> gem 'sass-rails', '>= 6'
> Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker
> gem 'webpacker', '~> 4.0'
> Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
> gem 'turbolinks', '~> 5'
> Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
> gem 'jbuilder', '~> 2.7'
> Use Redis adapter to run Action Cable in production
> gem 'redis', '~> 4.0'
> Use Active Model has_secure_password
> gem 'bcrypt', '~> 3.1.7'
> gem 'psych', '< 4'
> Use Active Storage varianti
> gem 'image_processing', '~> 1.2'
>
> Reduces boot times through caching; required in config/boot.rb
> gem 'bootsnap', '>= 1.4.2', require: false
>
> group :development, :test do
> Call 'byebug' anywhere in the code to stop execution and get a debugger console
> gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
> end
>
> group :development do
> Access an interactive console on exception pages or by calling 'console' anywhere in the code.
> gem 'web-console', '>= 3.3.0'
> end
>
> group :test do
> Adds support for Capybara system testing and selenium driver
> gem 'capybara', '>= 2.15'
> gem 'selenium-webdriver'
> Easy installation and use of web drivers to run system tests with browsers
> gem 'webdrivers'
> end
>
> Windows does not include zoneinfo files, so bundle the tzinfo-data gem
> gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

APPLICATION JS

// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")

// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
// const images = require.context('../images', true)
// const imagePath = (name) => images(name, true)
import "bootstrap"

PACKAGE.JSON

{
  "name": "alpha_blog",
  "private": true,
  "dependencies": {
    "@rails/actioncable": "^6.0.0",
    "@rails/activestorage": "^6.0.0",
    "@rails/ujs": "^6.0.0",
    "@rails/webpacker": "4.2.2",
    "bootstrap": "5.2",
    "jquery": "^3.6.1",
    "popper.js": "^1.16.1",
    "turbolinks": "^5.2.0"
  },
  "version": "0.1.0",
  "devDependencies": {
    "webpack-dev-server": "^3.10.3"
  }
}


问:
Get file using its path
so I have a function that takes in a string and determines if it is a url or a path to a file

```<code> ImageProvider<Object> displayPicture(String? image) {
      if (image!.contains("https://")) {
        return NetworkImage(image);
      } else {
        return FileImage(File(image));
      }
    }
</code>```

I seen an answer online to do so this way but File() doesn't seem to take in a file path and return a file
any help be apricated

Title: Get file using its path

Body:
so I have a function that takes in a string and determines if it is a url or a path to a file

 ImageProvider<Object> displayPicture(String? image) {
      if (image!.contains("https://")) {
        return NetworkImage(image);
      } else {
        return FileImage(File(image));
      }
    }

I seen an answer online to do so this way but File() doesn't seem to take in a file path and return a file
any help be apricated


问:
Issue retrieving an ISODate field from MongoDB in the correct format
We are running into issues retrieving MongoDB document using Spring JPA as it relates to MongoDB date field. Here is a document

```<code>{
    "field1": "some value",
    "field2": {
        "field2sub1": "some value",
        "field2datefield": ISODate(1234567890)
    }
}
</code>```

Java object:

```<code>@Data
class Dto {
    private String field1;
    private JsonNode field2;
}
</code>```

Once we retireve the data, the Dto.field2 looks as follows:

```<code>{
    "field2sub1": "some value",
    "field2datefield": {$date: "2022-01-01....."}
}
</code>```

The conversion is done correctly, except for what I need is

```<code>{
    "field2sub1": "some value",
    "field2datefield": 1234567890
}
</code>```

without {$date: ....}.

The data is retrieved using this code:

```<code>List<Dto> eventRtrs = mongoTemplate.find(query, Dto.class, "collection_name")
</code>```

Is there a way to specify that date fields need to be retrieved as a long or a formatted date and not as {$date ...} object?

UPDATE:

Potential solution I found was to recursively search the Document for any Date objects and convert them to Longs.

```<code>private void documentIterator(Map<String, Object> map) {
    for(Map.Entry<String, Object> entry : map.entrySet()) {
        // if the value is another map, search one level deeper
        if (entry.getValue() instanceof Map) {
            documentIterator((Map<String, Object>) entry.getValue());
        }
        // if the value is a Date, change it to a Long
        else if(entry.getValue() instanceof Date) {
            entry.setValue(((Date) entry.getValue()).getTime());
        }
    }
}
</code>```

Ideally though, I would be able to have the ObjectMapper do this conversion when it is converting the Document to a JsonNode to avoid this traversal.

Body:
We are running into issues retrieving MongoDB document using Spring JPA as it relates to MongoDB date field. Here is a document

{
    "field1": "some value",
    "field2": {
        "field2sub1": "some value",
        "field2datefield": ISODate(1234567890)
    }
}

Java object:

@Data
class Dto {
    private String field1;
    private JsonNode field2;
}

Once we retireve the data, the Dto.field2 looks as follows:

{
    "field2sub1": "some value",
    "field2datefield": {$date: "2022-01-01....."}
}

The conversion is done correctly, except for what I need is

{
    "field2sub1": "some value",
    "field2datefield": 1234567890
}

without {$date: ....}.

The data is retrieved using this code:

List<Dto> eventRtrs = mongoTemplate.find(query, Dto.class, "collection_name")

Is there a way to specify that date fields need to be retrieved as a long or a formatted date and not as {$date ...} object?

UPDATE:

Potential solution I found was to recursively search the Document for any Date objects and convert them to Longs.

private void documentIterator(Map<String, Object> map) {
    for(Map.Entry<String, Object> entry : map.entrySet()) {
        // if the value is another map, search one level deeper
        if (entry.getValue() instanceof Map) {
            documentIterator((Map<String, Object>) entry.getValue());
        }
        // if the value is a Date, change it to a Long
        else if(entry.getValue() instanceof Date) {
            entry.setValue(((Date) entry.getValue()).getTime());
        }
    }
}

Ideally though, I would be able to have the ObjectMapper do this conversion when it is converting the Document to a JsonNode to avoid this traversal.


问:
HOW TO FILTER DJANGO QUERYSETS WITH MULTIPLE AGGREGATIONS
Lets say I have a django model table

```<code>class Table(models.Model):
      name         = models.CharField()
      date_created = models.DatetimeField()
      total_sales  = models.DecimalField()
</code>```

some data for context

Name
date-created
total-sales

a
2020-01-01
200

b
2020-02-01
300

c
2020-04-01
400

*
**********
***

c
2020-12-01
1000

c
2020-12-12
500

now I want to filter an aggregate of

total_yearly_sales = 10500

current month being December

total_monthly_sales = 1500

daily_sales

total_daily_sales = 500

also do a Group by by name

models.Table.objects.values('Name').annotate(Sum('total-sales')).order_by()

I want to do this in one query(one db hit)

Hence the query should generate

total_yearly_sales

total_monthly_sales

total_daily_sales

total_sales_grouped_by_name ie {a:200, b:300, c:1900}

I know this is too much to ask. Hence let me express my immense gratitude and thanks for having a look at this.

cheers

The above queries I can generate them individually like so

```<code>today = timezone.now().date()
</code>```
```<code>todays_sales = models.Table.filter(date_created__date__gte=today, date_created___date__lte=today).aggregate(Sum('total_sales'))

=> 500
</code>```
```<code>monthly_sales(this month) = models.Table.objects.filter(date_created__year=today.year, date_created__month=today.month).aggregate(Sum('total_sales'))
 =>10500
</code>```
```<code>total_yearly_sales = models.Table.objects.filter(date_created__year=today.year).aggregate(Sum('total_sales')) => 10500
</code>```

Body:
Lets say I have a django model table

class Table(models.Model):
      name         = models.CharField()
      date_created = models.DatetimeField()
      total_sales  = models.DecimalField()

some data for context

Name
date-created
total-sales

a
2020-01-01
200

b
2020-02-01
300

c
2020-04-01
400

*
**********
***

c
2020-12-01
1000

c
2020-12-12
500

now I want to filter an aggregate of

total_yearly_sales = 10500

current month being December

total_monthly_sales = 1500

daily_sales

total_daily_sales = 500

also do a Group by by name

models.Table.objects.values('Name').annotate(Sum('total-sales')).order_by()

I want to do this in one query(one db hit)

Hence the query should generate

total_yearly_sales

total_monthly_sales

total_daily_sales

total_sales_grouped_by_name ie {a:200, b:300, c:1900}

I know this is too much to ask. Hence let me express my immense gratitude and thanks for having a look at this.

cheers

The above queries I can generate them individually like so

today = timezone.now().date()

todays_sales = models.Table.filter(date_created__date__gte=today, date_created___date__lte=today).aggregate(Sum('total_sales'))

=> 500

monthly_sales(this month) = models.Table.objects.filter(date_created__year=today.year, date_created__month=today.month).aggregate(Sum('total_sales'))
 =>10500

total_yearly_sales = models.Table.objects.filter(date_created__year=today.year).aggregate(Sum('total_sales')) => 10500


问:
How to reset Localization in english after logout in flutter

I have implemented localization in my app. It has two languages arabic and english. It is working fine but if i want to logout then i want to set it again to default language english. Any suggestions how can i do it?

Note
i am using simple method of localization.


问:
How to detect change in query params in Angular when done via Javascript
I am apending query params in my ASP.NET core app via javascript as below to append it without a reload.
Also I have loaded a angular component in my c# code which is

```<code>window.history.pushState({path: currentURL}, '', currentURL)
<app-root></app-root>
</code>```

I am using activated route in my angular app in constructor to listen the changes as below

```<code>this.route.queryParams.subscribe(params => {
let paramObject = {...params['keys'], ...params);
console.log(paramsObject)
})
</code>```

I can only detect changes when there is a page reload and not when I use pushState method to append the query params

Is there something missing here.

Body:
I am apending query params in my ASP.NET core app via javascript as below to append it without a reload.
Also I have loaded a angular component in my c# code which is

window.history.pushState({path: currentURL}, '', currentURL)
<app-root></app-root>

I am using activated route in my angular app in constructor to listen the changes as below

this.route.queryParams.subscribe(params => {
let paramObject = {...params['keys'], ...params);
console.log(paramsObject)
})

I can only detect changes when there is a page reload and not when I use pushState method to append the query params

Is there something missing here.


问:
How to store and manage images for selected users in MY SQL?
We are planning to upload Image only available for selected users. Here we have store the Image with visible users list in MuSql database.

At the same time consider a mobile API (Node JS), In that we have to fetch the all list of image urls that are visible for some random list of users (Users list from API request body). The image urls that are shown should be available only for the users in the request. The images that are not visible for the requested users should not be shown in the response list.

Please help us with how we have to setup the table and its columns in order the achieve the functionlaity.

We have tried adding a column users_list of JSON type to the table. With this we have made loop with requested users list with the users_list in the table. The difficulty is that when the requested users list very long then the loops gets more time execute.

Is there any way to fetch the images list that are available for requested users using MySql query without looping.


问:
too long Base64 image won't display with expo
I've been trying a couple ways, but I couldn't make it work. I'm receiving a Base64 image from my backend, but since it's too big, it doesn't display in my expo app. Smaller Base64 images work well, then I suppose it might be about the Base64 string length. It doesn't show any errors, but it's a blank space where the image was supposed to be. Any explanations on why and maybe solutions?

Big images from local directory worked well using 'require()', and so did smaller images as Base64 string. I know I shouldn't be using Base64 images so far, since I could've been using buckets or even public directories, but I can't change it right now.


问:
Login with azure doesn't returns info of auth
I'm using this steps to connect Azure with C# and get a quickstart.
https://learn.microsoft.com/pt-br/azure/active-directory/develop/web-app-quickstart?pivots=devlang-aspnet

But when I implement this code in my current LoginController, it just doesn't work. Literally my login page refreshes and nothing happens.

This is my code - I use loginAzure to redirect to a Microsoft webpage that returns auth.

```<code>public void LoginAzure()
{
    if (!Request.IsAuthenticated)
    {
        HttpContext.GetOwinContext().Authentication.Challenge(
                new AuthenticationProperties { RedirectUri = "/" },
                OpenIdConnectAuthenticationDefaults.AuthenticationType);
    }
}

// The Client ID is used by the application to uniquely identify itself to Azure AD.
string clientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"];

// RedirectUri is the URL where the user will be redirected to after they sign in.
string redirectUri = System.Configuration.ConfigurationManager.AppSettings["RedirectUri"];

// Tenant is the tenant ID (e.g. contoso.onmicrosoft.com, or 'common' for multi-tenant)
static string tenant = System.Configuration.ConfigurationManager.AppSettings["Tenant"];

// Authority is the URL for authority, composed by Microsoft identity platform endpoint and the tenant name (e.g. https://login.microsoftonline.com/contoso.onmicrosoft.com/v2.0)
string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, System.Configuration.ConfigurationManager.AppSettings["Authority"], tenant);

/// <summary>
/// Configure OWIN to use OpenIdConnect
/// </summary>
/// <param name="app"></param>
public void Configuration(IAppBuilder app)
{
    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

     app.UseCookieAuthentication(new CookieAuthenticationOptions());
     app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                // Sets the ClientId, authority, RedirectUri as obtained from web.config
                ClientId = clientId,
                Authority = authority,
                RedirectUri = redirectUri,

                // PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page
                PostLogoutRedirectUri = redirectUri,
                Scope = OpenIdConnectScope.OpenIdProfile,
                //Handle the incorret issuer
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false
                },
                // ResponseType is set to request the code id_token - which contains basic information about the signed-in user
                ResponseType = OpenIdConnectResponseType.CodeIdToken,

                // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = OnAuthenticationFailed
                }
            }) ;
}
</code>```

My login page has the same code of them but it simple doesn't go anywhere.

```<code>@if (!Request.IsAuthenticated)
{
    <!-- If the user is not authenticated, display the sign-in button -->
    <a href="@Url.Action("LoginAzure", "Login")" style="text-decoration: none;">
    Sign in with Microsoft
    </a>
}
else
{
    <br />
    <span>Hello @System.Security.Claims.ClaimsPrincipal.Current.FindFirst("name").Value;</span>
    <br /><br />
}
</code>```

I need the users logged information to log into my page using a SSO method.

Body:
I'm using this steps to connect Azure with C# and get a quickstart.
https://learn.microsoft.com/pt-br/azure/active-directory/develop/web-app-quickstart?pivots=devlang-aspnet

But when I implement this code in my current LoginController, it just doesn't work. Literally my login page refreshes and nothing happens.

This is my code - I use loginAzure to redirect to a Microsoft webpage that returns auth.

public void LoginAzure()
{
    if (!Request.IsAuthenticated)
    {
        HttpContext.GetOwinContext().Authentication.Challenge(
                new AuthenticationProperties { RedirectUri = "/" },
                OpenIdConnectAuthenticationDefaults.AuthenticationType);
    }
}

// The Client ID is used by the application to uniquely identify itself to Azure AD.
string clientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"];

// RedirectUri is the URL where the user will be redirected to after they sign in.
string redirectUri = System.Configuration.ConfigurationManager.AppSettings["RedirectUri"];

// Tenant is the tenant ID (e.g. contoso.onmicrosoft.com, or 'common' for multi-tenant)
static string tenant = System.Configuration.ConfigurationManager.AppSettings["Tenant"];

// Authority is the URL for authority, composed by Microsoft identity platform endpoint and the tenant name (e.g. https://login.microsoftonline.com/contoso.onmicrosoft.com/v2.0)
string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, System.Configuration.ConfigurationManager.AppSettings["Authority"], tenant);

///
/// Configure OWIN to use OpenIdConnect
///
/// <param name="app"></param>
public void Configuration(IAppBuilder app)
{
    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

     app.UseCookieAuthentication(new CookieAuthenticationOptions());
     app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                // Sets the ClientId, authority, RedirectUri as obtained from web.config
                ClientId = clientId,
                Authority = authority,
                RedirectUri = redirectUri,

                // PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page
                PostLogoutRedirectUri = redirectUri,
                Scope = OpenIdConnectScope.OpenIdProfile,
                //Handle the incorret issuer
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false
                },
                // ResponseType is set to request the code id_token - which contains basic information about the signed-in user
                ResponseType = OpenIdConnectResponseType.CodeIdToken,

                // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = OnAuthenticationFailed
                }
            }) ;
}

My login page has the same code of them but it simple doesn't go anywhere.

@if (!Request.IsAuthenticated)
{

    Sign in with Microsoft

}
else
{

    Hello @System.Security.Claims.ClaimsPrincipal.Current.FindFirst("name").Value;

}

I need the users logged information to log into my page using a SSO method.


问:
Django blocktranslate passed variable with jinja include
I need to pass variable in include html and tranlate that passed variable in Django.

In about.html file I include like that:

```<code>include "includes/breadcrumb.html" with dir_path="About us"  %}
</code>```

And in breadcrumb.html file I get variable

```<code>{{dir_path}} - it gives as expected: "About us"
</code>```

But I tried like that to be able to translate it, but not working

```<code>{% blocktranslate with dir_path=dir_path %} {{dir_path }} {% endblocktranslate %}
</code>```

Body:
I need to pass variable in include html and tranlate that passed variable in Django.

In about.html file I include like that:

include "includes/breadcrumb.html" with dir_path="About us"  %}

And in breadcrumb.html file I get variable

{{dir_path}} - it gives as expected: "About us"

But I tried like that to be able to translate it, but not working

{% blocktranslate with dir_path=dir_path %} {{dir_path }} {% endblocktranslate %}


问:
Read video stream from raspberry pi using openCV
I'm trying to build a robot which has efficient low latency video stream. I was able to capture the video using the raspberry pi camera and view it on VLC Media Player using this code:

server (my pc):

import socket
import subprocess

# Start a socket listening for connections on 0.0.0.0:8000 (0.0.0.0 means
# all interfaces)
server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 8000))
server_socket.listen(0)

# Accept a single connection and make a file-like object out of it
connection = server_socket.accept()[0].makefile('rb')
try:
    # Run a viewer with an appropriate command line. Uncomment the mplayer
    # version if you would prefer to use mplayer instead of VLC
    cmdline = ['vlc', '--demux', 'h264', '-']
    #cmdline = ['mplayer', '-fps', '25', '-cache', '1024', '-']
    player = subprocess.Popen(cmdline, stdin=subprocess.PIPE)
    while True:
        # Repeatedly read 1k of data from the connection and write it to
        # the media player's stdin
        data = connection.read(1024)
        if not data:
            break
        player.stdin.write(data)
finally:
    connection.close()
    server_socket.close()
    player.terminate()
```
<p>client (robot):</p>
<pre class="lang-python prettyprint-override"><code>import socket
import time
import picamera

# Connect a client socket to my_server:8000 (change my_server to the
# hostname of your server)
client_socket = socket.socket()
client_socket.connect(('my_server', 8000))

# Make a file-like object out of the connection
connection = client_socket.makefile('wb')
try:
    camera = picamera.PiCamera()
    camera.resolution = (640, 480)
    camera.framerate = 24
    # Start a preview and let the camera warm up for 2 seconds
    camera.start_preview()
    time.sleep(2)
    # Start recording, sending the output to the connection for 60
    # seconds, then stop
    camera.start_recording(connection, format='h264')
    camera.wait_recording(60)
    camera.stop_recording()
finally:
    connection.close()
    client_socket.close()
</code>```

Now I want to read the frames using opencv instead of VLC. Is there a way to do this?

Most answers I have seen involves running the raspi as a rtsp server and then accessing it with cv2.VideoCapture('rtsp://IPaddress:Port'). I want the raspi to be the client though.

Update: actually it'd be even better if there is a way to play the stream directly on a PyQt GUI. Essentially I'd like to make my own version of VLC...

Body:
I'm trying to build a robot which has efficient low latency video stream. I was able to capture the video using the raspberry pi camera and view it on VLC Media Player using this code:

server (my pc):

import socket
import subprocess

# Start a socket listening for connections on 0.0.0.0:8000 (0.0.0.0 means
# all interfaces)
server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 8000))
server_socket.listen(0)

# Accept a single connection and make a file-like object out of it
connection = server_socket.accept()[0].makefile('rb')
try:
    # Run a viewer with an appropriate command line. Uncomment the mplayer
    # version if you would prefer to use mplayer instead of VLC
    cmdline = ['vlc', '--demux', 'h264', '-']
    #cmdline = ['mplayer', '-fps', '25', '-cache', '1024', '-']
    player = subprocess.Popen(cmdline, stdin=subprocess.PIPE)
    while True:
        # Repeatedly read 1k of data from the connection and write it to
        # the media player's stdin
        data = connection.read(1024)
        if not data:
            break
        player.stdin.write(data)
finally:
    connection.close()
    server_socket.close()
    player.terminate()

client (robot):

import socket
import time
import picamera

# Connect a client socket to my_server:8000 (change my_server to the
# hostname of your server)
client_socket = socket.socket()
client_socket.connect(('my_server', 8000))

# Make a file-like object out of the connection
connection = client_socket.makefile('wb')
try:
    camera = picamera.PiCamera()
    camera.resolution = (640, 480)
    camera.framerate = 24
    # Start a preview and let the camera warm up for 2 seconds
    camera.start_preview()
    time.sleep(2)
    # Start recording, sending the output to the connection for 60
    # seconds, then stop
    camera.start_recording(connection, format='h264')
    camera.wait_recording(60)
    camera.stop_recording()
finally:
    connection.close()
    client_socket.close()

Now I want to read the frames using opencv instead of VLC. Is there a way to do this?

Most answers I have seen involves running the raspi as a rtsp server and then accessing it with cv2.VideoCapture('rtsp://IPaddress:Port'). I want the raspi to be the client though.

Update: actually it'd be even better if there is a way to play the stream directly on a PyQt GUI. Essentially I'd like to make my own version of VLC...


问:
Hide "Contains Ads" label which is placed next to applications on play store
I have a published application on play store that doesn't contain ads and I found the "contains ads" label is placed next to my app. So I changed the settings from Privacy => App Content. And I told them that my app doesn't contain ads. but the label is still placed

So I want to know when it will reflect to play store and this label will be hidden?


问:
data structure for a pricing engine (Non dynamic)
I want to design a "pricing calculator" for a cloud platform that takes into account different "service Types (Infra or PaaS)", "VM sizes", "storage", "Compute units (a custom metric of cpu cores + RAM for PaaS services)". These options can be added in any order by customer with any combination.
ex:For Infra:  small (2 cpu cores + 2 GB RAM), medium (4 cpu cores + 4 GB),
large (6 CPU cores + 8 GB of RAM) and so on...
For Storage: by GB allocated (both pay as u go and pre-paid and post paid)
For PaaS: Compute Units. Ex: Provisioning  10 CU's per hour translates to 2 CPU cores and 4 GB of RAM.
I want a data structure that can represent all the above combinations of variables</p>


Title: What is the best approach to use swin_b pretrained model for feature extraction?

Body:
I'm currently using different types of pretrained models with a specific dataset containing images. As language and tecnology I'm using python and PyTorch.

I was following the pytorch documentation to proper implement the weights: https://pytorch.org/vision/stable/models/generated/torchvision.models.swin_b.html#torchvision.models.swin_b and https://pytorch.org/vision/stable/models/generated/torchvision.models.swin_b.html#torchvision.models.swin_b.

But, when I run using the swin_b pretrained model I'm getting this warning at the end of the execution:

Final Result
Final Raw matrix:
[[51, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 4, 558, 0, 0, 0, 437, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0], [6, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 51, 0, 0, 0, 37, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0], [1, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 207, 0, 0, 0, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [5, 0, 0, 69, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 3, 386, 0, 0, 0, 252, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0], [3, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 63, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [3, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 125, 0, 0, 0, 17, 0, 0, 0, 0, 0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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [3, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 357, 0, 0, 0, 69, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]]

Final Classification Report:
...\lib\site-packages\sklearn\metrics\_classification.py:1334: UndefinedMetricWarning: Precision and F-score are ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior._warn_prf(average, modifier, msg_start, len(result))

I've imported the model using the following command:

from torchvision.models import swin_b as SwinTransformer

And I've tried different approaches for weights parameter, as follow:

model = SwinTransformer(weights='DEFAULT')

model = SwinTransformer(weights='IMAGENET1K_V1')

I also tried to import the Swin_B_Weights using: import torchvision.models.Swin_B_Weights.

model = SwinTransformer(weights=Swin_B_Weights.DEFAULT)

model = SwinTransformer(weights=Swin_B_Weights.IMAGENET1K_V1)

But in the end, I'm always receiveing the same warning. Can someone help me with this issue? Thanks!


问:
LBP Feature Grafting with CNN Layer using Custom Layer
Can we add manual features extracted by LBP in CNN Layer with the help of Custom Layer or any other terminology.

In the hidden layer.


问:
.Net 7.0 arm64 installer broken?
Today I tried installing .net to learn basics of it. However, after running the installer I was not able to run dotnet commands in my zh shell. ( Command not found )

I am sure that the install was successful due to my installer logs:

However, I cannot find the dotnet exe file anywhere in my file system. Not in the default usr/local/share/dotnet that it should be.

Is there any other PATH that the Installer puts to dotnet files? I have no clue what I have done wrong. Just followed the recommended installer right off of Microsoft's site.

I have tried searching all my file system for an hour for the dotnet files, then searching the internet for other options for paths or what could have happened.

Expecting to find the file path and manually add it to my system path

Title: .Net 7.0 arm64 installer broken?


问:
often redirected to login page rather than authorization page

```<code>    import random
    import urllib.parse as urllibparse
    import spotipy
    from spotipy.oauth2 import SpotifyOAuth

 #   credentials
    Client_Id = <CLIENT_ID>
    Client_Secret = <CLIENT_SECRET>
    redirect_uri = 'http://localhost:5500/'
    scope = "playlist-modify-private playlist-modify-public"
    response_type = 'code'
    username = <USERNAME>

    randomNum =str(random.getrandbits(128))
    hash = int(randomNum,36)
    state =  hex(hash)

    spotifyToken = SpotifyOAuth(Client_Id,Client_Secret,redirect_uri,state,scope)

    auth_url = spotifyToken.get_authorize_url()
    print(auth_url)

    spotifyObject = spotipy.Spotify(auth_manager=spotifyToken)
    print(spotifyObject)

    playlistName = "random"
    playlistDescription = "just to check"

    spotifyObject.user_playlist_create(user=username,name=playlistName,public=True,description=playlistDescription)

</code>```

suggestions required

often redirected to login page rather than authorization page  pls suggest some solution to resolve this problem or suggest any other way.

Body:
    import random
    import urllib.parse as urllibparse
    import spotipy
    from spotipy.oauth2 import SpotifyOAuth

 #   credentials
    Client_Id = <CLIENT_ID>
    Client_Secret = <CLIENT_SECRET>
    redirect_uri = 'http://localhost:5500/'
    scope = "playlist-modify-private playlist-modify-public"
    response_type = 'code'
    username = <USERNAME>

    randomNum =str(random.getrandbits(128))
    hash = int(randomNum,36)
    state =  hex(hash)

    spotifyToken = SpotifyOAuth(Client_Id,Client_Secret,redirect_uri,state,scope)

    auth_url = spotifyToken.get_authorize_url()
    print(auth_url)

    spotifyObject = spotipy.Spotify(auth_manager=spotifyToken)
    print(spotifyObject)

    playlistName = "random"
    playlistDescription = "just to check"

    spotifyObject.user_playlist_create(user=username,name=playlistName,public=True,description=playlistDescription)

suggestions required

often redirected to login page rather than authorization page  pls suggest some solution to resolve this problem or suggest any other way.


问:
Grabbing an index to map around it to style my blogs page
I'm trying to style my blogs page for my website. I integrated my Contentful blog using API's and its all displayed correctly, but I just don't know how to target individual elements to style them individually. I would like to be able to style my main blogs page as a grid layout, attached is the specific grid layout I would like to achieve. I just don't know the code syntax to achieve this. I've been told I need to target the index and use .map but I'm still quite confused

[![the grid layout I want to achieve ][1]][1]

I would also like to be able to add tags to fetch the tags from my Contentful and display them on my blogs main page and on the individual slugs page but I dont know the syntax to fetch this data

```<code>import Footer from "../components/Footer/Footer";
import { createClient } from "contentful";
import BlogCard from "../components/BlogCard/BlogCard";

export async function getStaticProps() {
  const array = [1, 4, 9, 16];

  const map = array.map((x) => x * 2);

  const client = createClient({
    space: process.env.CONTENTFUL_SPACE_ID,
    accessToken: process.env.CONTENTFUL_ACCESS_TOKEN,
    previewacessToken: process.env.PREVIEW_ACCESS_TOKEN,
  });

  const res = await client.getEntries({ content_type: "menuItem" });
  return {
    props: {
      blog: res.items,
    },
  };
}

export default function Blog({ blog }) {
  return (
    <div>
      <div className="bg-[#F5f5f5] pt-16 max-md:pt-10 max-lg:pt-4">
        <div className="flex flex-col">
          <header className="z-10">
            <Navbar />{" "}
          </header>
          <main className="flex-1">
            <div className="relative left-1/2 mt-12 min-w[100vw] translate-x-[-50%]">
              <div className="relative mx-auto pb-30 lg:pb-30">
                <div className="px-8 md:px-8.5 lg:px-40">
                  <div className="mx-auto max-w-container">
                    <div className="max-md:w-full">
                      <div className="grid grid-cols-2 grid-rows-3 gap-10 mt-24 mb-32 h-full sm:grid-cols-2 sm:h-full sm:w-full md:mb-24 md:w-full max-lg:block max-md:mt-16 max-md:mb-4">
                        {/* {blog.map((index) => (
                          <BlogCard key={index} menuItem={index} />
                        ))} */}
                        {/* {blog.map((menuItem) => (
                          <BlogCard key={menuItem.sys.id} menuItem={menuItem} />
                        ))} */}
                        {blog.map((menuItem) => (
                          <BlogCard key={menuItem.sys.id} menuItem={menuItem} />
                        ))}
                      </div>
                    </div>
                  </div>
                  <Footer />
                </div>
              </div>
            </div>
          </main>
        </div>
      </div>
    </div>
  );````

  [1]: https://i.stack.imgur.com/YzU1P.png
```

Body:
I'm trying to style my blogs page for my website. I integrated my Contentful blog using API's and its all displayed correctly, but I just don't know how to target individual elements to style them individually. I would like to be able to style my main blogs page as a grid layout, attached is the specific grid layout I would like to achieve. I just don't know the code syntax to achieve this. I've been told I need to target the index and use .map but I'm still quite confused

[![the grid layout I want to achieve ][1]][1]

I would also like to be able to add tags to fetch the tags from my Contentful and display them on my blogs main page and on the individual slugs page but I dont know the syntax to fetch this data

import Footer from "../components/Footer/Footer";
import { createClient } from "contentful";
import BlogCard from "../components/BlogCard/BlogCard";

export async function getStaticProps() {
  const array = [1, 4, 9, 16];

  const map = array.map((x) => x * 2);

  const client = createClient({
    space: process.env.CONTENTFUL_SPACE_ID,
    accessToken: process.env.CONTENTFUL_ACCESS_TOKEN,
    previewacessToken: process.env.PREVIEW_ACCESS_TOKEN,
  });

  const res = await client.getEntries({ content_type: "menuItem" });
  return {
    props: {
      blog: res.items,
    },
  };
}

export default function Blog({ blog }) {
  return (

            <Navbar />{" "}

                        {/* {blog.map((index) => (
                          <BlogCard key={index} menuItem={index} />
                        ))} */}
                        {/* {blog.map((menuItem) => (
                          <BlogCard key={menuItem.sys.id} menuItem={menuItem} />
                        ))} */}
                        {blog.map((menuItem) => (
                          <BlogCard key={menuItem.sys.id} menuItem={menuItem} />
                        ))}

  );````

  [1]: https://i.stack.imgur.com/YzU1P.png


问:
Working with a List of Dictionaries in Python
I have a list of 300 dictionaries with the same format/structure. I am trying to print the same value from each dictionary with something like this:
(https://i.stack.imgur.com/Rk77o.png)but I get this error

How do I get the correspondent value to "value" since I can't subscript a number?

I am not sure how to move forward and am very new to coding but I've been told stack overflow is super helpful.


问:
Get the current selection from macOS Finder
It seems like the only way to get to the currently selected files/folders of the macOS Finder is via the Scripting Bridge. The SwiftScripting project provides some pre-generated extensions to use. The code is rather simple:

```<code>    public func getSelected() -> [NSURL] {

        guard let app = SBApplication(bundleIdentifier: "com.apple.finder") else {
            print("no app")
            return []
        }

        let finder = app as FinderApplication
        guard let result = finder.selection else {
                print("No items selected")
                return []
        }

        print("result", result)

        guard let selection = result.get() else {
            print("get failed: ", result.lastError() ?? "")
            return []
        }

        print("selection", selection)

        return []
    }
</code>```

But unfortunately the get of the selection fails

```<code>result <SBObject @0x600000d26310: selection of application "Finder" (6039)>
get failed:  Error Domain=NSOSStatusErrorDomain Code=-1743 "(null)" UserInfo={ErrorNumber=-1743}
</code>```

That error is errAEEventNotPermitted. Which suggests the app needs the correct entitlements. The temporary exception would not be allowed on the App Store - but should in theory be enough. The scripting targets would probably the way to go - but it seems virtually impossible to find the relevant docs on this.

```<code><dict>
    <key>com.apple.security.app-sandbox</key>
    <true/>
    <key>com.apple.security.files.user-selected.read-only</key>
    <true/>
    <key>com.apple.security.temporary-exception.apple-events</key>
    <array>
        <string>com.apple.finder</string>
    </array>
    <key>com.apple.security.scripting-targets</key>
    <dict>
        <key>com.apple.finder</key>
        <array>
            <string>???</string>
        </array>
    </dict>
</dict>
</code>```

What parts am I missing to get this working?

Update:

What I was missing was the permission in the Info.plist. The key Privacy - AppleEvents Sending Usage Description needs to be set. That makes the get call succeed.

To get this through the app store review though, setting com.apple.security.scripting-targets correctly would still be required.

I am still looking for information on what target configurations are available for the Finder.

Body:
It seems like the only way to get to the currently selected files/folders of the macOS Finder is via the Scripting Bridge. The SwiftScripting project provides some pre-generated extensions to use. The code is rather simple:

    public func getSelected() -> [NSURL] {

        guard let app = SBApplication(bundleIdentifier: "com.apple.finder") else {
            print("no app")
            return []
        }

        let finder = app as FinderApplication
        guard let result = finder.selection else {
                print("No items selected")
                return []
        }

        print("result", result)

        guard let selection = result.get() else {
            print("get failed: ", result.lastError() ?? "")
            return []
        }

        print("selection", selection)

        return []
    }

But unfortunately the get of the selection fails

result <SBObject @0x600000d26310: selection of application "Finder" (6039)>
get failed:  Error Domain=NSOSStatusErrorDomain Code=-1743 "(null)" UserInfo={ErrorNumber=-1743}

That error is errAEEventNotPermitted. Which suggests the app needs the correct entitlements. The temporary exception would not be allowed on the App Store - but should in theory be enough. The scripting targets would probably the way to go - but it seems virtually impossible to find the relevant docs on this.

<dict>
    <key>com.apple.security.app-sandbox</key>
    <true/>
    <key>com.apple.security.files.user-selected.read-only</key>
    <true/>
    <key>com.apple.security.temporary-exception.apple-events</key>
    <array>
        <string>com.apple.finder</string>
    </array>
    <key>com.apple.security.scripting-targets</key>
    <dict>
        <key>com.apple.finder</key>
        <array>
            <string>???</string>
        </array>
    </dict>
</dict>

What parts am I missing to get this working?

Update:

What I was missing was the permission in the Info.plist. The key Privacy - AppleEvents Sending Usage Description needs to be set. That makes the get call succeed.

To get this through the app store review though, setting com.apple.security.scripting-targets correctly would still be required.

I am still looking for information on what target configurations are available for the Finder.


问:
? zmq.libzmq imported from - Building 'dist\main.exe'. error: [WinError 87] the parameter is incorrect. PY2EXE
I want to convert my python file main.py into an executable. I'm using Py2exe to do this.
This is my code.
Setup for the conversion
`    from distutils.core import setup
import py2exe

```<code> setup(
 options = {'py2exe': {'bundle_files': 1}},
 windows = \[{'script': "main.py"}\],
 zipfile = None,
 )\`
</code>```

Main
`import cv2
import mediapipe as mp
import pyautogui

def show_webcam():
scale = 10

```<code>camera = cv2.VideoCapture(0)

face_mesh = mp.solutions.face_mesh.FaceMesh(refine_landmarks=True)
screen_w, screen_h = pyautogui.size()

while True:
    _, frame = camera.read()
    frame = cv2.flip(frame, 1)

    height, width, channels = frame.shape
    #cropping
    centerX, centerY = int(height/2), int(width/2)
    radiusX, radiusY = int(scale*height/100), int(scale*width/100)
    minX, maxX = centerX - radiusX, centerX + radiusX
    minY, maxY = centerY-radiusY, centerY+radiusY
    cropped = frame[minX:maxX, minY:maxY]
    resized_cropped = cv2.resize(cropped, (width, height))

    rgb_frame = cv2.cvtColor(resized_cropped, cv2.COLOR_BGR2RGB)
    output = face_mesh.process(rgb_frame)
    landmark_points = output.multi_face_landmarks
    # print(landmark_points)
    frame_h, frame_w, _ = resized_cropped.shape
    if landmark_points:
        landmarks = landmark_points[0].landmark
        for id, landmark in enumerate(landmarks[473:478]):
            x = int(landmark.x * frame_w)
            y = int(landmark.y * frame_h)
            cv2.circle(resized_cropped, (x, y), 3, (0, 255, 0))
            if id == 1:
                screen_x = screen_w / frame_w * x
                screen_y = screen_h / frame_h * y
                try:
                    pyautogui.moveTo(screen_x, screen_y)
                except pyautogui.FailSafeException:
                    print('Running code before exiting.')
                    break
                pyautogui.moveTo(screen_x, screen_y)
        # LEFT CLICK
        left = [landmarks[145], landmarks[159]]
        for landmark in left:
            x = int(landmark.x * frame_w)
            y = int(landmark.y * frame_h)
            cv2.circle(resized_cropped, (x, y), 3, (0, 255, 255))
        if (left[0].y - left[1].y) < 0.04:
            # print('click')
            pyautogui.click()
            pyautogui.sleep(1)

    cv2.imshow('Eyes Controlled Mouse', resized_cropped)
    key = cv2.waitKey(10)
    # if Esc key is press then break out of the loop
    if key == 27:
        break

camera.release()
cv2.destroyAllWindows()
</code>```

def main():
show_webcam()

if name == 'main':
main()`

If I run python main.py py2exe I get this error
? zmq.libzmq imported from - Building 'dist\main.exe'. error: [WinError 87] the parameter is incorrect.

Could anyone help me?

Body:
I want to convert my python file main.py into an executable. I'm using Py2exe to do this.
This is my code.
Setup for the conversion
`    from distutils.core import setup
import py2exe

 setup(
 options = {'py2exe': {'bundle_files': 1}},
 windows = \[{'script': "main.py"}\],
 zipfile = None,
 )\`

Main
`import cv2
import mediapipe as mp
import pyautogui

def show_webcam():
scale = 10

camera = cv2.VideoCapture(0)

face_mesh = mp.solutions.face_mesh.FaceMesh(refine_landmarks=True)
screen_w, screen_h = pyautogui.size()

while True:
    _, frame = camera.read()
    frame = cv2.flip(frame, 1)

    height, width, channels = frame.shape
    #cropping
    centerX, centerY = int(height/2), int(width/2)
    radiusX, radiusY = int(scale*height/100), int(scale*width/100)
    minX, maxX = centerX - radiusX, centerX + radiusX
    minY, maxY = centerY-radiusY, centerY+radiusY
    cropped = frame[minX:maxX, minY:maxY]
    resized_cropped = cv2.resize(cropped, (width, height))

    rgb_frame = cv2.cvtColor(resized_cropped, cv2.COLOR_BGR2RGB)
    output = face_mesh.process(rgb_frame)
    landmark_points = output.multi_face_landmarks
    # print(landmark_points)
    frame_h, frame_w, _ = resized_cropped.shape
    if landmark_points:
        landmarks = landmark_points[0].landmark
        for id, landmark in enumerate(landmarks[473:478]):
            x = int(landmark.x * frame_w)
            y = int(landmark.y * frame_h)
            cv2.circle(resized_cropped, (x, y), 3, (0, 255, 0))
            if id == 1:
                screen_x = screen_w / frame_w * x
                screen_y = screen_h / frame_h * y
                try:
                    pyautogui.moveTo(screen_x, screen_y)
                except pyautogui.FailSafeException:
                    print('Running code before exiting.')
                    break
                pyautogui.moveTo(screen_x, screen_y)
        # LEFT CLICK
        left = [landmarks[145], landmarks[159]]
        for landmark in left:
            x = int(landmark.x * frame_w)
            y = int(landmark.y * frame_h)
            cv2.circle(resized_cropped, (x, y), 3, (0, 255, 255))
        if (left[0].y - left[1].y) < 0.04:
            # print('click')
            pyautogui.click()
            pyautogui.sleep(1)

    cv2.imshow('Eyes Controlled Mouse', resized_cropped)
    key = cv2.waitKey(10)
    # if Esc key is press then break out of the loop
    if key == 27:
        break

camera.release()
cv2.destroyAllWindows()

def main():
show_webcam()

if name == 'main':
main()`

If I run python main.py py2exe I get this error
? zmq.libzmq imported from - Building 'dist\main.exe'. error: [WinError 87] the parameter is incorrect.

Could anyone help me?


问:
Python argsparse to filter for a region
```<code>  parser.add_argument('-r', '--regions', nargs="*", choices=["us-east-1", "us-west-2"], default=["us-east-1"],
                        type=str)
    args = parser.parse_args()

    if args.action == 'list':
        list_response = secrets_session.list_secrets()
        print(json.dumps(list_response, indent=4, default=str))

</code>```

ask- in the above code,i have to list only for the specific region input by the user in cli.how can send the choices from args parser?
cmd i am trying is not filtering the region- python -m file -a list -r 'us-east-1'

i have added the list with the choices and tried to input in the cmdline,but looks like i need to add a if condition or soemwhere to pick the specific choices.

Title: Python argsparse to filter for a region

Body:
  parser.add_argument('-r', '--regions', nargs="*", choices=["us-east-1", "us-west-2"], default=["us-east-1"],
                        type=str)
    args = parser.parse_args()

    if args.action == 'list':
        list_response = secrets_session.list_secrets()
        print(json.dumps(list_response, indent=4, default=str))

ask- in the above code,i have to list only for the specific region input by the user in cli.how can send the choices from args parser?
cmd i am trying is not filtering the region- python -m file -a list -r 'us-east-1'

i have added the list with the choices and tried to input in the cmdline,but looks like i need to add a if condition or soemwhere to pick the specific choices.


问:
Mapbox problems with user position and Map on Click in Android Studio
The position of the user is not displayed. The permission is requested and the map is opened. Furthermore, the app is restarted when clicking on the map.

The Mapbox 9.0.2 with Java code was used.

```<code>
public void onMapReady(@NonNull MapboxMap mapboxMap) {
        this.map = mapboxMap;
        map.addOnMapClickListener(this);
        mapboxMap.setStyle(Style.LIGHT, new Style.OnStyleLoaded() {
            @Override
            public void onStyleLoaded(@NonNull Style style) {

                enaleCommponent(style);
            }

        });
    }

    @SuppressLint("SuspiciousIndentation")
    public void enaleCommponent(@NonNull Style loadedMapStyle){
        try {
            if (PermissionsManager.areLocationPermissionsGranted(this)) {
                locationComponent = map.getLocationComponent();
                locationComponent.activateLocationComponent(LocationComponentActivationOptions.builder(this, loadedMapStyle).build());
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
                locationComponent.setLocationComponentEnabled(true);
                locationComponent.zoomWhileTracking(14,3000);
                locationComponent.setCameraMode(CameraMode.TRACKING);
                locationComponent.setRenderMode(RenderMode.COMPASS);
                locationComponent.tiltWhileTracking(45);
            }else{
                permissionsManager= new PermissionsManager(this);
                permissionsManager.requestLocationPermissions(this);
            }
        }
        catch (Exception e){
            Log.e("ERR_LOAD_MAP",e.getMessage());
        }
    }
</code>```

Body:
The position of the user is not displayed. The permission is requested and the map is opened. Furthermore, the app is restarted when clicking on the map.

The Mapbox 9.0.2 with Java code was used.

public void onMapReady(@NonNull MapboxMap mapboxMap) {
        this.map = mapboxMap;
        map.addOnMapClickListener(this);
        mapboxMap.setStyle(Style.LIGHT, new Style.OnStyleLoaded() {
            @Override
            public void onStyleLoaded(@NonNull Style style) {

                enaleCommponent(style);
            }

        });
    }

    @SuppressLint("SuspiciousIndentation")
    public void enaleCommponent(@NonNull Style loadedMapStyle){
        try {
            if (PermissionsManager.areLocationPermissionsGranted(this)) {
                locationComponent = map.getLocationComponent();
                locationComponent.activateLocationComponent(LocationComponentActivationOptions.builder(this, loadedMapStyle).build());
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
                locationComponent.setLocationComponentEnabled(true);
                locationComponent.zoomWhileTracking(14,3000);
                locationComponent.setCameraMode(CameraMode.TRACKING);
                locationComponent.setRenderMode(RenderMode.COMPASS);
                locationComponent.tiltWhileTracking(45);
            }else{
                permissionsManager= new PermissionsManager(this);
                permissionsManager.requestLocationPermissions(this);
            }
        }
        catch (Exception e){
            Log.e("ERR_LOAD_MAP",e.getMessage());
        }
    }


问:
Player Y location messed up
I have a resizable canvas in which a player is drawn. For some reason, the player will go off screen if the screen is too tall. This usually occurs in fullscreen mode, where the game will mostly be played. I've tried to change how it's calculated based on mx and my, but nothing seems to work.

Fullscreen, where the bug is happening: https://editor.p5js.org/Voxel_/full/61_2FX_-4

Code (it works fine in the preview canvas): https://editor.p5js.org/Voxel_/sketches/61_2FX_-4

Title: Player Y location messed up


问:
CkEditor html to docx conversion - 3 column header
I have tried various HTML on the ckeditor demo page (https://docx-converter.cke-cs.com/demo) attempting to get a reliable 2 (Left, Right) or 3 column (Left, Center, Right) layout for the header, but am unable to get it work due to ckeditor docx conversion only supporting a limited number of css properties (https://ckeditor.com/docs/ckeditor5/latest/features/export-word.html#supported-css-properties)

So I thought perhaps a plain table layout would work. However, the table layout suffers from borders that I cannot seem to remove.

To make generating HTML easier, I found this ckeditor Import from word word-to-html converter (https://ckeditor.com/import-from-word/demo/#rest-api) so we can see what styles are actually accepted by creating a document in word and converting it to html. Then when it gets converted back to word we will know the html works.

Any thoughts or solutions would be greatly appreciated!


问:
Threejs color hue of renderer, scene or material
With that, all my imported material get a higher saturation than the original, and also the color hue seems to be wrong.

Is there a way i can work with color hue/saturation of my renderer?

If not, is there a way to work with hue/saturation on the imported material? (all materials come from http requests with the correct colors)

This is my renderer:

import * as THREE from 'three';

export function makeRenderer() {
    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.setClearColor('#000', 0.1);
    renderer.outputEncoding =  THREE.sRGBEncoding;

    return renderer;
}```
</div>
</div>
</p>
<p><strong>This is my MTL loader:</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { makeObjLoader } from '../factories';
import { FileUtil } from '../utils/FileUtil';
import { UrlUtil } from '../utils/UrlUtil';
import { MTLLoader } from 'three/examples/jsm/loaders/MTLLoader';
import * as THREE from 'three';
import { UrlUtil } from '../../utils/UrlUtil';

//CREATES THE LOADER TO BE USED IN MtlRemoteStrategy
export const makeMtlRemoteLoader = (files = []) => {
    const loadingManagerMTL = new THREE.LoadingManager();

    loadingManagerMTL.setURLModifier((url) => {
        const currentFile = files.find((f) => url.includes(f.name))
        const newUrl = `${UrlUtil.getRemoteSharedPath()}/${currentFile.name}`

        return newUrl
    });

    return new MTLLoader(loadingManagerMTL);
};

export class MtlRemoteStrategy {
    constructor(scene, files = [], loader) {
        this.scene = scene;
        this.files = files;
        this.loader = loader;
    }

    load() {
        const mtlObjectUrl = UrlUtil.getRemoteObjectUrl(FileUtil.getFileByText(this.files, '.mtl'))
        const objObjectUrl = UrlUtil.getRemoteObjectUrl(FileUtil.getFileByText(this.files, '.obj'))

        this.loader.load(mtlObjectUrl, (materials) => {
            materials.preload();

            makeObjLoader()
                .setMaterials(materials)
                .load(objObjectUrl, (model) => {
                    model.position.set(0, 0, 0);
                    this.scene.add(model);
                });
        });
    }
}</code>```

Here's what happens with the colors on the rendered object:

Body:
With that, all my imported material get a higher saturation than the original, and also the color hue seems to be wrong.

Is there a way i can work with color hue/saturation of my renderer?

If not, is there a way to work with hue/saturation on the imported material? (all materials come from http requests with the correct colors)

This is my renderer:

import * as THREE from 'three';

export function makeRenderer() {
    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.setClearColor('#000', 0.1);
    renderer.outputEncoding =  THREE.sRGBEncoding;

    return renderer;
}

This is my MTL loader:

import { makeObjLoader } from '../factories';
import { FileUtil } from '../utils/FileUtil';
import { UrlUtil } from '../utils/UrlUtil';
import { MTLLoader } from 'three/examples/jsm/loaders/MTLLoader';
import * as THREE from 'three';
import { UrlUtil } from '../../utils/UrlUtil';

//CREATES THE LOADER TO BE USED IN MtlRemoteStrategy
export const makeMtlRemoteLoader = (files = []) => {
    const loadingManagerMTL = new THREE.LoadingManager();

    loadingManagerMTL.setURLModifier((url) => {
        const currentFile = files.find((f) => url.includes(f.name))
        const newUrl = `${UrlUtil.getRemoteSharedPath()}/${currentFile.name}`

        return newUrl
    });

    return new MTLLoader(loadingManagerMTL);
};

export class MtlRemoteStrategy {
    constructor(scene, files = [], loader) {
        this.scene = scene;
        this.files = files;
        this.loader = loader;
    }

    load() {
        const mtlObjectUrl = UrlUtil.getRemoteObjectUrl(FileUtil.getFileByText(this.files, '.mtl'))
        const objObjectUrl = UrlUtil.getRemoteObjectUrl(FileUtil.getFileByText(this.files, '.obj'))

        this.loader.load(mtlObjectUrl, (materials) => {
            materials.preload();

            makeObjLoader()
                .setMaterials(materials)
                .load(objObjectUrl, (model) => {
                    model.position.set(0, 0, 0);
                    this.scene.add(model);
                });
        });
    }
}

Here's what happens with the colors on the rendered object:


问:
Changing view visibility when drawing a view to a canvas/bitmap in android
I am trying to capture a "partial screenshot" to an image file by drawing a view to a bitmap canvas, so that it can then be shared.

There are some child views that are initially visible and I need to hide (e.g. the card holding the button that triggers this function), and some other views that are initially hidden and I only want to show in the outputted image (e.g. "Powered by..." text).

The code below is mostly working, but the views that are initially hidden and are being programmatically shown are not drawn to the canvas. The views that I'm programmatically hiding do get hidden and not drawn on the canvas but the layout isn't updated to account for the fact they're no longer visible (there's just a blank space where they were)

I've tried invalidate() and requestLayout(), but I don't think these do anything until the system decides to redraw, which doesn't happen until after I've drawn the view to the canvas.

How can I modify a view, capture it to an image, then return the view to it's initial state, without the user seeing those changes on screen (only in the captured image)?

```<code>      binding.cardRecording.setVisibility(View.GONE);
            binding.cardHistory.setVisibility(View.GONE);
            binding.getRoot().setBackground(ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.snowflakes_background, null));
            binding.getRoot().setBackgroundTintList(ColorStateList.valueOf(ColorUtils.setAlphaComponent(primaryColor, 20)));
            binding.getRoot().setBackgroundTintMode(PorterDuff.Mode.SRC_OUT);
            binding.tvHeader.setTextColor(ContextCompat.getColor(mContext, R.color.grey_font));
            binding.tvHeader.setText(getName());
            binding.tvHeader.setVisibility(View.VISIBLE);
            binding.tvPoweredBy.setVisibility(View.VISIBLE);
            binding.ivLogo.setVisibility(View.VISIBLE);

            Bitmap bitmap;
            Canvas canvas;
            View view2 = binding.getRoot();
            bitmap = Bitmap.createBitmap(view2.getWidth(), view2.getHeight(), Bitmap.Config.ARGB_8888);
            canvas = new Canvas(bitmap);
            canvas.drawColor(Color.WHITE);
            view2.draw(canvas);

            File storageDir = mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES);

            File outFile = new File(storageDir, "temp.png");
            try {
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(outFile));
                Uri uri = FileProvider.getUriForFile(mContext, fileprovider,outFile);
                Intent intent = new Intent(Intent.ACTION_SEND);

                intent.putExtra(Intent.EXTRA_STREAM, uri);

                // setting type to image
                intent.setType("image/png");

                // calling startactivity() to share
                startActivity(Intent.createChooser(intent, "Share Via"));
            } catch (FileNotFoundException e) {

            }
            binding.cardRecording.setVisibility(View.GONE);
            binding.cardHistory.setVisibility(View.VISIBLE);
                 binding.getRoot().setBackground(null);
            binding.tvHeader.setVisibility(View.GONE);
            binding.tvPoweredBy.setVisibility(View.GONE);
            binding.ivLogo.setVisibility(View.GONE);
</code>```

Body:
I am trying to capture a "partial screenshot" to an image file by drawing a view to a bitmap canvas, so that it can then be shared.

There are some child views that are initially visible and I need to hide (e.g. the card holding the button that triggers this function), and some other views that are initially hidden and I only want to show in the outputted image (e.g. "Powered by..." text).

The code below is mostly working, but the views that are initially hidden and are being programmatically shown are not drawn to the canvas. The views that I'm programmatically hiding do get hidden and not drawn on the canvas but the layout isn't updated to account for the fact they're no longer visible (there's just a blank space where they were)

I've tried invalidate() and requestLayout(), but I don't think these do anything until the system decides to redraw, which doesn't happen until after I've drawn the view to the canvas.

How can I modify a view, capture it to an image, then return the view to it's initial state, without the user seeing those changes on screen (only in the captured image)?

      binding.cardRecording.setVisibility(View.GONE);
            binding.cardHistory.setVisibility(View.GONE);
            binding.getRoot().setBackground(ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.snowflakes_background, null));
            binding.getRoot().setBackgroundTintList(ColorStateList.valueOf(ColorUtils.setAlphaComponent(primaryColor, 20)));
            binding.getRoot().setBackgroundTintMode(PorterDuff.Mode.SRC_OUT);
            binding.tvHeader.setTextColor(ContextCompat.getColor(mContext, R.color.grey_font));
            binding.tvHeader.setText(getName());
            binding.tvHeader.setVisibility(View.VISIBLE);
            binding.tvPoweredBy.setVisibility(View.VISIBLE);
            binding.ivLogo.setVisibility(View.VISIBLE);

            Bitmap bitmap;
            Canvas canvas;
            View view2 = binding.getRoot();
            bitmap = Bitmap.createBitmap(view2.getWidth(), view2.getHeight(), Bitmap.Config.ARGB_8888);
            canvas = new Canvas(bitmap);
            canvas.drawColor(Color.WHITE);
            view2.draw(canvas);

            File storageDir = mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES);

            File outFile = new File(storageDir, "temp.png");
            try {
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(outFile));
                Uri uri = FileProvider.getUriForFile(mContext, fileprovider,outFile);
                Intent intent = new Intent(Intent.ACTION_SEND);

                intent.putExtra(Intent.EXTRA_STREAM, uri);

                // setting type to image
                intent.setType("image/png");

                // calling startactivity() to share
                startActivity(Intent.createChooser(intent, "Share Via"));
            } catch (FileNotFoundException e) {

            }
            binding.cardRecording.setVisibility(View.GONE);
            binding.cardHistory.setVisibility(View.VISIBLE);
                 binding.getRoot().setBackground(null);
            binding.tvHeader.setVisibility(View.GONE);
            binding.tvPoweredBy.setVisibility(View.GONE);
            binding.ivLogo.setVisibility(View.GONE);


问:
Write a Bayesian Network in BIFXML file
I am trying to generate random Bayesian Networks using pgmpy library and save them into BIFXML file using XMLBIFWriter.

My code so far is:

```<code>model = BayesianModel.get_random(10, 0.5, 2)
writer = XMLBIFWriter(model)
writer.get_definition()
writer.get_properties()
writer.get_states()
writer.get_values()
writer.get_variables()
writer.write_xmlbif('test.xml')
</code>```

but I am getting this error: TypeError: cannot serialize 1 (type int)
Does this error occur because my variables(nodes) are ints? How can I solve this? Thank you!

Edit: I solved it. Turns out XMLBIFWriter is not compatible with the BN format you get from get_random() function so code in XMLBIFWriter needs to be changed. More specifically boofar.text = foobar needs to be replaced with boofar.text = str(foobar)

Title: Write a Bayesian Network in BIFXML file

Body:
I am trying to generate random Bayesian Networks using pgmpy library and save them into BIFXML file using XMLBIFWriter.

My code so far is:

model = BayesianModel.get_random(10, 0.5, 2)
writer = XMLBIFWriter(model)
writer.get_definition()
writer.get_properties()
writer.get_states()
writer.get_values()
writer.get_variables()
writer.write_xmlbif('test.xml')

but I am getting this error: TypeError: cannot serialize 1 (type int)
Does this error occur because my variables(nodes) are ints? How can I solve this? Thank you!

Edit: I solved it. Turns out XMLBIFWriter is not compatible with the BN format you get from get_random() function so code in XMLBIFWriter needs to be changed. More specifically boofar.text = foobar needs to be replaced with boofar.text = str(foobar)


问:
Tooling to test complicated SQL queries in python
I inherited a legacy Python project that is essentially a small CRUD service. The difficulty is that it has a hand rolled data layer. It is a few hundred lines of manually written SQL with no test coverage. I need to modify some of the functionality, but before I do that I would love to introduce some testing for the data layer specifically.

Because there's zero abstraction in the data layer, I plan to:

Generate a known good set of data.

Populate a test database (Postgres).

Run my tests/asserts.

Drop the data.

My questions:

Is there a better approach that I'm missing?

Is there any tooling that I can leverage for this? Python preferred but not mandatory.


问:
Add multiple categories with the category badge on the publication widget
Elementor offers a publishing widget to display articles. I use it to display personalized posts : referencing. These listings all have categories, for example "Bar", Hotel".

Elementor offers via the publishing widget a card style, which allows to display a badge. By default, this badge displays only one category.

I read a lot of topics on the Internet, for example on this GitHub.

I tried to create plugins with this code inside

```<code>
add_action( 'elementor/widget/posts/skins_init', function( $widget ) {

    class issue6480_skin extends \ElementorPro\Modules\Posts\Skins\Skin_Cards {
        protected function render_badge() {
            $taxonomy = $this->get_instance_value( 'badge_taxonomy' );
            if ( empty( $taxonomy ) ) {
                return;
            }
            $terms = get_the_terms( get_the_ID(), $taxonomy );
            if ( ! is_array( $terms ) ) {
                return;
            }
            ?><div class="elementor-post__badges"><?php
            foreach( $terms as $term ) : ?>
                <div class="elementor-post__badge"><?php echo $term->name; ?></div>
            <?php endforeach; ?>
            </div>
            <?php
        }

        public function get_id() {
            return 'cards_multi_badge';
        }

        public function get_title() {
            return __( 'Cards Multi Badge', 'elementor-pro' );
        }
    }

    // register the skin to the posts widget
    $widget->add_skin( new issue6480_skin( $widget ) );
} );
</code>```

But it is impossible to make multiple categories work and display them. Do you have any idea which files I should turn to in order to create this code? Thanks

Body:
Elementor offers a publishing widget to display articles. I use it to display personalized posts : referencing. These listings all have categories, for example "Bar", Hotel".

Elementor offers via the publishing widget a card style, which allows to display a badge. By default, this badge displays only one category.

I read a lot of topics on the Internet, for example on this GitHub.

I tried to create plugins with this code inside

add_action( 'elementor/widget/posts/skins_init', function( $widget ) {

    class issue6480_skin extends \ElementorPro\Modules\Posts\Skins\Skin_Cards {
        protected function render_badge() {
            $taxonomy = $this->get_instance_value( 'badge_taxonomy' );
            if ( empty( $taxonomy ) ) {
                return;
            }
            $terms = get_the_terms( get_the_ID(), $taxonomy );
            if ( ! is_array( $terms ) ) {
                return;
            }
            ?>
<?php
            foreach( $terms as $term ) : ?>

<?php echo $term->name; ?>

            <?php endforeach; ?>

            <?php
        }

        public function get_id() {
            return 'cards_multi_badge';
        }

        public function get_title() {
            return __( 'Cards Multi Badge', 'elementor-pro' );
        }
    }

    // register the skin to the posts widget
    $widget->add_skin( new issue6480_skin( $widget ) );
} );

But it is impossible to make multiple categories work and display them. Do you have any idea which files I should turn to in order to create this code? Thanks


问:
bar charts with rounded bottom react chart js
I am trying to implement a bar chart using react chartjs and chartjs 2  my data to bar chart looks like this

```<code>dataSetCurrencies = {
    labels: ['₹', '$', '€', '£'],
    datasets: [
      {
        label: 'Dataset',
        data: [512364, 820847, 969833, 395342],
        backgroundColor: '#63ABFD',
        borderColor: '#165BAA',
        borderWidth:3,
        borderSkipped: false,
        borderRadius: 80,
      }
    ]
  };
 options = {

    plugins: {
      title: {
        display: false,
        text:'Total sales Currency Wise',
      },
      legend: {
        display: false
    },
    },
    animation: false,
    scales: {
        y: {
            ticks: {
              stepSize: 100000
            },
            grid: {
              color: '#ffffff1f',
          },
          beginAtZero: false
        },
        x: {
          grid: {
            color: '#ffffff1f',
        }
      },
    },
  }
</code>```

so far i was able to achieve the top rounded portion but the bottom is sticked to the x axis and is not rounded.Is there a way to fix this.My graph is attached

Body:
I am trying to implement a bar chart using react chartjs and chartjs 2  my data to bar chart looks like this

dataSetCurrencies = {
    labels: ['₹', '$', '€', '£'],
    datasets: [
      {
        label: 'Dataset',
        data: [512364, 820847, 969833, 395342],
        backgroundColor: '#63ABFD',
        borderColor: '#165BAA',
        borderWidth:3,
        borderSkipped: false,
        borderRadius: 80,
      }
    ]
  };
 options = {

    plugins: {
      title: {
        display: false,
        text:'Total sales Currency Wise',
      },
      legend: {
        display: false
    },
    },
    animation: false,
    scales: {
        y: {
            ticks: {
              stepSize: 100000
            },
            grid: {
              color: '#ffffff1f',
          },
          beginAtZero: false
        },
        x: {
          grid: {
            color: '#ffffff1f',
        }
      },
    },
  }

so far i was able to achieve the top rounded portion but the bottom is sticked to the x axis and is not rounded.Is there a way to fix this.My graph is attached


问:
Dynamic data variable names and assigning value [JavaScript]
Let me get straight to the point. Iam trying to use a data variable name dynamic with respect to a condition.

```<code>let nameOfDataVariable = condition ? 'a' : 'b');
this.nameOfDataVariable = true;
</code>```

What iam trying to basically achieve is use the string value inbetween the 'this.' and '=true'. I have gone through a few topics but couldn't get it right. Any help would be appreciated

Body:
Let me get straight to the point. Iam trying to use a data variable name dynamic with respect to a condition.

let nameOfDataVariable = condition ? 'a' : 'b');
this.nameOfDataVariable = true;

What iam trying to basically achieve is use the string value inbetween the 'this.' and '=true'. I have gone through a few topics but couldn't get it right. Any help would be appreciated