问:
Mastercard payment api's are giving 503 in sandbox
I have been trying for about a month now to integrate mastercard api's in my flutter app but all of them are giving me 503 error and flutter debugger gives this and it's on api response

```<code>FormatException (FormatException: Unexpected character (at character 1)
<HTML><HEAD>
^
)
</code>```

Further printing out the error tells this which exactly matches to the node.js api response

```<code>flutter: <HTML><HEAD>
flutter: <TITLE>Service Unavailable</TITLE>
flutter: </HEAD><BODY>
flutter: <H1>Service Unavailable - Zero size object</H1>
flutter: The server is temporarily unable to service your request.  Please try again
flutter: later.<P>
flutter: Reference #15.11a4c017.1671895863.83e1579a
flutter: </BODY></HTML>
</code>```

The api url I'm calling is https://sandbox.api.mastercard.com/hostedcheckout/v2/paymentform
or this in other file https://sandbox.api.mastercard.com/clicktopay/v2/pay
I've tried multiple sandbox accounts but still same results.
I've tried Click to Pay, Hosted Checkout, Mastercard payment gateway services (MPGS) but same results.

If anyone has done it in flutter or called restful api in any language or made their own middleware in some language then please help me out.

Body:
I have been trying for about a month now to integrate mastercard api's in my flutter app but all of them are giving me 503 error and flutter debugger gives this and it's on api response

FormatException (FormatException: Unexpected character (at character 1)

^
)

Further printing out the error tells this which exactly matches to the node.js api response

flutter:
flutter: <TITLE>Service Unavailable</TITLE>
flutter:
flutter:
Service Unavailable - Zero size object

flutter: The server is temporarily unable to service your request.  Please try again
flutter: later.

flutter: Reference #15.11a4c017.1671895863.83e1579a
flutter:

The api url I'm calling is https://sandbox.api.mastercard.com/hostedcheckout/v2/paymentform
or this in other file https://sandbox.api.mastercard.com/clicktopay/v2/pay
I've tried multiple sandbox accounts but still same results.
I've tried Click to Pay, Hosted Checkout, Mastercard payment gateway services (MPGS) but same results.

If anyone has done it in flutter or called restful api in any language or made their own middleware in some language then please help me out.


来源: stackexchange

问:
Reset Android Room database instance after restore
I am able to successfully backup and restore my room database using the method from the following answer. The issue is that now I have to close my app and open it to get the restored data. Before closing and reopening I am still seeing the old data from the database that was replaced. Is there a way to reinitialize the database instance and associated flows? When I try to close the database I am met with the same errors from the question I linked to.</p>

ContentLicense: CC BY-SA 4.0


问:
Create axios HLS stream from dynamic image in node
I want to create an m3u8 (HLS) stream from the dynamic image supplied via URL. I managed to find many examples of storing local images however not many where I can convert one type of stream into another. Bdw, the picture from the link is dynamic just often there is not much action.

Here is what I'm doing at the moment:

const express = require("express");
const axios = require("axios");
const app = express();

app.get("/", async (req, res) => {
  try {
    const cam = await axios({
      url: "http://sydneycitywebcam.com/scw.php",
      method: "GET",
      responseType: "stream"
    });

    const stream = cam.data;
    stream.pipe(res);
  } catch (e) {
    console.log(e);
    res.sendStatus(500);
  }
});

app.listen(8888);```

Here is my codesandbox in Express & Node:

https://codesandbox.io/s/dawn-fire-hkugw1?file=/src/index.js:0-390

I used this for a reference: https://gist.github.com/mharsch/5188206

I'm also using this site to find out if the stream is valid:

https://developer-tools.jwplayer.com/stream-tester

Thanks

Body:
I want to create an m3u8 (HLS) stream from the dynamic image supplied via URL. I managed to find many examples of storing local images however not many where I can convert one type of stream into another. Bdw, the picture from the link is dynamic just often there is not much action.

Here is what I'm doing at the moment:

const express = require("express");
const axios = require("axios");
const app = express();

app.get("/", async (req, res) => {
  try {
    const cam = await axios({
      url: "http://sydneycitywebcam.com/scw.php",
      method: "GET",
      responseType: "stream"
    });

    const stream = cam.data;
    stream.pipe(res);
  } catch (e) {
    console.log(e);
    res.sendStatus(500);
  }
});

app.listen(8888);

Here is my codesandbox in Express & Node:

https://codesandbox.io/s/dawn-fire-hkugw1?file=/src/index.js:0-390

I used this for a reference: https://gist.github.com/mharsch/5188206

I'm also using this site to find out if the stream is valid:

https://developer-tools.jwplayer.com/stream-tester

Thanks


问:
Possible to perform GitHub OAuth 2 login with Firebase from Swagger UI?
I'd like to allow users of the Swagger UI provided by my app to be able to log in with GitHub.

I'm using Firebase Auth with GitHub as sign-in method.

The official example by Google has no authorizationUrl for the implicit flow which leads to Swagger UI running in an error when the Authorize button is clicked:

Is it possible to configure a v3 security scheme in a way that when the user clicks the Authorize button, the GitHub login popup appears like in the UI with the firebase library?


问:
Can I set a global State from getInitProps in nextjs _app.tsx?
and I am really stuck on one of the concepts

Our app has a global context, and I am trying to read the ctx.referer from getInitProps and set it to the gloabl context, both the context and the getInitProps are available in the _app.tsx.

Below is how it is setup, I am not sure what is the right approach in that case?

PS. useReferrer is inside of the ManagedUIContext

Thanks in advance!

```<code>import App from 'next/app'
import type { AppProps } from 'next/app'
import { ManagedUIContext, useReferrer } from '@components/ui/context'
import { Head } from '@components/common'

    const MyApp = ({ Component, pageProps, router }: AppProps) => {
      const Layout = (Component as any).Layout || Noop
      const { setReferrers } = useReferrer()

      return (
        <>
          <Head />
          <ManagedUIContext>
            <Layout pageProps={pageProps}>
              <Component {...pageProps} />
            </Layout>
          </ManagedUIContext>
        </>
      )
    }

    MyApp.getInitialProps = async (appContext: any) => {
      const appProps = await App.getInitialProps(appContext)
      if (appContext.ctx) {
        const { referer } = appContext.ctx.req.headers
        // i would like to set the state here ex:setReferrers(referer)
        return {
          pageProps: {
            ...appProps.pageProps,
            referer,
          },
        }
      }

      return {}
    }
    export default MyApp
</code>```

Body:
and I am really stuck on one of the concepts

Our app has a global context, and I am trying to read the ctx.referer from getInitProps and set it to the gloabl context, both the context and the getInitProps are available in the _app.tsx.

Below is how it is setup, I am not sure what is the right approach in that case?

PS. useReferrer is inside of the ManagedUIContext

Thanks in advance!

import App from 'next/app'
import type { AppProps } from 'next/app'
import { ManagedUIContext, useReferrer } from '@components/ui/context'
import { Head } from '@components/common'

    const MyApp = ({ Component, pageProps, router }: AppProps) => {
      const Layout = (Component as any).Layout || Noop
      const { setReferrers } = useReferrer()

      return (
        <>

          <ManagedUIContext>
            <Layout pageProps={pageProps}>
              <Component {...pageProps} />
            </Layout>
          </ManagedUIContext>
        </>
      )
    }

    MyApp.getInitialProps = async (appContext: any) => {
      const appProps = await App.getInitialProps(appContext)
      if (appContext.ctx) {
        const { referer } = appContext.ctx.req.headers
        // i would like to set the state here ex:setReferrers(referer)
        return {
          pageProps: {
            ...appProps.pageProps,
            referer,
          },
        }
      }

      return {}
    }
    export default MyApp


问:
With jetpack compose how can I dump an item from an array into mutableState to be used
For example, if I have a data class of

```<code>data class RaceViewModelItem(
    val location: String,
    val raceDescription: String,
    val title: String
)
</code>```

In my body I have

```<code>  LazyRow{
        items(data) { item ->
              ...
      }
</code>```

I want to dump item into a mutable state so it's just one.

I found I can use var sampleData by remember { mutableStateOf(arrayOf<RaceViewModelItem>()) }, but if I want to pass that data to another view I'm getting a mismatch.

```<code>View I want to send my data to:

@Composable
fun HeroCard(
    data: RaceViewModelItem
) {
</code>```

Type mismatch: inferred type is RaceViewModelItem but Array<RaceViewModelItem> was expected

Body:
For example, if I have a data class of

data class RaceViewModelItem(
    val location: String,
    val raceDescription: String,
    val title: String
)

In my body I have

  LazyRow{
        items(data) { item ->
              ...
      }

I want to dump item into a mutable state so it's just one.

I found I can use var sampleData by remember { mutableStateOf(arrayOf<RaceViewModelItem>()) }, but if I want to pass that data to another view I'm getting a mismatch.

View I want to send my data to:

@Composable
fun HeroCard(
    data: RaceViewModelItem
) {

Type mismatch: inferred type is RaceViewModelItem but Array<RaceViewModelItem> was expected


问:
Go HTML page repeats the content inside it on each reload
I'm in the process of creating a go package that's a mix of django, express and gin and I'm already having many difficulties but it's one that's been so annoying for the past couple days.
When reloading an html page that's served via the Ctx.HTML() or Ctx.Template() funcs it repeats it's content. With a result like this:
The problem GIF

I'll leave the link to the issue here -> /dpouris/goster/issues/5

I've tried pretty much every type of test and manual printing of errors and whatnot but have yet to find a solution :/

Any help would be greatly appreciated thank you! :)


问:
Passing a ufloat argument to a numpy mathematical function
I've been using the uncertainties library for calculation of the gaussian error propagation with good results for quite some time.

The problem is that I use the numpy library for all mathematical functions like sin(), sqrt(), and so on. Which does not support any arguments of  ufloat type. Thus making it impossible to calculate the error propagation of a function with any mathematical function implemented with numpy.

If I am not mistaken a simple typecast doesn't fix the issue because the ufloat data type isn't "natural" to python.

So let me give you an example of the issue.

```<code>import numpy as np
from uncertainties import *

#Stack example
def function_1():
    # When not using uncertainties np works as expected
    Var_1 = 0.13
    Var_2 = 0.32
    Result_1 = 1/(np.sqrt(np.sin(Var_1*Var_2)))
    print(Result_1)

    # However it doesn't work with ufloat data type
    var1 = ufloat(0.31, 0.10)
    var2 = ufloat(0.32, 0.02)
    result = 1/(np.sqrt(np.sin(var1*var2)))
    print(result)
function_1()
</code>```

So summarizing I would like to know how to calculate the error propagation of functions containing standard mathematical expressions like sin(), sqrt(), etc.

Of course if a different library provides functions compatible with uncertainties, then I don't need to stick with numpy, it was just an example.

All help is appreciated, thanks in advance!

Body:
I've been using the uncertainties library for calculation of the gaussian error propagation with good results for quite some time.

The problem is that I use the numpy library for all mathematical functions like sin(), sqrt(), and so on. Which does not support any arguments of  ufloat type. Thus making it impossible to calculate the error propagation of a function with any mathematical function implemented with numpy.

If I am not mistaken a simple typecast doesn't fix the issue because the ufloat data type isn't "natural" to python.

So let me give you an example of the issue.

import numpy as np
from uncertainties import *

#Stack example
def function_1():
    # When not using uncertainties np works as expected
    Var_1 = 0.13
    Var_2 = 0.32
    Result_1 = 1/(np.sqrt(np.sin(Var_1*Var_2)))
    print(Result_1)

    # However it doesn't work with ufloat data type
    var1 = ufloat(0.31, 0.10)
    var2 = ufloat(0.32, 0.02)
    result = 1/(np.sqrt(np.sin(var1*var2)))
    print(result)
function_1()

So summarizing I would like to know how to calculate the error propagation of functions containing standard mathematical expressions like sin(), sqrt(), etc.

Of course if a different library provides functions compatible with uncertainties, then I don't need to stick with numpy, it was just an example.

All help is appreciated, thanks in advance!


问:
Settings is no longer exists in TinyMCE
I used TinyMCE version 5.10.2.

I add toolbar dynamically in version 5.10.2.

```<code>var tinyMceInstance = tinymce.get('tinymceid');
tinyMceInstance.settings.plugins += ' image';
tinyMceInstance.settings.toolbar[4].items.push('image');
</code>```

But when I upgrade tinyMCE version from 5 to 6, settings is not available.

How can I add toolbar dynamically in tinyMCE version 6.x ?

Title: Settings is no longer exists in TinyMCE

Body:
I used TinyMCE version 5.10.2.

I add toolbar dynamically in version 5.10.2.

var tinyMceInstance = tinymce.get('tinymceid');
tinyMceInstance.settings.plugins += ' image';
tinyMceInstance.settings.toolbar[4].items.push('image');

But when I upgrade tinyMCE version from 5 to 6, settings is not available.

How can I add toolbar dynamically in tinyMCE version 6.x ?


问:
CCXT balance = binanceus.fetch_balance() python problems
I am having trouble with my fetch_balance() it fails when I classify it as quantity.

```<code>
</code>```
```<code>import ccxt
import config

binanceus = ccxt.binanceus({
'apiKey': config.API_KEY,
'secret': config.API_SECRET,

})

def trade_crypto(request):
data = request.get_json()
balance = binanceus.fetch_balance()

tickers = {
    'DOGEUSDT': 'DOGE/USDT'
}

ticker = tickers[data['ticker']]
quantity = balance['free']
sell_price =  data['close'] * 1.005
order = binanceus.create_limit_sell_order(ticker, quantity, sell_price)

return order
</code>```
```<code>
</code>```

In the quantity section it fails. If I replace (ticker, 1000, sell_price) it works. Not sure why it is failing.

Body:
I am having trouble with my fetch_balance() it fails when I classify it as quantity.

import ccxt
import config

binanceus = ccxt.binanceus({
'apiKey': config.API_KEY,
'secret': config.API_SECRET,

})

def trade_crypto(request):
data = request.get_json()
balance = binanceus.fetch_balance()

tickers = {
    'DOGEUSDT': 'DOGE/USDT'
}

ticker = tickers[data['ticker']]
quantity = balance['free']
sell_price =  data['close'] * 1.005
order = binanceus.create_limit_sell_order(ticker, quantity, sell_price)

return order

In the quantity section it fails. If I replace (ticker, 1000, sell_price) it works. Not sure why it is failing.


问:
I want to update viewers_can_edit param in grafana defaults.ini file deployed by helm in kubernetes
I want to update viewers_can_edit param in grafana defaults.ini file deployed by helm in kubernetes . I need change the parameter from false to true.
I deployed the solution prometheus stack in a kubernetes cluster, version 1.20, using helm.
So, I was finding in the pods and I found the file. But it's not possible modify.

Locate the file

```<code>bash-5.1$ pwd
/usr/share/grafana
bash-5.1$ cd conf/
bash-5.1$ ls
defaults.ini        ldap.toml           ldap_multiple.toml  provisioning        sample.ini
</code>```

Param to modify

```<code># Viewers can edit/inspect dashboard settings in the browser. But not save the dashboard.
viewers_can_edit = false
</code>```

My question is, if I canot login as root and I cannot modify the file in the pod, what is the correct way to do this change?
I listen your experience or advice.
Thank in advance.
Juan Andres

Body:
I want to update viewers_can_edit param in grafana defaults.ini file deployed by helm in kubernetes . I need change the parameter from false to true.
I deployed the solution prometheus stack in a kubernetes cluster, version 1.20, using helm.
So, I was finding in the pods and I found the file. But it's not possible modify.

Locate the file

bash-5.1$ pwd
/usr/share/grafana
bash-5.1$ cd conf/
bash-5.1$ ls
defaults.ini        ldap.toml           ldap_multiple.toml  provisioning        sample.ini

Param to modify

# Viewers can edit/inspect dashboard settings in the browser. But not save the dashboard.
viewers_can_edit = false

My question is, if I canot login as root and I cannot modify the file in the pod, what is the correct way to do this change?
I listen your experience or advice.
Thank in advance.
Juan Andres


问:
How to handle IntegrityError exception of conditional unique constraint in Django/Postgres?
let's assume we have the below model class code:

from django.db import models

class SupplierAddress(models.Model):
    """Model to create supplier's address instances"""

    class Meta:
        """Customize django default way to plural the class name"""

        verbose_name = 'Supplier Address'
        verbose_name_plural = 'Supplier Addresses'
        constraints = [
            models.UniqueConstraint(
                fields=['supplier', 'address'],
                name='supplier_address_unique_appversion'
            ),
            models.UniqueConstraint(
                fields=['supplier'],
                condition=models.Q(is_default=True),
                name='one_default_address_per_supplier'
            )
        ]

    # Define model fields.
    supplier = models.ForeignKey(
        'Supplier',
        on_delete=models.CASCADE,
        related_name='supplier_addresses_supplier'
    )
    address = models.ForeignKey(
        'Address',
        on_delete=models.CASCADE,
        related_name='supplier_addresses_address'
    )
    is_default = models.BooleanField(default=False)

    def __str__(self):
       """String representation of model objects"""

       return '{}, {}'.format(self.supplier, self.address)

```
<p>This model constraints will make sure there are <strong>unique constraint</strong> between <code>supplier</code> and <code>address</code> foreign keys <strong>AND</strong> a <strong>conditional unique constraint</strong> between <code>supplier</code> and <code>is_default</code> when it's <code>True</code>.</p>
<p>The <strong>conditional unique constraint</strong> in Django and Postgres as database engine, will raise an exception:</p>
```IntegrityError: duplicate key value violates unique constraint...
```
<p>In case the input by user go against the constraint condition.</p>
<p><strong>Ideas to handle such case:</strong></p>
<p>1- handle it on user side, like using <code>forms</code> <strong>But</strong> not a good idea for testing.</p>
<p>2- using <code>clean()</code> method and raise an error message, like:</p>
<pre class="lang-py prettyprint-override"><code>
def clean(self, *args, **kwargs):
    """Restrict the add/change to model fields"""

    if self.is_default is True:
        if SupplierAddress.objects.filter(
                supplier=self.supplier,
                is_default=True
        ).exclude(id=self.id).count() >= 1:
            raise forms.ValidationError(
                {
                    "is_default": "You can't set more than one default address"
                }
            )

</code>```

BUT this will not works fine if you are forcing multiple model instances add/change because each instance (object) works separately from others and this means at time of checking, all instances being clean and none of them saved in the database yet, so the clean() method condition will pass for all of them.

Any better idea?

Body:
let's assume we have the below model class code:

from django.db import models

class SupplierAddress(models.Model):
    """Model to create supplier's address instances"""

    class Meta:
        """Customize django default way to plural the class name"""

        verbose_name = 'Supplier Address'
        verbose_name_plural = 'Supplier Addresses'
        constraints = [
            models.UniqueConstraint(
                fields=['supplier', 'address'],
                name='supplier_address_unique_appversion'
            ),
            models.UniqueConstraint(
                fields=['supplier'],
                condition=models.Q(is_default=True),
                name='one_default_address_per_supplier'
            )
        ]

    # Define model fields.
    supplier = models.ForeignKey(
        'Supplier',
        on_delete=models.CASCADE,
        related_name='supplier_addresses_supplier'
    )
    address = models.ForeignKey(
        'Address',
        on_delete=models.CASCADE,
        related_name='supplier_addresses_address'
    )
    is_default = models.BooleanField(default=False)

    def __str__(self):
       """String representation of model objects"""

       return '{}, {}'.format(self.supplier, self.address)

This model constraints will make sure there are unique constraint between supplier and address foreign keys AND a conditional unique constraint between supplier and is_default when it's True.

The conditional unique constraint in Django and Postgres as database engine, will raise an exception:

IntegrityError: duplicate key value violates unique constraint...

In case the input by user go against the constraint condition.

Ideas to handle such case:

1- handle it on user side, like using forms But not a good idea for testing.

2- using clean() method and raise an error message, like:

def clean(self, *args, **kwargs):
    """Restrict the add/change to model fields"""

    if self.is_default is True:
        if SupplierAddress.objects.filter(
                supplier=self.supplier,
                is_default=True
        ).exclude(id=self.id).count() >= 1:
            raise forms.ValidationError(
                {
                    "is_default": "You can't set more than one default address"
                }
            )

BUT this will not works fine if you are forcing multiple model instances add/change because each instance (object) works separately from others and this means at time of checking, all instances being clean and none of them saved in the database yet, so the clean() method condition will pass for all of them.

Any better idea?


问:
python test non absolute uri through a proxy server
I am trying to test one of my servers with a non-absolute URI through a proxy server using aiohttp. unfortunately, aiohttp complains InvalidURL exception.

Is there any alternative way to test non-absolute URI using aiohttp or any other package available to do this scenario?

```<code>import aiohttp
import asyncio

async def main():
    async with aiohttp.ClientSession() as session:
        async with session.get(url='/get', proxy='http://proxy.com') as resp:
            print(resp.status)
            print(await resp.text())

asyncio.run(main())

Traceback (most recent call last):
  File "test.py", line 10, in <module>
    asyncio.run(main())
  File "/usr/lib/python3.8/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/usr/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
    return future.result()
  File "test.py", line 6, in main
    async with session.get(url='/get', proxy='http://proxy.com') as resp:
  File "/home/kosuri/gitswarm/venv/lib/python3.8/site-packages/aiohttp/client.py", line 1141, in __aenter__
    self._resp = await self._coro
  File "/home/kosuri/gitswarm/venv/lib/python3.8/site-packages/aiohttp/client.py", line 508, in _request
    req = self._request_class(
  File "/home/kosuri/gitswarm/venv/lib/python3.8/site-packages/aiohttp/client_reqrep.py", line 305, in __init__
    self.update_host(url)
  File "/home/kosuri/gitswarm/venv/lib/python3.8/site-packages/aiohttp/client_reqrep.py", line 364, in update_host
    raise InvalidURL(url)
aiohttp.client_exceptions.InvalidURL: /get
</code>```

Body:
I am trying to test one of my servers with a non-absolute URI through a proxy server using aiohttp. unfortunately, aiohttp complains InvalidURL exception.

Is there any alternative way to test non-absolute URI using aiohttp or any other package available to do this scenario?

import aiohttp
import asyncio

async def main():
    async with aiohttp.ClientSession() as session:
        async with session.get(url='/get', proxy='http://proxy.com') as resp:
            print(resp.status)
            print(await resp.text())

asyncio.run(main())

Traceback (most recent call last):
  File "test.py", line 10, in <module>
    asyncio.run(main())
  File "/usr/lib/python3.8/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/usr/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
    return future.result()
  File "test.py", line 6, in main
    async with session.get(url='/get', proxy='http://proxy.com') as resp:
  File "/home/kosuri/gitswarm/venv/lib/python3.8/site-packages/aiohttp/client.py", line 1141, in __aenter__
    self._resp = await self._coro
  File "/home/kosuri/gitswarm/venv/lib/python3.8/site-packages/aiohttp/client.py", line 508, in _request
    req = self._request_class(
  File "/home/kosuri/gitswarm/venv/lib/python3.8/site-packages/aiohttp/client_reqrep.py", line 305, in __init__
    self.update_host(url)
  File "/home/kosuri/gitswarm/venv/lib/python3.8/site-packages/aiohttp/client_reqrep.py", line 364, in update_host
    raise InvalidURL(url)
aiohttp.client_exceptions.InvalidURL: /get


问:
Firebase & Stripe - Uncaught (in promise) Error: INTERNAL
I'm trying to get Stripe payments working on my project site.

I am getting this error when I click to the checkout button. It is pointing to :

```<code>checkoutButton.addEventListener('click', () => {
    createStripeCheckout()
      .then(response => {
        const sessionId = response.data.id
        stripe.redirectToCheckout({ sessionId: sessionId })
      })
  })
</code>```

Full code:

```<code>  var firebaseConfig = {
    apiKey: "***",
    authDomain: "DOMAIN",
    databaseURL: "DB URL",
    projectId: "X",
    storageBucket: "X",
    messagingSenderId: "345845091768",
    appId: "APP-ID",
    measurementId: "G-E53ZGGY217"
    };

    firebase.initializeApp(firebaseConfig);

  const checkoutButton = document.getElementById('checkout-button')
  const createStripeCheckout = firebase.functions().httpsCallable('createStripeCheckout')
  const stripe = Stripe('API KEY')

  checkoutButton.addEventListener('click', () => {
    createStripeCheckout()
      .then(response => {
        const sessionId = response.data.id
        stripe.redirectToCheckout({ sessionId: sessionId })
      })
  })
</code>```

Not sure what I'm doing wrong, it's to integrate with Stripe.

I've tried looking up the answer online but there isn't any help.

I'd really appreciate help! Thank you!

Full error:

```<code>POST    https://<name>.cloudfunctions.net/createStripeCheckout
Status 500
Internal Server Error

Uncaught (in promise) Error: INTERNAL
    g error.ts:66
    b error.ts:175
    call service.ts:276
    t tslib.es6.js:102
    t tslib.es6.js:83
    r tslib.es6.js:73
    promise callback*o tslib.es6.js:75
    r tslib.es6.js:73
    promise callback*o tslib.es6.js:75
    s tslib.es6.js:76
    s tslib.es6.js:72
    call service.ts:238
    httpsCallable service.ts:183
    <anonymous> scripts.js:19
    EventListener.handleEvent* scripts.js:18
</code>```

Body:
I'm trying to get Stripe payments working on my project site.

I am getting this error when I click to the checkout button. It is pointing to :

checkoutButton.addEventListener('click', () => {
    createStripeCheckout()
      .then(response => {
        const sessionId = response.data.id
        stripe.redirectToCheckout({ sessionId: sessionId })
      })
  })

Full code:

  var firebaseConfig = {
    apiKey: "***",
    authDomain: "DOMAIN",
    databaseURL: "DB URL",
    projectId: "X",
    storageBucket: "X",
    messagingSenderId: "345845091768",
    appId: "APP-ID",
    measurementId: "G-E53ZGGY217"
    };

    firebase.initializeApp(firebaseConfig);

  const checkoutButton = document.getElementById('checkout-button')
  const createStripeCheckout = firebase.functions().httpsCallable('createStripeCheckout')
  const stripe = Stripe('API KEY')

  checkoutButton.addEventListener('click', () => {
    createStripeCheckout()
      .then(response => {
        const sessionId = response.data.id
        stripe.redirectToCheckout({ sessionId: sessionId })
      })
  })

Not sure what I'm doing wrong, it's to integrate with Stripe.

I've tried looking up the answer online but there isn't any help.

I'd really appreciate help! Thank you!

Full error:

POST    https://<name>.cloudfunctions.net/createStripeCheckout
Status 500
Internal Server Error

Uncaught (in promise) Error: INTERNAL
    g error.ts:66
    b error.ts:175
    call service.ts:276
    t tslib.es6.js:102
    t tslib.es6.js:83
    r tslib.es6.js:73
    promise callback*o tslib.es6.js:75
    r tslib.es6.js:73
    promise callback*o tslib.es6.js:75
    s tslib.es6.js:76
    s tslib.es6.js:72
    call service.ts:238
    httpsCallable service.ts:183
    <anonymous> scripts.js:19
    EventListener.handleEvent* scripts.js:18


问:
Minimax algorithm for tic tac toe doesnt give optimal solution
I am writing 3D tic tac toe game using minimax algorithm with alpha beta pruning, but the algorithm doesnt give optimal solution, it goes and chooses next possible solution from winning states, not taking into concern what is on the board, meaning it wont block my moves.
This is the code:
`

```<code>int Game::miniMax(char marker, int depth, int alpha, int beta){
    // Initialize best move
    bestMove = std::make_tuple(-1, -1, -1);

        // If we hit a terminal state (leaf node), return the best score and move
    if (isBoardFull() || getBoardState('O')!=0 || depth>5)
        return getBoardState('O');

    auto allowedMoves = getAllowedMoves();

    for (int i = 0; i < allowedMoves.size(); i++){
        auto move = allowedMoves[i];
        board[std::get<0>(move)][std::get<1>(move)][std::get<2>(move)] = marker;

        // Maximizing player's turn
        if (marker == 'O'){
            int bestScore = INT32_MIN;
            int score = miniMax('X', depth + 1, alpha, beta);

            // Get the best scoring move
            if (bestScore <= score){
                bestScore = score - depth * 10;
                bestMove = move;
                // Check if this branch's best move is worse than the best
                // option of a previously search branch. If it is, skip it
                alpha = std::max(alpha, bestScore);
                board[std::get<0>(move)][std::get<1>(move)][std::get<2>(move)] = '-';
                if (beta <= alpha){
                    break;
                }
            }

        } // Minimizing opponent's turn
        else{
            int bestScore = INT32_MAX;
            int score = miniMax('O', depth + 1, alpha, beta);

            if (bestScore >= score){
                bestScore = score + depth * 10;
                bestMove = move;

                // Check if this branch's best move is worse than the best
                // option of a previously search branch. If it is, skip it
                beta = std::min(beta, bestScore);
                board[std::get<0>(move)][std::get<1>(move)][std::get<2>(move)] = '-';
                if (beta <= alpha){
                    break;
                }
            }

        }

        board[std::get<0>(move)][std::get<1>(move)][std::get<2>(move)] = '-'; // Undo move

    }

    if(marker== 'O')
        return INT32_MIN;
    else
        return INT32_MAX;
}
</code>```

`
What do I need to change to make it work?

I tried other ways to implement minimax, but it doesnt give optimal, or any, solution.
The limit on depth is because it is too slow for bigger depths, but still not giving solution, also increasing the value of the constant that multiplies the depth in the score part is only slowing the program

Body:
I am writing 3D tic tac toe game using minimax algorithm with alpha beta pruning, but the algorithm doesnt give optimal solution, it goes and chooses next possible solution from winning states, not taking into concern what is on the board, meaning it wont block my moves.
This is the code:
`

int Game::miniMax(char marker, int depth, int alpha, int beta){
    // Initialize best move
    bestMove = std::make_tuple(-1, -1, -1);

        // If we hit a terminal state (leaf node), return the best score and move
    if (isBoardFull() || getBoardState('O')!=0 || depth>5)
        return getBoardState('O');

    auto allowedMoves = getAllowedMoves();

    for (int i = 0; i < allowedMoves.size(); i++){
        auto move = allowedMoves[i];
        board[std::get<0>(move)][std::get<1>(move)][std::get<2>(move)] = marker;

        // Maximizing player's turn
        if (marker == 'O'){
            int bestScore = INT32_MIN;
            int score = miniMax('X', depth + 1, alpha, beta);

            // Get the best scoring move
            if (bestScore <= score){
                bestScore = score - depth * 10;
                bestMove = move;
                // Check if this branch's best move is worse than the best
                // option of a previously search branch. If it is, skip it
                alpha = std::max(alpha, bestScore);
                board[std::get<0>(move)][std::get<1>(move)][std::get<2>(move)] = '-';
                if (beta <= alpha){
                    break;
                }
            }

        } // Minimizing opponent's turn
        else{
            int bestScore = INT32_MAX;
            int score = miniMax('O', depth + 1, alpha, beta);

            if (bestScore >= score){
                bestScore = score + depth * 10;
                bestMove = move;

                // Check if this branch's best move is worse than the best
                // option of a previously search branch. If it is, skip it
                beta = std::min(beta, bestScore);
                board[std::get<0>(move)][std::get<1>(move)][std::get<2>(move)] = '-';
                if (beta <= alpha){
                    break;
                }
            }

        }

        board[std::get<0>(move)][std::get<1>(move)][std::get<2>(move)] = '-'; // Undo move

    }

    if(marker== 'O')
        return INT32_MIN;
    else
        return INT32_MAX;
}

`
What do I need to change to make it work?

I tried other ways to implement minimax, but it doesnt give optimal, or any, solution.
The limit on depth is because it is too slow for bigger depths, but still not giving solution, also increasing the value of the constant that multiplies the depth in the score part is only slowing the program


问:
Reset password button is disabled after magento upgrade to 2.4.5
When I click forgot password from home page, I can enter my email for a link to reset password to be sent; however, the submit button (Reset Password) is disabled.  I understand that a condition is newly added in the upgraded version.  Any help to enable the button is appreciated.  Thanks in advance.</p>


问:
MSAL doesn't recognize signIn() from Chrome Extension
I am trying to make some API calls via MsGraph from Chrome-extension.I am using Vue2 to build this extension  and 'vue-msal'. When I print msal object it gets in this format:

But when I call it I get nothing.It suppose to open a logIn window.

```<code>  <div id="demo">
    <div v-if="user">
        <div>Welcome {{user.name}}</div>
        <div v-if="user.profile.jobTitle">Your job title is {{user.profile.jobTitle}}</div>
        <div><button @click="signOut()">logout</button></div>
    </div>
    <div v-else>
        <button @click="signIn()"> Please sign-in</button>
    </div>
</div>

</template>

<script>
import { msalMixin } from 'vue-msal';
export default {
  mixins: [msalMixin],
  name: 'HelloWorld',
  mounted () {

  },
  computed: {
    user() {
          let user = null;
          if (this.msal.isAuthenticated) { // Note that the dollar sign ($) is missing from this.msal
            user = {
              ...this.msal.user,
              profile: {}
            }
            if (this.msal.graph && this.msal.graph.profile) {
                user.profile = this.msal.graph.profile
            }
          }
          return user;
        }
  },
  methods:{
    async signIn(){
       console.log(this.$msal,'msal')
       console.log(this.$msal.signIn(),'signIn func')

    },
    signOut(){
      this.$msal.signOut()
    }
  }
}
</script>

</code>```

Body:
I am trying to make some API calls via MsGraph from Chrome-extension.I am using Vue2 to build this extension  and 'vue-msal'. When I print msal object it gets in this format:

But when I call it I get nothing.It suppose to open a logIn window.

Welcome {{user.name}}

Your job title is {{user.profile.jobTitle}}

<button @click="signOut()">logout</button>

        <button @click="signIn()"> Please sign-in</button>

</template>


问:
How to implement shared session store with fastify
I am using apollo server 4 + fastify with @mgcrea/fastify-session
as my session store and can't get data to be shared between multiple requests.
My cookie configuration looks like this.

  app.register(fastifySession, {
    cookieName: "qid",
    saveUninitialized: true,
    store: new RedisStore({
      client: new Redis({ enableAutoPipelining: true }),
    }),
    secret: "cats",
    cookie: {
      maxAge: 31536e7,
      httpOnly: true,
      sameSite: "lax",
      secure: "auto",
    },
  });
```
<p>My resolver looks like this.</p>
<pre class="lang-js prettyprint-override"><code>  @Query(() => Int, { nullable: true })
  test(@Ctx() { req }: MyCtx): number {
    req.session.set("5", 2);
    return req.session.get("5") as number;
  }
</code>```

The code directly above returns 2 as expected. But when I use multiple resolvers it doesn't share the data as I would like it.

  @Query(() => Int, { nullable: true })
  test(@Ctx() { req }: MyCtx): number {
    req.session.set("5", 2);
    return req.session.get("5") as number;
  }
  @Query(() => Int, { nullable: true })
  test2(@Ctx() { req }: MyCtx): number {
    return req.session.get("5") as number;
  }
```

Even when I execute test first then test2. test2 always returns null.

How can I remedy this?

I tried to use the req.session.data object to store data instead but that didn't solve the issue.

Body:
I am using apollo server 4 + fastify with @mgcrea/fastify-session
as my session store and can't get data to be shared between multiple requests.
My cookie configuration looks like this.

  app.register(fastifySession, {
    cookieName: "qid",
    saveUninitialized: true,
    store: new RedisStore({
      client: new Redis({ enableAutoPipelining: true }),
    }),
    secret: "cats",
    cookie: {
      maxAge: 31536e7,
      httpOnly: true,
      sameSite: "lax",
      secure: "auto",
    },
  });

My resolver looks like this.

  @Query(() => Int, { nullable: true })
  test(@Ctx() { req }: MyCtx): number {
    req.session.set("5", 2);
    return req.session.get("5") as number;
  }

The code directly above returns 2 as expected. But when I use multiple resolvers it doesn't share the data as I would like it.

  @Query(() => Int, { nullable: true })
  test(@Ctx() { req }: MyCtx): number {
    req.session.set("5", 2);
    return req.session.get("5") as number;
  }
  @Query(() => Int, { nullable: true })
  test2(@Ctx() { req }: MyCtx): number {
    return req.session.get("5") as number;
  }

Even when I execute test first then test2. test2 always returns null.

How can I remedy this?

I tried to use the req.session.data object to store data instead but that didn't solve the issue.


问:
I have a audio in 128kbps that was read 16KB every second, but it seems that I am getting more than 1 seconds of the music each time. Why?
So I have a new stream to which I will push 2048 bytes of audio buffer every 128ms (i.e. 16KB every second) but I seem to have more than 1 second of data pushed to the stream. (I think so by finding ffmpeg is still streaming sound even tens of seconds after I stop pushing data in it)

When I changed it to 1024 bytes/128ms (8KB/s), the sound stop right after I stop pushing data.

Please correct me if I do anything wrong!

Some background story

I am using ffmpeg to stream to a rtp server. It is one-time used, so I can't stop ffmpeg and start again. I don't want to use the ZeroMQ way because of latency. The target I am trying to archive is to have the same readable stream to ffmpeg and change the audio content on the go by stop pushing chunks of previous audio file and switch to the new one.

If you know some other ways to archive the goal, I would be very pleased to know. Thank you in advance!

My current code

const stream = new Stream.Readable();

// ...
// (send stream to ffmpeg)
// ...

fileP = fs.createReadStream(input);
fileP.on('readable', async () => {
    var chunk;
    while (previousStream && (chunk = fileP?.read(16 * 128))) {
        if (!previousStream) break;
        stream.push(chunk);
        await delay(125);
    }
});
```


问:
Use DIAL to cast to apple tv from android app
Can we use DIAL to discover and play content on apple tv from android app? If not what should we use  cast to apple tv from android mobile

Thanks,
Pavan Tiwari


问:
EF Core 7 t4 file - get string length
I've installed the default t4 templates for EF Core into my project, and now I want to edit the EntityType.t4 template so that for any varchar field, I generate a static variable with the max length. For example, the scaffold right now will generate a line like:

public string? CollateralName { get; set; }
```
<p>When it does that, I also want it to add:</p>
<pre class="lang-cs prettyprint-override"><code>public const int CollateralNamePropertyMaxLength = 50;
</code>```

I can see in the t4 file where it's writing the property, but I'm not sure how to get the max length of the string from the database column.

Title: EF Core 7 t4 file - get string length

Body:
I've installed the default t4 templates for EF Core into my project, and now I want to edit the EntityType.t4 template so that for any varchar field, I generate a static variable with the max length. For example, the scaffold right now will generate a line like:

public string? CollateralName { get; set; }

When it does that, I also want it to add:

public const int CollateralNamePropertyMaxLength = 50;

I can see in the t4 file where it's writing the property, but I'm not sure how to get the max length of the string from the database column.


问:
Performance issues with large MySQL tables with 100million of rows
I've had some performance issues with MySQL tables and I'm trying to get some help. The SQL knowledge I have is pretty limited, so far over the years I was able to figure out most by using Google for solutions. At this point my the tables are so large that even doing something like a simple UPDATE query takes 1 second per row (usually its 0.0001s or something similar). My database is hosted on AWS using an Aurora MySQL engine and the instance is a db.t3.small. My largest table has 164million rows and keeps adding around 2million every day. I was reading about 2 possible solutions: Indexing and Partitioning. Right now I havent really indexed anything other than the main id which I dont use for anything:

Table metrics:

Column
Type
Indexes

id
int(11)
PRIMARY, id_UNIQUE

trackid
varchar(100)

plays
int(15)

source
int(11)

timestamp
timestamp

Table tracks:

Column
Type
Indexes

id
int(11)
PRIMARY

trackid
varchar(100)
trackid

trackname
varchar(200)

artistname
varchar(200)

artistid
varchar(100)

date_added
timestamp

I suppose first of all since my joins happen on trackid and not id I should create an index on trackid for all my tables. Any other indexes I should create? Also, would partitioning help my case? I was thinking to split up all the tables into monthly snapshots and just union them on the fly, but I dont know if thats a good idea. I really dont know what the best practices are and if I can even do partitioning this late in the process since the data is so big. Thanks for the help


问:
Can I assign column names to SQL query with dynamic columns?
I'm a noob at SQL. Sorry if my title isn't correct; Here's the problem:

I have a QODBC [1] query for QuickBooks that generates Profit & Loss report with dynamic columns:

```<code>sp_report
    ProfitAndLossStandard
show
    "Text",
    "RowType",
    "Amount"  <-- dynamic
parameters
    DateFrom= ?,
    DateTo= ?,
    SummarizeColumnsBy='Day'
</code>```

With the parameter SummarizeColumnsBy='Day' you get x number of Amount columns for x number of days between DateFrom & DateTo (inclusive).

The above query with three days range looks something like this (first three rows):

0
1
2
3
4
5

0
Ordinary Income/Expense
TextRow
366
None
None
None

1
Income
TextRow
366
None
None
None

2
4000 · Revenue
DataRow
366
[value]
[value]
[value]

...

Columns 3-5 are the Amount feature and they each show a summary value for a date in the range (only on row type == DataRow). (I also get this extra column, 2, not in the SQL request.)

I'm using Python and PyODBC to call QuickBooks. The resulting data is put into a Pandas DataFrame to represent the P&L in my script..

I can do some DataFrame carpentry to get the column names with Pandas, but is there a way to get the column names in the SQL syntax?

IE. 0 = "Text", 1 = "RowType", ...

[1]: In case you don't know, "QODBC is a fully functional ODBC driver for reading and writing QuickBooks ...accounting data files by using standard SQL commands."

Body:
I'm a noob at SQL. Sorry if my title isn't correct; Here's the problem:

I have a QODBC [1] query for QuickBooks that generates Profit & Loss report with dynamic columns:

sp_report
    ProfitAndLossStandard
show
    "Text",
    "RowType",
    "Amount"  <-- dynamic
parameters
    DateFrom= ?,
    DateTo= ?,
    SummarizeColumnsBy='Day'

With the parameter SummarizeColumnsBy='Day' you get x number of Amount columns for x number of days between DateFrom & DateTo (inclusive).

The above query with three days range looks something like this (first three rows):

0
1
2
3
4
5

0
Ordinary Income/Expense
TextRow
366
None
None
None

1
Income
TextRow
366
None
None
None

2
4000 · Revenue
DataRow
366
[value]
[value]
[value]

...

Columns 3-5 are the Amount feature and they each show a summary value for a date in the range (only on row type == DataRow). (I also get this extra column, 2, not in the SQL request.)

I'm using Python and PyODBC to call QuickBooks. The resulting data is put into a Pandas DataFrame to represent the P&L in my script..

I can do some DataFrame carpentry to get the column names with Pandas, but is there a way to get the column names in the SQL syntax?

IE. 0 = "Text", 1 = "RowType", ...

[1]: In case you don't know, "QODBC is a fully functional ODBC driver for reading and writing QuickBooks ...accounting data files by using standard SQL commands."


问:
How to modify the Unity maximum pixel width and height?
I want to get 1920x1080 camera view from Unity but output : (cam.pixelWidth: 256, cam.pixelHeight = 256) always . I have multiple camera. For main camera as a default I can get 1920x1080 resolution but I can not get for other cameras. How can I convert 256:256 image to 1920:1080 ?</p>


问:
Get JTextField input to System.in of different Java-program run by main program via console command?
I'm trying to code my own little Java IDE in Java. I'm pretty far for what I want, because I only want to be able to code simple command-line-programs in my IDE.

My current problem has to do with user input.

This is how I handle having an own console-output in my IDE (outputField is a jTextArea):

```<code>try {
    Process p = Runtime.getRuntime().exec(cmd);
    BufferedReader readerInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader readerError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    //BufferedWriter processInput = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
    String outputLine;
    while ((outputLine = readerInput.readLine()) != null) {
        outputField.append(outputLine + "\n");
    }
    while ((outputLine = readerError.readLine()) != null) {
        outputField.append(outputLine + "\n");
    }
} catch (IOException e) {
    e.printStackTrace();
}
</code>```

But I have no idea how I could get user input to satisfy the scanner if a user written console-application asks for user input via a scanner. Right now my IDE would just freezes. Probably because the command-line-program waits for user input? Maybe I should run it in a different thread. How would I do that?

Maybe someone can get me some keywords I could research etc.

Greetings,
Daniel

Body:
I'm trying to code my own little Java IDE in Java. I'm pretty far for what I want, because I only want to be able to code simple command-line-programs in my IDE.

My current problem has to do with user input.

This is how I handle having an own console-output in my IDE (outputField is a jTextArea):

try {
    Process p = Runtime.getRuntime().exec(cmd);
    BufferedReader readerInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader readerError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    //BufferedWriter processInput = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
    String outputLine;
    while ((outputLine = readerInput.readLine()) != null) {
        outputField.append(outputLine + "\n");
    }
    while ((outputLine = readerError.readLine()) != null) {
        outputField.append(outputLine + "\n");
    }
} catch (IOException e) {
    e.printStackTrace();
}

But I have no idea how I could get user input to satisfy the scanner if a user written console-application asks for user input via a scanner. Right now my IDE would just freezes. Probably because the command-line-program waits for user input? Maybe I should run it in a different thread. How would I do that?

Maybe someone can get me some keywords I could research etc.

Greetings,
Daniel


问:
How do I fix this MongoDB Permission Denied error?
I'm using:

```<code>brew install mongodb-community@6.0
</code>```

To install mongoDB. it keeps giving me the error :

```<code>==> Installing mongodb/brew/mongodb-community dependency: mongodb-database-
Error: An exception occurred within a child process:
  Errno::EACCES: Permission denied @ dir_s_mkdir - /usr/local/Cellar/mongodb-database-tools/100.6.1
</code>```

How do I fix that?

Body:
I'm using:

brew install mongodb-community@6.0

To install mongoDB. it keeps giving me the error :

==> Installing mongodb/brew/mongodb-community dependency: mongodb-database-
Error: An exception occurred within a child process:
  Errno::EACCES: Permission denied @ dir_s_mkdir - /usr/local/Cellar/mongodb-database-tools/100.6.1

How do I fix that?


问:
How can I merge my two files - one has a foreign key and the rows should be added to the other table
I do not know how I can merge my two .csv files. The second file should be added to the first one based on a foreign key which should extend the first table.

So I did my research but whenever I tried something the second table added to the first one based on their primary key and not the numerical foreign key. But I have a list of people and need to add their sales of this year to the list from the second list.

Do I need to add another column to the first table named after the foreign key although it's based on the numbers of the primary key?


问:
ag-grid access view/model from cellStyle
I am using ipyaggrid and looking at the advanced example here:
https://gitlab.com/DGothrek/ipyaggrid/-/blob/master/docs/notebooks/demo-ipyaggrid-customize.ipynb

I inject custom params via 'user_params' input to the ag-grid wrappper layer which appear to be hooked under the hood of ag-grid at

```<code>view.model.get('user_params')
</code>```

I need to get a hold of these inside a cellStyle function.
I can see how this could work via a js_post_grid function that copies

```<code>view.model.get('user_params')
</code>```

into

```<code>gridOptions.api.context.user_params
</code>```

which is then accessible from cellStyle via param.api.context.

Sounds like there should be an easier way though?

P.S. I tested that indeed this works :

```<code>
cell_style1 = """

function(params) {

console.log(params.api.context.user_params);

return {color: "black", backgroundColor: "white"};

}

"""

js_post_grid = ["""

    gridOptions.api.context.user_params = view.model.get('user_params');

"""]

</code>```

Body:
I am using ipyaggrid and looking at the advanced example here:
https://gitlab.com/DGothrek/ipyaggrid/-/blob/master/docs/notebooks/demo-ipyaggrid-customize.ipynb

I inject custom params via 'user_params' input to the ag-grid wrappper layer which appear to be hooked under the hood of ag-grid at

view.model.get('user_params')

I need to get a hold of these inside a cellStyle function.
I can see how this could work via a js_post_grid function that copies

view.model.get('user_params')

into

gridOptions.api.context.user_params

which is then accessible from cellStyle via param.api.context.

Sounds like there should be an easier way though?

P.S. I tested that indeed this works :

cell_style1 = """

function(params) {

console.log(params.api.context.user_params);

return {color: "black", backgroundColor: "white"};

}

"""

js_post_grid = ["""

    gridOptions.api.context.user_params = view.model.get('user_params');

"""]


问:
Pandas: divide several columns by another column using chaining
I've seen on the internet that true adepts of python utilize chaining in their code. I've managed to learn .assign() and .apply() for some simple examples, but stugling with the one below.

let's say I have a df df_temp as below:

day
cost_fb
cost_ig
cost_ya
cost_yt
cost_total

2020-05-03
936.0
943.0
969.0
454.0
3302.0

2020-05-04
548.0
503.0
555.0
259.0
1865.0

2020-05-05
260.0
314.0
308.0
147.0
1029.0

I would like to divide each column of costs by a cost_total column to get percentages instead of absolute values. The one-liner is:

```<code>df_temp.iloc[:, 1:] = round(100 * df_temp.iloc[:, 1:].div(df_temp.cost_total, axis=0), 2)
</code>```

But then if I would like to make it a part of the upstream transformation like this - how can I include this in the chain?

```<code>df_temp = (
    pd.pivot_table(
        data=df_costs,
        index='day',
        columns='source',
        values='cost',
        aggfunc='sum',
        margins=True
    )
    .reset_index()
    .rename_axis('index', axis=1)
    .set_axis(['day', 'cost_fb', 'cost_ig', 'cost_ya', 'cost_yt', 'cost_total'], axis=1)
    # THIS APPLY DOESNT WORK - IndexingError: Too many indexers
    .apply(
        lambda df: df.iloc[:, 1:].div(df.cost_total, axis=0)
    )
)
</code>```

I've tried

df_temp.iloc[:, 1:] = round(100 * df_temp.iloc[:, 1:].div(df_temp.cost_total, axis=0), 2)

and it works, but it is not in the chain. Google doesn't seem to know the answer...

Body:
I've seen on the internet that true adepts of python utilize chaining in their code. I've managed to learn .assign() and .apply() for some simple examples, but stugling with the one below.

let's say I have a df df_temp as below:

day
cost_fb
cost_ig
cost_ya
cost_yt
cost_total

2020-05-03
936.0
943.0
969.0
454.0
3302.0

2020-05-04
548.0
503.0
555.0
259.0
1865.0

2020-05-05
260.0
314.0
308.0
147.0
1029.0

I would like to divide each column of costs by a cost_total column to get percentages instead of absolute values. The one-liner is:

df_temp.iloc[:, 1:] = round(100 * df_temp.iloc[:, 1:].div(df_temp.cost_total, axis=0), 2)

But then if I would like to make it a part of the upstream transformation like this - how can I include this in the chain?

df_temp = (
    pd.pivot_table(
        data=df_costs,
        index='day',
        columns='source',
        values='cost',
        aggfunc='sum',
        margins=True
    )
    .reset_index()
    .rename_axis('index', axis=1)
    .set_axis(['day', 'cost_fb', 'cost_ig', 'cost_ya', 'cost_yt', 'cost_total'], axis=1)
    # THIS APPLY DOESNT WORK - IndexingError: Too many indexers
    .apply(
        lambda df: df.iloc[:, 1:].div(df.cost_total, axis=0)
    )
)

I've tried

df_temp.iloc[:, 1:] = round(100 * df_temp.iloc[:, 1:].div(df_temp.cost_total, axis=0), 2)

and it works, but it is not in the chain. Google doesn't seem to know the answer...


问:
Django: ModelAdmin inside a template or view
i am looking for to make a page or view of Model.Admin page inside my website, so users with right permission can access my custom model.admin page with all of its functions/actions.

im talking about this page:
this


问:
Create additional orders in Shopware 6 on onOrderTransactionWritten event
I need to create multiple orders after an order is placed in Shopware 6.

I have managed to create the plugin, set up the OrderSubscribe and listen to the event, but i can't figure it out how to easily create multiple orders based on the informations of the placed order.

```<code>I can update the order like this:

</code>```
```<code>$this->orderRepository->upsert([[
    'id' => $payload['orderId'],
    'customFields' => ['order_type' => $this->getOrderType($orderObject->lineItems)]
]], $event->getContext());
</code>```
```<code>
i can delete it like this:

</code>```
```<code>$this->deleteOrder($payload['orderId'], $event->getContext());
</code>```
```<code>
How i can create other orders taking advantages for example of:

</code>```
```<code>$this->getOrderObject($event, $payload)->getOrderCustomer();
</code>```
```<code>
It's better approach to use the create method:

</code>```
```<code>$this->orderRepository->create([], $event->getContext());
</code>```
```<code>or using the Cart somehow?
</code>```

Body:
I need to create multiple orders after an order is placed in Shopware 6.

I have managed to create the plugin, set up the OrderSubscribe and listen to the event, but i can't figure it out how to easily create multiple orders based on the informations of the placed order.

I can update the order like this:

$this->orderRepository->upsert([[
    'id' => $payload['orderId'],
    'customFields' => ['order_type' => $this->getOrderType($orderObject->lineItems)]
]], $event->getContext());

i can delete it like this:

$this->deleteOrder($payload['orderId'], $event->getContext());

How i can create other orders taking advantages for example of:

$this->getOrderObject($event, $payload)->getOrderCustomer();

It's better approach to use the create method:

$this->orderRepository->create([], $event->getContext());

or using the Cart somehow?


问:
Funcanimation with bit=True is not updating x axis and not making sense with maximizing the window
I am trying to just have a simple life by getting a real-time plot functionality with blit=True but what I get is a plot with wrong x-axis limits and the plot changes when I maximize the plot window.

I want to have a plot of 50000 (say) points made in one go and then use funcanimation to call animate() to update the existing plot with set_data(x,y). Everything works fine if blit=False but I want to have blitting in my GUI. Please help with your thoughts. Attaching a short video for your reference along with the code.

I am pasting my code below:
Thanks in advance!

```<code>import time

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from random import randrange

fig = plt.figure(figsize=(6, 3))
varLen = 1000
x=[r for r in range(varLen-300)]
y=[randrange(0, 10) for r in range(varLen-300)]
y2=[10+randrange(0, 10) for r in range(varLen-300)]
# y=[]
# y2=[]
print(type(x))

ln, = plt.plot(x, y, '-')
ln2, = plt.plot(x, y2, '-')

def update(frame):
    start=time.time()
    global x, y, y2

    x.append(x[-1]+1)
    val=randrange(0, 10)
    y.append(val)
    y2.append(10+val)
    # print(len(x), len(y), len(y2))
    x=x[-varLen:]
    y = y[-varLen:]
    y2 = y2[-varLen:]
    ln.set_data(x, y)
    ln2.set_data(x,y2)

    # ln.set_data(frame, randrange(0, 10))
    # ln2.set_data(frame, 10+randrange(0, 10))

    fig.gca().relim()
    fig.gca().autoscale_view()
    print(f'Time (ms): {round((time.time() - start)*1000,2)}')
    return ln,ln2,

animation = FuncAnimation(fig, update, interval=1, blit=True)
plt.show()
</code>```
```<code>
</code>```

Body:
I am trying to just have a simple life by getting a real-time plot functionality with blit=True but what I get is a plot with wrong x-axis limits and the plot changes when I maximize the plot window.

I want to have a plot of 50000 (say) points made in one go and then use funcanimation to call animate() to update the existing plot with set_data(x,y). Everything works fine if blit=False but I want to have blitting in my GUI. Please help with your thoughts. Attaching a short video for your reference along with the code.

I am pasting my code below:
Thanks in advance!

import time

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from random import randrange

fig = plt.figure(figsize=(6, 3))
varLen = 1000
x=[r for r in range(varLen-300)]
y=[randrange(0, 10) for r in range(varLen-300)]
y2=[10+randrange(0, 10) for r in range(varLen-300)]
# y=[]
# y2=[]
print(type(x))

ln, = plt.plot(x, y, '-')
ln2, = plt.plot(x, y2, '-')

def update(frame):
    start=time.time()
    global x, y, y2

    x.append(x[-1]+1)
    val=randrange(0, 10)
    y.append(val)
    y2.append(10+val)
    # print(len(x), len(y), len(y2))
    x=x[-varLen:]
    y = y[-varLen:]
    y2 = y2[-varLen:]
    ln.set_data(x, y)
    ln2.set_data(x,y2)

    # ln.set_data(frame, randrange(0, 10))
    # ln2.set_data(frame, 10+randrange(0, 10))

    fig.gca().relim()
    fig.gca().autoscale_view()
    print(f'Time (ms): {round((time.time() - start)*1000,2)}')
    return ln,ln2,

animation = FuncAnimation(fig, update, interval=1, blit=True)
plt.show()


问:
How to pass state value from child to parent from a mapped select/option
I am trying to pass the "year" value back from a child component to the parent component. I am able to get the value passed back however after my props/function runs in the child component it resets the selection option to the default "choose a year" (but correctly passes the chosen year back to the parent component).

I am not sure if it is due to me mapping through the array and the function refreshing the component after each change?

```<code>function MapComponent() {

  const [input1, setInput1] = useState("");

  const setVehicleInfoInput = (value) => {
    setInput1(value)
  }

return (
    {input1} // shows the selected year from child component
    <VehicleInput setVehicleInfoInput={setVehicleInfoInput} sendYear={input1} />
)

export default React.memo(MapComponent)

const VehicleInput = ({setVehicleInfoInput, sendYear}) => {

  let vehicleYearsArray = ["2000","2001","2002","2003" etc ]

  let handleYearSelection = (e) => {
    setVehicleInfoInput(e.target.value)
  }

  return (

// sends the chosen year to parent component but then resets to "choose a year" rather than also showing the chosen year in the dropdown/select

   <select value={sendYear} className='vehicleInput' onChange={handleYearSelection}>
     <option value="Choose a Year"> -- Choose a Year -- </option>
     {vehicleYearsArray.map((year) => (
     <option value={year}>{year}</option>
     ))}
   </select>

)

export default VehicleInput;

</code>```

Thank you for any assistance

Body:
I am trying to pass the "year" value back from a child component to the parent component. I am able to get the value passed back however after my props/function runs in the child component it resets the selection option to the default "choose a year" (but correctly passes the chosen year back to the parent component).

I am not sure if it is due to me mapping through the array and the function refreshing the component after each change?

function MapComponent() {

  const [input1, setInput1] = useState("");

  const setVehicleInfoInput = (value) => {
    setInput1(value)
  }

return (
    {input1} // shows the selected year from child component
    <VehicleInput setVehicleInfoInput={setVehicleInfoInput} sendYear={input1} />
)

export default React.memo(MapComponent)

const VehicleInput = ({setVehicleInfoInput, sendYear}) => {

  let vehicleYearsArray = ["2000","2001","2002","2003" etc ]

  let handleYearSelection = (e) => {
    setVehicleInfoInput(e.target.value)
  }

  return (

// sends the chosen year to parent component but then resets to "choose a year" rather than also showing the chosen year in the dropdown/select

   <select value={sendYear} className='vehicleInput' onChange={handleYearSelection}>
     <option value="Choose a Year"> -- Choose a Year -- </option>
     {vehicleYearsArray.map((year) => (
     <option value={year}>{year}</option>
     ))}
   </select>

)

export default VehicleInput;

Thank you for any assistance


问:
Python Google Voice API Login Error: AttributeError: 'NoneType' object has no attribute 'group'
I was hoping somebody could help me figure out why I am getting this error when trying to login through the Google Voice API. I tried substituting the usr and pwd variables with the string literals and still got the same error. Please help!

```<code>from googlevoice import Voice
import keyring

if __name__ == '__main__':
    gv = Voice()
    usr = keyring.get_password('2', '2')
    pwd = keyring.get_password('1', '1')
    client = gv.login(usr,pwd)
</code>```

Throws the following error:

```<code>Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "/Users/<usrname>/workingProjects/<projectname>/lib/python3.10/site-packages/googlevoice/voice.py", line 76, in login
    ).group(1)
AttributeError: 'NoneType' object has no attribute 'group'
</code>```

Body:
I was hoping somebody could help me figure out why I am getting this error when trying to login through the Google Voice API. I tried substituting the usr and pwd variables with the string literals and still got the same error. Please help!

from googlevoice import Voice
import keyring

if __name__ == '__main__':
    gv = Voice()
    usr = keyring.get_password('2', '2')
    pwd = keyring.get_password('1', '1')
    client = gv.login(usr,pwd)

Throws the following error:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "/Users/<usrname>/workingProjects/<projectname>/lib/python3.10/site-packages/googlevoice/voice.py", line 76, in login
    ).group(1)
AttributeError: 'NoneType' object has no attribute 'group'


问:
Keras model_plot generates random text in figure
I am currently testing some dummy code about CNN.
I created the following tranditional model

```<code>model = Sequential()
model.add(Conv2D(16, (3, 3), activation = 'relu', padding='same', input_shape = (6,6,1)))
model.add(MaxPooling2D((2, 2), padding='same'))
model.add(Conv2D(32, (3, 3), activation = 'relu', padding='same', input_shape = (6,6,1)))
model.add(MaxPooling2D((2, 2), padding='same'))
model.add(Conv2D(64, (3, 3), activation = 'relu', padding='same', input_shape = (6,6,1)))
model.add(MaxPooling2D((2, 2), padding='same'))
model.add(Conv2D(64, (3, 3), activation = 'relu', padding='same', input_shape = (6,6,1)))
model.add(MaxPooling2D((2, 2), padding='same'))
model.add(Flatten())
model.add(Dense(units = 32, activation = 'relu'))
model.add(Dropout(0.2))
model.add(Dense(units = 1, activation = 'sigmoid'))
model.compile(loss = 'binary_crossentropy', optimizer = 'adam', metrics = ['accuracy'])
</code>```

Now, I am trying to plot the model using plot_model:

```<code>from tensorflow.keras.utils import plot_model
plot_model(model, to_file="test.png", dpi=120, show_shapes=True)
</code>```

However, the generated output figure includes random text that does not make sense for me:

I trying reinstalling the pydot and pydotplus again:

```<code>conda uninstall pydot
conda uninstall pydotplus
conda install pydot
conda install pydotplus
</code>```

However, no progress. Any help with that?

Body:
I am currently testing some dummy code about CNN.
I created the following tranditional model

model = Sequential()
model.add(Conv2D(16, (3, 3), activation = 'relu', padding='same', input_shape = (6,6,1)))
model.add(MaxPooling2D((2, 2), padding='same'))
model.add(Conv2D(32, (3, 3), activation = 'relu', padding='same', input_shape = (6,6,1)))
model.add(MaxPooling2D((2, 2), padding='same'))
model.add(Conv2D(64, (3, 3), activation = 'relu', padding='same', input_shape = (6,6,1)))
model.add(MaxPooling2D((2, 2), padding='same'))
model.add(Conv2D(64, (3, 3), activation = 'relu', padding='same', input_shape = (6,6,1)))
model.add(MaxPooling2D((2, 2), padding='same'))
model.add(Flatten())
model.add(Dense(units = 32, activation = 'relu'))
model.add(Dropout(0.2))
model.add(Dense(units = 1, activation = 'sigmoid'))
model.compile(loss = 'binary_crossentropy', optimizer = 'adam', metrics = ['accuracy'])

Now, I am trying to plot the model using plot_model:

from tensorflow.keras.utils import plot_model
plot_model(model, to_file="test.png", dpi=120, show_shapes=True)

However, the generated output figure includes random text that does not make sense for me:

I trying reinstalling the pydot and pydotplus again:

conda uninstall pydot
conda uninstall pydotplus
conda install pydot
conda install pydotplus

However, no progress. Any help with that?


问:
How to display 2 arrays in 1 table using angular?
I want to create the same table as the image. And, I need to add data from two arrays with the first two separators as a veg-topping and the second az non-veg-topping under the non-plant table header.

My list is:

```<code>this.vegtooping = [
 {vegproduct: 'Tomatoes($1.00)', cost :1 ,small:false, medium: false, larg: false, xlarg: false},
 {vegproduct: 'Onions($0.50)',cost :0.5, small:false, medium: false, larg: false, xlarg: false},
];
this.nonvegtooping = [
{nonvegproduct: 'Sausage ($1.00)', cost :1 ,small:false, medium: false, larg: false, xlarg: false},
];
</code>```
```<code><p-table [value]="vegtooping"  [value]="vegtooping" [tableStyle]="{'min-width': '50rem'}">
    <ng-template pTemplate="header">
        <tr>
            <th rowspan="2">Toppings</th>
            <th colspan="4">Pizza Size</th>
        </tr>

        <tr>
            <th>Small($5)</th>
            <th>Medium($7)</th>
            <th>Larg($8)</th>
            <th>Xxtra Larg($9)</th>
        </tr>
        <tr>
            <th colspan="5">
                veg Toppings
            </th>
        </tr>
    </ng-template>
    <ng-template pTemplate="body" let-vegtooping let-nonvegtooping>
        <tr>
            <td>{{nonvegtooping.vegproduct}}</td>
            <td> <p-checkbox >{{nonvegtooping.Small}}</p-checkbox></td>
            <td><p-checkbox>{{nonvegtooping.Medium}}</p-checkbox></td>
            <td> <p-checkbox>{{nonvegtooping.aa }}</p-checkbox></td>
            <td> <p-checkbox>{{nonvegtooping.ss }}</p-checkbox></td>
        </tr>
        <!-- <td >{{vegtooping.vegproduct}}</td>
        <td> <p-checkbox >{{vegtooping.Small}}</p-checkbox></td>
        <td><p-checkbox>{{vegtooping.Medium}}</p-checkbox></td>
        <td> <p-checkbox>{{vegtooping.lastYearProfit | currency: 'USD'}}</p-checkbox></td>
        <td> <p-checkbox>{{vegtooping.thisYearProfit | currency: 'USD'}}</p-checkbox></td>
        -->
    </ng-template>
</code>```

Body:
I want to create the same table as the image. And, I need to add data from two arrays with the first two separators as a veg-topping and the second az non-veg-topping under the non-plant table header.

My list is:

this.vegtooping = [
 {vegproduct: 'Tomatoes($1.00)', cost :1 ,small:false, medium: false, larg: false, xlarg: false},
 {vegproduct: 'Onions($0.50)',cost :0.5, small:false, medium: false, larg: false, xlarg: false},
];
this.nonvegtooping = [
{nonvegproduct: 'Sausage ($1.00)', cost :1 ,small:false, medium: false, larg: false, xlarg: false},
];

    <ng-template pTemplate="header">

            Toppings
            Pizza Size

            Small($5)
            Medium($7)
            Larg($8)
            Xxtra Larg($9)

                veg Toppings

    </ng-template>
    <ng-template pTemplate="body" let-vegtooping let-nonvegtooping>

            {{nonvegtooping.vegproduct}}

{{nonvegtooping.Small}}

{{nonvegtooping.Medium}}

{{nonvegtooping.aa }}

{{nonvegtooping.ss }}

    </ng-template>


问:
PHP Pest (with Laravel) tests running very slow in OSX Docker
I was developing an app locally using Laravel. For testing I was using Pest and tests were running fast, really fast. That was until I decided to Dockerize my app, now tests are running pretty slow.

What it used to run in 3 seconds now it's running in over a minute.

Here's my Dockerfile:

```<code>FROM php:8.1.12-fpm

ARG uid=1000
ARG user=macgiver

RUN apt-get update && apt-get install -y \
    git \
    curl \
    libpng-dev \
    libonig-dev \
    libxml2-dev \
    zip \
    unzip

# Install and enable xDebug
RUN pecl install xdebug \
    && docker-php-ext-enable xdebug

RUN apt-get clean && rm -rf /var/lib/apt/lists/*

# Install php modules required by laravel.
RUN docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd

# Create system user to run Composer and Artisan commands.
RUN useradd -G www-data,root -u $uid -d /home/$user $user
RUN mkdir -p /home/$user/.composer && \
    chown -R $user:$user /home/$user

# Install composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer

# Set working directory
WORKDIR /var/www

USER $user
</code>```

and this is my docker-compose:

```<code>version: "3.9"
services:
  app:
    build:
      context: ./
      dockerfile: Dockerfile
    image: dmc
    container_name: dmc-app
    restart: unless-stopped
    working_dir: /var/www/
    depends_on:
      - db
      - nginx
    volumes:
      - ./:/var/www/
      - ./docker/php/conf.d/xdebug.ini:/usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
      - ./docker/php/conf.d/error_reporting.ini:/usr/local/etc/php/conf.d/error_reporting.ini
    expose:
      - "9003"
    networks:
      - dmc-net

  nginx:
    image: nginx:1.23.2-alpine
    container_name: dmc-nginx
    restart: unless-stopped
    ports:
      - "8000:80"
    volumes:
      - ./:/var/www
      - ./docker-compose/nginx:/etc/nginx/conf.d
    networks:
      - dmc-net

  db:
    image: mysql:8.0.31
    container_name: dmc-db
    restart: unless-stopped
    # using 3307 on the host machine to avoid collisions in case there's a local MySQL instance installed already.
    ports:
      - "3307:3306"
    # use the variables declared in .env file
    environment:
      MYSQL_HOST: ${DB_HOST}
      MYSQL_DATABASE: ${DB_DATABASE}
      MYSQL_PASSWORD: ${DB_PASSWORD}
      MYSQL_ROOT_PASSWORD: abcd1234
      MYSQL_USER: ${DB_USERNAME}
      SERVICE_TAGS: dev
      SERVICE_NAME: mysql
    volumes:
      - ./docker-compose/mysql:/docker-entrypoint-initdb.d
      - mysql-data:/var/lib/mysql
    networks:
      - dmc-net

networks:
  dmc-net:
    driver: bridge

volumes:
  mysql-data:
</code>```

Any ideas?

Body:
I was developing an app locally using Laravel. For testing I was using Pest and tests were running fast, really fast. That was until I decided to Dockerize my app, now tests are running pretty slow.

What it used to run in 3 seconds now it's running in over a minute.

Here's my Dockerfile:

FROM php:8.1.12-fpm

ARG uid=1000
ARG user=macgiver

RUN apt-get update && apt-get install -y \
    git \
    curl \
    libpng-dev \
    libonig-dev \
    libxml2-dev \
    zip \
    unzip

# Install and enable xDebug
RUN pecl install xdebug \
    && docker-php-ext-enable xdebug

RUN apt-get clean && rm -rf /var/lib/apt/lists/*

# Install php modules required by laravel.
RUN docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd

# Create system user to run Composer and Artisan commands.
RUN useradd -G www-data,root -u $uid -d /home/$user $user
RUN mkdir -p /home/$user/.composer && \
    chown -R $user:$user /home/$user

# Install composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer

# Set working directory
WORKDIR /var/www

USER $user

and this is my docker-compose:

version: "3.9"
services:
  app:
    build:
      context: ./
      dockerfile: Dockerfile
    image: dmc
    container_name: dmc-app
    restart: unless-stopped
    working_dir: /var/www/
    depends_on:
      - db
      - nginx
    volumes:
      - ./:/var/www/
      - ./docker/php/conf.d/xdebug.ini:/usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
      - ./docker/php/conf.d/error_reporting.ini:/usr/local/etc/php/conf.d/error_reporting.ini
    expose:
      - "9003"
    networks:
      - dmc-net

  nginx:
    image: nginx:1.23.2-alpine
    container_name: dmc-nginx
    restart: unless-stopped
    ports:
      - "8000:80"
    volumes:
      - ./:/var/www
      - ./docker-compose/nginx:/etc/nginx/conf.d
    networks:
      - dmc-net

  db:
    image: mysql:8.0.31
    container_name: dmc-db
    restart: unless-stopped
    # using 3307 on the host machine to avoid collisions in case there's a local MySQL instance installed already.
    ports:
      - "3307:3306"
    # use the variables declared in .env file
    environment:
      MYSQL_HOST: ${DB_HOST}
      MYSQL_DATABASE: ${DB_DATABASE}
      MYSQL_PASSWORD: ${DB_PASSWORD}
      MYSQL_ROOT_PASSWORD: abcd1234
      MYSQL_USER: ${DB_USERNAME}
      SERVICE_TAGS: dev
      SERVICE_NAME: mysql
    volumes:
      - ./docker-compose/mysql:/docker-entrypoint-initdb.d
      - mysql-data:/var/lib/mysql
    networks:
      - dmc-net

networks:
  dmc-net:
    driver: bridge

volumes:
  mysql-data:

Any ideas?


问:
Need a more elegant solution of using templatefile
I'm trying to create bucket policies using a few templates, and dynamically passing in the name of the Principals. I did get it working, but I feel like there should be an easier and natural way of doing it than using flatten and a temporary variable like I did. Also I can't add policy_principals_read  = ["ignore"] and policy_principals_write = ["ignore"] to all the existing buckets (well that'd be super ugly)

The output produced is later imported by another module, hence the extra variables in the output shouldn't be a problem. The below code should be a reproducible example. Thank you for your time!

locals.tf

```<code>locals {

  principals = {
    "n-prod" = [
      "role/NP",
    ]
    "n-staging" = [
      "role/NS",
    ]
    "p-ro-roles" = [
      "p-dev",
      "p-prod",
    ]
    "ignore" = []
  }

  bucket_defaults = {
    server-data = {
      policy_name = "allow_read_only"
      policy_principals = [
        "p-ro-roles",
        "n-prod",
        "n-staging"
      ]
      policy_principals_read  = ["ignore"]
      policy_principals_write = ["ignore"]
    }

    client-data = {
      policy_name            = "allow_read_write"
      policy_principals      = []
      policy_principals_read = ["p-ro-roles"]
      policy_principals_write = [
        "n-prod",
        "n-staging"
      ]
    }
  }

  buckets = merge({
    for bucket_name, settings in local.bucket_defaults : bucket_name =>
    merge(settings, {
      policy = templatefile("policies/${settings.policy_name}.json.tmpl", {
        principals_read = setunion([
          for principal in flatten([settings.policy_principals_read, "ignore"]) : local.principals[principal]
        ]...)
        principals_write = setunion([
          for principal in flatten([settings.policy_principals_write, "ignore"]) : local.principals[principal]
        ]...)
        principals = setunion([
          for principal in flatten([settings.policy_principals, "ignore"]) : local.principals[principal]
        ]...)
        bucket_name = bucket_name
      })
    })
    }
  )
}
</code>```

outputs.tf

```<code>output "buckets" {
  value = local.buckets
}
</code>```

policies/allow_read_only.json.tmpl

```<code>{
  "Version" : "2012-10-17",
  "Id" : "AllowBucketRO",
  "Statement" : [
    {
      "Sid" : "AllowBucketRO",
      "Effect" : "Allow",
      "Principal" : {
        "AWS" : ${jsonencode(principals)}
      },
      "Action" : [
        "s3:Get*",
        "s3:List*"
      ],
      "Resource" : [
        "arn:aws:s3:::${bucket_name}",
        "arn:aws:s3:::${bucket_name}/*"
      ]
    }
  ]
}
</code>```

policies/allow_read_write.json.tmpl

```<code>{
  "Version": "2012-10-17",
  "Id" : "AllowBucketRW",
  "Statement": [
    {
      "Sid": "AllowConsoleAccess",
      "Effect": "Allow",
      "Principal" : {
        "AWS" : ${jsonencode(principals_write)}
      },
      "Action": [
        "s3:GetBucketAcl",
        "s3:GetBucketLocation",
        "s3:GetBucketPolicyStatus",
        "s3:GetBucketPublicAccessBlock"
      ],
      "Resource": [
        "arn:aws:s3:::${bucket_name}"
      ]
    },
    {
      "Sid" : "AllowBucketRO",
      "Effect" : "Allow",
      "Principal" : {
        "AWS" : ${jsonencode(principals_read)}
      },
      "Action" : [
        "s3:Get*",
        "s3:List*"
      ],
      "Resource" : [
        "arn:aws:s3:::${bucket_name}",
        "arn:aws:s3:::${bucket_name}/*"
      ]
    }
  ]
}
</code>```

EDIT:

Now I don't have to include policy_principals_read and policy_principals_write in bucket_defaults' which is a relief. I'm using try` to check if those attributes exist:

```<code>  buckets = merge({
    for bucket_name, settings in local.bucket_defaults : bucket_name =>
    merge(settings, {
      policy = templatefile("policies/${settings.policy_name}.json.tmpl", {
        principals_read = setunion([
          for principal in flatten([try(settings.policy_principals_read, ["ignore"]), "ignore"]) : local.principals[principal]
        ]...)
        principals_write = setunion([
          for principal in flatten([try(settings.policy_principals_read, ["ignore"]), "ignore"]) : local.principals[principal]
        ]...)
        principals = setunion([
          for principal in flatten([try(settings.policy_principals, ["ignore"]), "ignore"]) : local.principals[principal]
        ]...)
        bucket_name = bucket_name
      })
    })
    }
  )
</code>```

But I'd like to find a better way to perform flatten([try(settings.policy_principals_read, ["ignore"]), "ignore"])

Body:
I'm trying to create bucket policies using a few templates, and dynamically passing in the name of the Principals. I did get it working, but I feel like there should be an easier and natural way of doing it than using flatten and a temporary variable like I did. Also I can't add policy_principals_read  = ["ignore"] and policy_principals_write = ["ignore"] to all the existing buckets (well that'd be super ugly)

The output produced is later imported by another module, hence the extra variables in the output shouldn't be a problem. The below code should be a reproducible example. Thank you for your time!

locals.tf

locals {

  principals = {
    "n-prod" = [
      "role/NP",
    ]
    "n-staging" = [
      "role/NS",
    ]
    "p-ro-roles" = [
      "p-dev",
      "p-prod",
    ]
    "ignore" = []
  }

  bucket_defaults = {
    server-data = {
      policy_name = "allow_read_only"
      policy_principals = [
        "p-ro-roles",
        "n-prod",
        "n-staging"
      ]
      policy_principals_read  = ["ignore"]
      policy_principals_write = ["ignore"]
    }

    client-data = {
      policy_name            = "allow_read_write"
      policy_principals      = []
      policy_principals_read = ["p-ro-roles"]
      policy_principals_write = [
        "n-prod",
        "n-staging"
      ]
    }
  }

  buckets = merge({
    for bucket_name, settings in local.bucket_defaults : bucket_name =>
    merge(settings, {
      policy = templatefile("policies/${settings.policy_name}.json.tmpl", {
        principals_read = setunion([
          for principal in flatten([settings.policy_principals_read, "ignore"]) : local.principals[principal]
        ]...)
        principals_write = setunion([
          for principal in flatten([settings.policy_principals_write, "ignore"]) : local.principals[principal]
        ]...)
        principals = setunion([
          for principal in flatten([settings.policy_principals, "ignore"]) : local.principals[principal]
        ]...)
        bucket_name = bucket_name
      })
    })
    }
  )
}

outputs.tf

output "buckets" {
  value = local.buckets
}

policies/allow_read_only.json.tmpl

{
  "Version" : "2012-10-17",
  "Id" : "AllowBucketRO",
  "Statement" : [
    {
      "Sid" : "AllowBucketRO",
      "Effect" : "Allow",
      "Principal" : {
        "AWS" : ${jsonencode(principals)}
      },
      "Action" : [
        "s3:Get*",
        "s3:List*"
      ],
      "Resource" : [
        "arn:aws:s3:::${bucket_name}",
        "arn:aws:s3:::${bucket_name}/*"
      ]
    }
  ]
}

policies/allow_read_write.json.tmpl

{
  "Version": "2012-10-17",
  "Id" : "AllowBucketRW",
  "Statement": [
    {
      "Sid": "AllowConsoleAccess",
      "Effect": "Allow",
      "Principal" : {
        "AWS" : ${jsonencode(principals_write)}
      },
      "Action": [
        "s3:GetBucketAcl",
        "s3:GetBucketLocation",
        "s3:GetBucketPolicyStatus",
        "s3:GetBucketPublicAccessBlock"
      ],
      "Resource": [
        "arn:aws:s3:::${bucket_name}"
      ]
    },
    {
      "Sid" : "AllowBucketRO",
      "Effect" : "Allow",
      "Principal" : {
        "AWS" : ${jsonencode(principals_read)}
      },
      "Action" : [
        "s3:Get*",
        "s3:List*"
      ],
      "Resource" : [
        "arn:aws:s3:::${bucket_name}",
        "arn:aws:s3:::${bucket_name}/*"
      ]
    }
  ]
}

EDIT:

Now I don't have to include policy_principals_read and policy_principals_write in bucket_defaults' which is a relief. I'm using try` to check if those attributes exist:

  buckets = merge({
    for bucket_name, settings in local.bucket_defaults : bucket_name =>
    merge(settings, {
      policy = templatefile("policies/${settings.policy_name}.json.tmpl", {
        principals_read = setunion([
          for principal in flatten([try(settings.policy_principals_read, ["ignore"]), "ignore"]) : local.principals[principal]
        ]...)
        principals_write = setunion([
          for principal in flatten([try(settings.policy_principals_read, ["ignore"]), "ignore"]) : local.principals[principal]
        ]...)
        principals = setunion([
          for principal in flatten([try(settings.policy_principals, ["ignore"]), "ignore"]) : local.principals[principal]
        ]...)
        bucket_name = bucket_name
      })
    })
    }
  )

But I'd like to find a better way to perform flatten([try(settings.policy_principals_read, ["ignore"]), "ignore"])


问:
How to get list of running VMs from AzureML
I am a beginner with Python and with AzureML.
Currently, my task is to list all the running VMs (or Compute Instances) with status and (if running) for how long they ran.
I managed to connect to AzureML and list Subscriptions, Resource Groups and Workspaces, but I'm stuck on how to list running VMs now.
Here's the code that I have currently:

# get subscriptions list using credentials
subscription_client = SubscriptionClient(credentials)
sub_list = subscription_client.subscriptions.list()

print("Subscription ID".ljust(column_width) + "Display name")
print(separator)
for group in list(sub_list):
    print(f'{group.subscription_id:<{column_width}}{group.display_name}')
    subscription_id = group.subscription_id
    resource_client = ResourceManagementClient(credentials, subscription_id)

    group_list = resource_client.resource_groups.list()
    print("    Resource Groups:")
    for group in list(group_list):
        print(f"    {group.name}{group.location}")
        print("        Workspaces:")
        my_ml_client = Workspace.list(subscription_id, credentials, group.name)
        for ws in list(my_ml_client):
            try:
                print(f"        {ws}")
                if ws:
                    compute = ComputeTarget(workspace=ws, name=group.name)
                    print('Found existing compute: ' + group.name)
            except:()
```
<p>Please note that this is more or less a learning exercise and it's not the final shape of the code, I will refactor once I get it to work.</p>
<p>Edit: I found an easy way to do this:</p>
<pre class="lang-py prettyprint-override"><code>workspace = Workspace(
     subscription_id=subscription_id,
     resource_group=group.name,
     workspace_name=ws,
)
print(workspace.compute_targets)
</code>```

Edit2: If anyone stumbles on this question and is just beginning to understand Python+Azure just like I do, all this information is from official documentation (which is just hard to follow as a beginner).
The result from 'workspace.compute_targets' will contain both Compute Instances and AML Instances.
If you need to retrieve only the VMs (like I do) you need to take an extra step to filter the result like this:

if type(compute_list[vm]) == ComputeInstance:
```

Body:
I am a beginner with Python and with AzureML.
Currently, my task is to list all the running VMs (or Compute Instances) with status and (if running) for how long they ran.
I managed to connect to AzureML and list Subscriptions, Resource Groups and Workspaces, but I'm stuck on how to list running VMs now.
Here's the code that I have currently:

# get subscriptions list using credentials
subscription_client = SubscriptionClient(credentials)
sub_list = subscription_client.subscriptions.list()

print("Subscription ID".ljust(column_width) + "Display name")
print(separator)
for group in list(sub_list):
    print(f'{group.subscription_id:<{column_width}}{group.display_name}')
    subscription_id = group.subscription_id
    resource_client = ResourceManagementClient(credentials, subscription_id)

    group_list = resource_client.resource_groups.list()
    print("    Resource Groups:")
    for group in list(group_list):
        print(f"    {group.name}{group.location}")
        print("        Workspaces:")
        my_ml_client = Workspace.list(subscription_id, credentials, group.name)
        for ws in list(my_ml_client):
            try:
                print(f"        {ws}")
                if ws:
                    compute = ComputeTarget(workspace=ws, name=group.name)
                    print('Found existing compute: ' + group.name)
            except:()

Please note that this is more or less a learning exercise and it's not the final shape of the code, I will refactor once I get it to work.

Edit: I found an easy way to do this:

workspace = Workspace(
     subscription_id=subscription_id,
     resource_group=group.name,
     workspace_name=ws,
)
print(workspace.compute_targets)

Edit2: If anyone stumbles on this question and is just beginning to understand Python+Azure just like I do, all this information is from official documentation (which is just hard to follow as a beginner).
The result from 'workspace.compute_targets' will contain both Compute Instances and AML Instances.
If you need to retrieve only the VMs (like I do) you need to take an extra step to filter the result like this:

if type(compute_list[vm]) == ComputeInstance:


问:
One To Many (UniDirectional) Add Method On-One Side Gives Error
Error is:

at jdk.proxy2/jdk.proxy2.$Proxy106.save(Unknown Source) ~[na:na]  at
com.example.OneToManyUniDirectional.service.concretes.AuthorManager.addAuthor(AuthorManager.java:50)
~[classes/:na]    at
com.example.OneToManyUniDirectional.controller.AuthorController.addAuthors(AuthorController.java:21)
~[classes/:an]

I have no idead why this happening.

Author class:

```<code>public class Author {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name="name")
    private String firstName;
    @Column(name="surname")
    private String lastName;
    @OneToMany(cascade=CascadeType.MERGE,fetch = FetchType.EAGER)
    private Set<Book> books=new HashSet<>();

}
</code>```

Book Class:

```<code>public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String isbn;
    @Column(name="book_name")
    private String name;
}
</code>```

addAuthor method

```<code>    @Override
        public void addAuthor(CreateAuthor createAuthor){
          //  Book book=new Book();
   Author author=new Author();
            author.setFirstName(createAuthor.getFirstName());
            author.setLastName(createAuthor.getLastName());
            if(this.bookRepository.findById(createAuthor.getBook().getId()).isPresent()){
                UpdateBook updateBook=new UpdateBook();
                updateBook.setName(createAuthor.getBook().getName());
                updateBook.setIsbn(createAuthor.getBook().getIsbn());
                this.bookService.updateBook(updateBook,createAuthor.getBook().getId());
            }
            else{

                CreateBook createBook=new CreateBook();
                createBook.setName(createAuthor.getBook().getName());
                createBook.setIsbn(createAuthor.getBook().getIsbn());
                this.bookService.addBook(createBook);
 author.getBooks().add(createAuthor.getBook());
            }

            this.authorRepository.save(author);
        }
</code>```

Create Author:

```<code>@Data
@NoArgsConstructor
@AllArgsConstructor
public class CreateAuthor {
    private String firstName;
    private String lastName;
    private Book book;
}
</code>```

Controller

```<code>  @PostMapping("/authors")
    public void addAuthors(@RequestBody CreateAuthor createAuthor){
        this.authorService.addAuthor(createAuthor);
    }
</code>```

Also create book and  updateBook classes does not has id properties in it.

Body:
Error is:

at jdk.proxy2/jdk.proxy2.$Proxy106.save(Unknown Source) ~[na:na]  at
com.example.OneToManyUniDirectional.service.concretes.AuthorManager.addAuthor(AuthorManager.java:50)
~[classes/:na]    at
com.example.OneToManyUniDirectional.controller.AuthorController.addAuthors(AuthorController.java:21)
~[classes/:an]

I have no idead why this happening.

Author class:

public class Author {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name="name")
    private String firstName;
    @Column(name="surname")
    private String lastName;
    @OneToMany(cascade=CascadeType.MERGE,fetch = FetchType.EAGER)
    private Set<Book> books=new HashSet<>();

}

Book Class:

public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String isbn;
    @Column(name="book_name")
    private String name;
}

addAuthor method

    @Override
        public void addAuthor(CreateAuthor createAuthor){
          //  Book book=new Book();
   Author author=new Author();
            author.setFirstName(createAuthor.getFirstName());
            author.setLastName(createAuthor.getLastName());
            if(this.bookRepository.findById(createAuthor.getBook().getId()).isPresent()){
                UpdateBook updateBook=new UpdateBook();
                updateBook.setName(createAuthor.getBook().getName());
                updateBook.setIsbn(createAuthor.getBook().getIsbn());
                this.bookService.updateBook(updateBook,createAuthor.getBook().getId());
            }
            else{

                CreateBook createBook=new CreateBook();
                createBook.setName(createAuthor.getBook().getName());
                createBook.setIsbn(createAuthor.getBook().getIsbn());
                this.bookService.addBook(createBook);
 author.getBooks().add(createAuthor.getBook());
            }

            this.authorRepository.save(author);
        }

Create Author:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class CreateAuthor {
    private String firstName;
    private String lastName;
    private Book book;
}

Controller

  @PostMapping("/authors")
    public void addAuthors(@RequestBody CreateAuthor createAuthor){
        this.authorService.addAuthor(createAuthor);
    }

Also create book and  updateBook classes does not has id properties in it.