问:
Type of expression is ambiguous without more context when fetching core data
In my swift code the goal is to fetch an attribute and display it on an image view. I am having trouble fetching the attribute pic which is a binary data.

if let imageData = Pictucre[imageNo].pic

```<code>    func getImage(imageNo:Int) {
       // first check the array bounds
        let info = CoredataHandler.shareInstance.fetchImage()

        print("image count is", info.count)
       if info.count > imageNo {

           // check if the data is available

           if let imageData = Pictucre[imageNo].pic

            {
           imagePlace.image = UIImage(data: imageData)

           } else {
               // no data
               print("data is empty Textss")
           }
       } else {
           // image number is greater than array bounds
           print("you are asking out of bounds")
       }
    }

}

class CoredataHandler : NSManagedObject {
    static let shareInstance = CoredataHandler()
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    private class func getContext() -> NSManagedObjectContext {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate

        return appDelegate.persistentContainer.viewContext
    }
    func saveImage(data: Data) {
        let imageInstance = Pictucre(context: context)

        imageInstance.pic = data

        do {
            try context.save()

        } catch {
            print(error.localizedDescription)
        }
    }

    class func fetchObject() -> [Pictucre]?
    {
        let context = getContext()
        var max : [Pictucre]? = nil
        do {
            max = try context.fetch(Pictucre.fetchRequest())

            return max

        } catch {
            return max
        }

    }

    func fetchImage() -> [Pictucre] {

        var fetchingImage = [Pictucre]()
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Max")

        do {

            fetchingImage = try context.fetch(fetchRequest) as! [Pictucre]
        } catch {
            print("Error while fetching the image")
        }

        return fetchingImage
    }

}
</code>```

pic of core data
the error states Type of expression is ambiguous without more context. It is a runtime error

I tried adding a ! to pic making it pic! and that still causes a runtime error.

Body:
In my swift code the goal is to fetch an attribute and display it on an image view. I am having trouble fetching the attribute pic which is a binary data.

if let imageData = Pictucre[imageNo].pic

    func getImage(imageNo:Int) {
       // first check the array bounds
        let info = CoredataHandler.shareInstance.fetchImage()

        print("image count is", info.count)
       if info.count > imageNo {

           // check if the data is available

           if let imageData = Pictucre[imageNo].pic

            {
           imagePlace.image = UIImage(data: imageData)

           } else {
               // no data
               print("data is empty Textss")
           }
       } else {
           // image number is greater than array bounds
           print("you are asking out of bounds")
       }
    }

}

class CoredataHandler : NSManagedObject {
    static let shareInstance = CoredataHandler()
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    private class func getContext() -> NSManagedObjectContext {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate

        return appDelegate.persistentContainer.viewContext
    }
    func saveImage(data: Data) {
        let imageInstance = Pictucre(context: context)

        imageInstance.pic = data

        do {
            try context.save()

        } catch {
            print(error.localizedDescription)
        }
    }

    class func fetchObject() -> [Pictucre]?
    {
        let context = getContext()
        var max : [Pictucre]? = nil
        do {
            max = try context.fetch(Pictucre.fetchRequest())

            return max

        } catch {
            return max
        }

    }

    func fetchImage() -> [Pictucre] {

        var fetchingImage = [Pictucre]()
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Max")

        do {

            fetchingImage = try context.fetch(fetchRequest) as! [Pictucre]
        } catch {
            print("Error while fetching the image")
        }

        return fetchingImage
    }

}

pic of core data
the error states Type of expression is ambiguous without more context. It is a runtime error

I tried adding a ! to pic making it pic! and that still causes a runtime error.


来源: stackexchange

问:
Download fits files that are in the form of URLs line by line in a txt file using python and saving them iteratively in a folder
So my text file contains 20 odd lines,each line having url that has some fits file.I want to read them,download from url and iteratively save them in a uniform manner(using numbers lets say) in a given folder. I want to use python here

I also would like to save the fits files as jpeg in a folder later on again iteratively.

ContentLicense: CC BY-SA 4.0


问:
How do I make a nextjs middleware that checks to see if an authenticated user is an admin?
I'm essentially trying to build a next middleware that checks if a logged in firebase user is an admin. The problem is that I can't get a firebase authenticated user in src/middleware.ts

Code

```<code>import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { onAuthStateChanged } from 'firebase/auth';
import { auth } from './firebase';

// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
  if(request.url.includes('/admin')) {
    onAuthStateChanged(auth, (user) => {
      console.log(user);
    });
  }
  // return NextResponse.redirect(new URL('/', request.url))
}
</code>```

The console.log(user) outputs null. If I change the console to console.log(auth); I get currentUser: null,.

I know the user is logged in because I can use the same firebase function to retrieve the user with an onClick. For example this works:

```<code>const GetUser = () => {
  const buttonClick = async () => {
    await onAuthStateChanged(auth, (user) => {
      console.log(user);
    });
  }

  return (<button onClick={buttonClick}>Get Logged in user</button>)
}

</code>```

How do I get a firebase authenticated user in a next middleware?

Body:
I'm essentially trying to build a next middleware that checks if a logged in firebase user is an admin. The problem is that I can't get a firebase authenticated user in src/middleware.ts

Code

import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { onAuthStateChanged } from 'firebase/auth';
import { auth } from './firebase';

// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
  if(request.url.includes('/admin')) {
    onAuthStateChanged(auth, (user) => {
      console.log(user);
    });
  }
  // return NextResponse.redirect(new URL('/', request.url))
}

The console.log(user) outputs null. If I change the console to console.log(auth); I get currentUser: null,.

I know the user is logged in because I can use the same firebase function to retrieve the user with an onClick. For example this works:

const GetUser = () => {
  const buttonClick = async () => {
    await onAuthStateChanged(auth, (user) => {
      console.log(user);
    });
  }

  return (<button onClick={buttonClick}>Get Logged in user</button>)
}

How do I get a firebase authenticated user in a next middleware?


问:
How to get Capability Name on Android App Actions when Intents Triggered?
I want to know the name of the capability when some Intent was Triggered, like

```<code>    <!-- shortcuts.xml -->
    <capability android:name="actions.intent.GET_THING">
</code>```

Here my code for logging the intents, that only shows the result of intents.

```<code>    <!-- MainActivity.kt -->
    val bundle : Bundle = intent.extras ?: return

    bundle.keySet().forEach{ key ->
        Log.d("debug_intents", "[$key=${bundle.get(key)}]");
    }

    Log.v("debug_intents", intent.action.toString())
</code>```

any idea?

Body:
I want to know the name of the capability when some Intent was Triggered, like

    <capability android:name="actions.intent.GET_THING">

Here my code for logging the intents, that only shows the result of intents.

    val bundle : Bundle = intent.extras ?: return

    bundle.keySet().forEach{ key ->
        Log.d("debug_intents", "[$key=${bundle.get(key)}]");
    }

    Log.v("debug_intents", intent.action.toString())

any idea?


问:
Why can I only clone using my username in the url of the repository?
Last days I've been only able to clone repositories by using my user name in it.

Suppose the url is  https://github.com/company/repo.git. When I try

```<code>$ git clone https://github.com/company/repo.git
</code>```

it says that the repository was not found. It used to work fine before. Now I have to do

```<code>$ git clone https://username@github.com/company/repo.git
</code>```

in order for it to work. I think I messed up some configuration when I used $ gh auth login and now I can't seem to let things working as they were before and it's causing me a lot of trouble.

How can I make things work as they did before?

Body:
Last days I've been only able to clone repositories by using my user name in it.

Suppose the url is  https://github.com/company/repo.git. When I try

$ git clone https://github.com/company/repo.git

it says that the repository was not found. It used to work fine before. Now I have to do

$ git clone https://username@github.com/company/repo.git

in order for it to work. I think I messed up some configuration when I used $ gh auth login and now I can't seem to let things working as they were before and it's causing me a lot of trouble.

How can I make things work as they did before?


问:
How to use exact-active-class for child components in Vue 3 router-link
I want when entering a child component, the current menu item will still receive the active class, but because I can't use the child router in vue 3, exact-active-class doesn't get it.
It looks like this:

I want when I go to the detail page of S3 Storage, the active class of the menu bar is still activated.
It will look like this:

It will look like this:
Router/index.js

{
      path:"/aws3",
      name:"aws3",
      component: () => import("../views/Aws3Storage.vue")
    },

    {
      path:"/aws3detail/:id",
      name:"aws3detail",
      component: () => import("../views/DetailAWS3.vue")
    }
```
<p><strong>menu.vue</strong></p>
<pre class="lang-js prettyprint-override"><code> <router-link exact-active-class="bg-purple-400 text-white"
              <span  class="ml-4">{{ page.name }}</span>

            </router-link>
</code>```

Hope there will be a solution for me, thanks everyone

Body:
I want when entering a child component, the current menu item will still receive the active class, but because I can't use the child router in vue 3, exact-active-class doesn't get it.
It looks like this:

I want when I go to the detail page of S3 Storage, the active class of the menu bar is still activated.
It will look like this:

It will look like this:
Router/index.js

{
      path:"/aws3",
      name:"aws3",
      component: () => import("../views/Aws3Storage.vue")
    },

    {
      path:"/aws3detail/:id",
      name:"aws3detail",
      component: () => import("../views/DetailAWS3.vue")
    }

menu.vue

 <router-link exact-active-class="bg-purple-400 text-white"
              {{ page.name }}

            </router-link>

Hope there will be a solution for me, thanks everyone


问:
Adding OneSignal dependency causing Activity Reload
I have implemented OneSignal in my app which is causing the Launch Activity to reload on the very first App Launch. I even removed the OneSignal initialization code and found out that just adding the OneSignal dependency in app's build.gradle is causing the issue. The weird thing is that it happens on the very first app launch and not on subsequent launches.

On investigation, I found out that some Configuration change is happening which is causing the activity to reload. By Overriding OnPause method of apps Launch Activity and calling getChangingConfigurations(); I got the int value of the config that has changed to be -2147483648 . On further investigation, I found out that the said constant value relates to SIGNAL_STRENGTH_UNSPECIFIED which can be found out HERE . Now I am out of ideas how to fix it. Any help is appreciated. TIA


问:
Problem in connectiong Xabber Beta 3.0.2 with openfire (installed in virtual machine)
I have installed openfire from https://bitnami.com/stack/openfire/virtual-machine on my local machine and got access to its admin panel too.
I have installed Xabber Beta 3.0.2 on Samsung A71 and trying to connect it to open fire.
got following error:
yuser@192.168.100.xx
Connection error:
orgs.jivessoftware.smack.smackexception : The following addresses failed: 'null:5222' failed because:/192.168.100.51 exception: java.net.socketTimeoutexception: failed to connect /192.168.100.51(port 5222) from 192.168.31.185 (port 42764) after 3000ms at com.xabber.xmpp.smack.XMPPTCPconnection.connectUsingconfiguration(Unknown source:312) at xabber.xmpp.smack.XMPPTCPconnection.connectInternel(UnknownSource:5) at orgs.jive.smack.AbstractXMPPconnection.connect(Unknown Source:27) at
com.xabber.android.data.connection.ConnectionThread.connectAndLogin(UnknoenSource:207)
at com.xabber.android.data.connection.connectionThread$1.run(UnknownSOurce:8) at Java.lang.Thread.run(Thread.java:1012)

please comment and provide solution.
i am really stuck :(

please help in resolving the issue in connection error


问:
Push data into media server using Stream key and URL
Looking forward to replicate OBS streaming function, push data into media server using stream key and URL to connect with server. Expecting a function or source code, at least an algorithm, and relevant reference to perform.</p>


问:
SQLSTATE[08S01]: [Microsoft][ODBC Driver 18 for SQL Server]SSL Provider: [error:140E0197:SSL routines:SSL_shutdown:shutdown while in init]
It's a new experience for me, using Laravel with SQL Server.

My issue is, some of it shows this error message SQLSTATE[08S01]: [Microsoft][ODBC Driver 18 for SQL Server]SSL Provider: [error:140E0197:SSL routines:SSL_shutdown:shutdown while in init] when INSERT or UPDATE the data. It's happened randomly.

Here's my connection string on Laravel.

Please tell me, how to resolve this issue.


问:
Cache API response and access it in the upcoming API request
I have a problem where I have to trigger a airflow dag using an API, but the difference between two api request have to be 1 seconds. As this project is time sensitive I cannot put time.sleep(1). so i was thinking of cache in a way like "i will cache the request of (n)th api request and before making (n+1)th api request i will check the timestamp is present in the cache or not, if present then i will add 1 seconds to a time stamp and then make api request else make an api request directly.

```<code># making API request
                import json
                import requests
                from requests.auth import HTTPBasicAuth
                import datetime

                utc_date = datetime.datetime.utcnow()
                formatted_date = utc_date.strftime('%Y-%m-%dT%H:%M:%SZ')

                data = {
                    "conf": {
                        "flag": 0,
                        "files": details["filename"],
                        "upload_path": details["upload_path"],
                        "tmp_file_path": f,
                        "tmp_path": details["tmp_path"],
                        "dataset_id": details["dataset_id"],
                },
                    "dag_run_id": str(uuid.uuid4()),
                    "logical_date": str(formatted_date),
                }
                headers={
                    'Content-type':'application/json',
                    'Accept':'application/json'
                }
                json_payload = json.dumps(data)
                r = requests.post("http://localhost:8080/api/v1/dags/working_1/dagRuns", auth=HTTPBasicAuth("airflow", "airflow"), data=json_payload, headers=headers)
                print(r.status_code)
                print(r.text)
</code>```

Here in the above code the logical_date you see have to different in each api request.

```<code># This is the response i get from r.text and this i want to cache, so that i can use make use of it in next api request.

 "dag_id": "working_1",
  "dag_run_id": "c9ac60a5-705b-4598-a956-8d26454b26ce",
  "end_date": null,
  "execution_date": "2022-12-13T12:01:57+00:00",
  "external_trigger": true,
  "logical_date": "2022-12-13T12:01:57+00:00",
  "start_date": null,
  "state": "queued"
}
</code>```

So, from the r.text response which is there in the cache i want to get the value of logical date and compare it with current timestamp which will be sending as logical date in next api request. if matched then i will add 1 second and then send an request.

PS: I cannot add milliseconds, because the logical_date format is this only

Thanks,

Body:
I have a problem where I have to trigger a airflow dag using an API, but the difference between two api request have to be 1 seconds. As this project is time sensitive I cannot put time.sleep(1). so i was thinking of cache in a way like "i will cache the request of (n)th api request and before making (n+1)th api request i will check the timestamp is present in the cache or not, if present then i will add 1 seconds to a time stamp and then make api request else make an api request directly.

# making API request
                import json
                import requests
                from requests.auth import HTTPBasicAuth
                import datetime

                utc_date = datetime.datetime.utcnow()
                formatted_date = utc_date.strftime('%Y-%m-%dT%H:%M:%SZ')

                data = {
                    "conf": {
                        "flag": 0,
                        "files": details["filename"],
                        "upload_path": details["upload_path"],
                        "tmp_file_path": f,
                        "tmp_path": details["tmp_path"],
                        "dataset_id": details["dataset_id"],
                },
                    "dag_run_id": str(uuid.uuid4()),
                    "logical_date": str(formatted_date),
                }
                headers={
                    'Content-type':'application/json',
                    'Accept':'application/json'
                }
                json_payload = json.dumps(data)
                r = requests.post("http://localhost:8080/api/v1/dags/working_1/dagRuns", auth=HTTPBasicAuth("airflow", "airflow"), data=json_payload, headers=headers)
                print(r.status_code)
                print(r.text)

Here in the above code the logical_date you see have to different in each api request.

# This is the response i get from r.text and this i want to cache, so that i can use make use of it in next api request.

 "dag_id": "working_1",
  "dag_run_id": "c9ac60a5-705b-4598-a956-8d26454b26ce",
  "end_date": null,
  "execution_date": "2022-12-13T12:01:57+00:00",
  "external_trigger": true,
  "logical_date": "2022-12-13T12:01:57+00:00",
  "start_date": null,
  "state": "queued"
}

So, from the r.text response which is there in the cache i want to get the value of logical date and compare it with current timestamp which will be sending as logical date in next api request. if matched then i will add 1 second and then send an request.

PS: I cannot add milliseconds, because the logical_date format is this only

Thanks,


问:
Minimizing Number of Hops When Passing Attendance Sheet in Class
My CS class has 7 rows and 11 columns of seats. I have noticed that whenever my teacher conducts attendance checks and passes one person a piece of paper to hand to everyone in my class, someone is usually required to get up and physically move to pass the paper. The usual seating positions of the students are

```<code>0,9
0,10
1,0
1,10
2,9
2,10
3,4
3,10
4,2
4,6
4,7
4,8
5,0
5,5
6,2
6,10
</code>```

with 0,9 being the starting vertex where the professor begins to pass the attendance sheet. How would I minimize number of hops (i.e. number of times someone has to get up to pass sheet) between passing this sheet? This isn't a homework assignment or anything, I am just genuinely curious. Also, it is sometimes a bit annoying when people are getting up to pass the attendance sheet during the lecture.

I thought about using Dijkstra's algorithm to calculate this (the adjacency matrix implementation), but I am not entirely sure how I would calculate the weights between seats? Any consideration for this (ultimately) meaningless problem would be appreciated.

Body:
My CS class has 7 rows and 11 columns of seats. I have noticed that whenever my teacher conducts attendance checks and passes one person a piece of paper to hand to everyone in my class, someone is usually required to get up and physically move to pass the paper. The usual seating positions of the students are

0,9
0,10
1,0
1,10
2,9
2,10
3,4
3,10
4,2
4,6
4,7
4,8
5,0
5,5
6,2
6,10

with 0,9 being the starting vertex where the professor begins to pass the attendance sheet. How would I minimize number of hops (i.e. number of times someone has to get up to pass sheet) between passing this sheet? This isn't a homework assignment or anything, I am just genuinely curious. Also, it is sometimes a bit annoying when people are getting up to pass the attendance sheet during the lecture.

I thought about using Dijkstra's algorithm to calculate this (the adjacency matrix implementation), but I am not entirely sure how I would calculate the weights between seats? Any consideration for this (ultimately) meaningless problem would be appreciated.


问:
How can you properly Destroy() your chart when using react-chartjs-2 and function components?
Getting the error: "Uncaught Error: Canvas is already in use. Chart with ID '0' must be destroyed before the canvas with ID '' can be reused." which led me to destroy(). Looks simple enough to use for vanilla JS but how can we use this function on the react-chartjs-2 components such as  or ?

Chart is being rendered after an API call and I'm using conditional rendering to render the component. E.g.

```<code>`{response && (
```

<Line />

```
)}`
</code>```

This stack solves it with class components but I'd prefer to stick with functional components.
React & Chartjs: How can I best destroy my chart when re-rendering?

Body:
Getting the error: "Uncaught Error: Canvas is already in use. Chart with ID '0' must be destroyed before the canvas with ID '' can be reused." which led me to destroy(). Looks simple enough to use for vanilla JS but how can we use this function on the react-chartjs-2 components such as  or ?

Chart is being rendered after an API call and I'm using conditional rendering to render the component. E.g.

`{response && (
```
<div style={{ width: "700px" }}>
<Line />
</div>
```
)}`

This stack solves it with class components but I'd prefer to stick with functional components.
React & Chartjs: How can I best destroy my chart when re-rendering?


问:
Slice plot in vtk
I have a polydata file containing 3D coordinates of the mesh (as vtkPoints) and temperature at each point as an attribute. I want to plot the temperature as a slice plot (at three elevations) over the geometry. I managed to get the data slices at different elevation using vtkClipPolyData function. However, I am unable to find a good example showing how to interpolate the value at each of these points and plot the data. Really appreciate if someone can help me on this.

I tried to render the clipped data directly by increasing the point size from actor property,
actor.GetProperty().SetPointSize(5)
however, this gives a pixelated plot. See plot here

Title: Slice plot in vtk


问:
How to convert Word Doc to pdf in Android? docx4j
Errors:
Caused by: org.docx4j.openpackaging.exceptions.InvalidFormatException: Bad [Content_Types].xml
##docx4j##
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'javax.xml.bind.Unmarshaller javax.xml.bind.JAXBContext.createUnmarshaller()' on a null object reference

```<code>
</code>```

dependencies

```<code>
implementation 'org.docx4j:docx4j-JAXB-ReferenceImpl:8.0.0'
implementation 'org.docx4j:docx4j-JAXB-Internal:8.0.0'
implementation 'org.docx4j:docx4j-JAXB-MOXy:8.0.0'
implementation 'org.docx4j:docx4j-export-fo:8.0.0'
implementation 'org.docx4j:docx4j-MOXy-JAXBContext:3.0.0'
implementation 'stax:stax:1.2.0'
</code>```
```<code>private void Word_to_PDF(String path, String outPath) {
    try {

        InputStream templateInputStream = new FileInputStream(path);
        WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(templateInputStream);
        MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();

        String outputfilepath = outPath;
        FileOutputStream os = new FileOutputStream(outputfilepath);
        Docx4J.toPDF(wordMLPackage,os);
        os.flush();
        os.close();
    } catch (Throwable e) {

        e.printStackTrace();
    }

}
</code>```

Body:
Errors:
Caused by: org.docx4j.openpackaging.exceptions.InvalidFormatException: Bad [Content_Types].xml
##docx4j##
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'javax.xml.bind.Unmarshaller javax.xml.bind.JAXBContext.createUnmarshaller()' on a null object reference

dependencies

implementation 'org.docx4j:docx4j-JAXB-ReferenceImpl:8.0.0'
implementation 'org.docx4j:docx4j-JAXB-Internal:8.0.0'
implementation 'org.docx4j:docx4j-JAXB-MOXy:8.0.0'
implementation 'org.docx4j:docx4j-export-fo:8.0.0'
implementation 'org.docx4j:docx4j-MOXy-JAXBContext:3.0.0'
implementation 'stax:stax:1.2.0'

private void Word_to_PDF(String path, String outPath) {
    try {

        InputStream templateInputStream = new FileInputStream(path);
        WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(templateInputStream);
        MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();

        String outputfilepath = outPath;
        FileOutputStream os = new FileOutputStream(outputfilepath);
        Docx4J.toPDF(wordMLPackage,os);
        os.flush();
        os.close();
    } catch (Throwable e) {

        e.printStackTrace();
    }

}


问:
Jupyter notebook error on closing the console after updating to windows 11 22H2
I have recently updated my windows 11 to version 22H2. Since then whenever I want to close the Jupyter notebook's console after I'm done, I get a popup error saying The application was unable to start correctly (0x0000142).. The annoying part is that I have to click OK for about ten times before it stops showing again and again.

I have Anaconda with Python 3.9 and I open jupyter-notebook using the command line in whichever location that is needed. I have two laptops and the same scenario has happened on both of them exactly after updating windows.


问:
vba IF function for Combo Boxes
I am trying to create a user form on vba Excel, and want it so that if a combo box displays a certain value, the next combo box will only show certain options. For Example, if shopping is chosen in the first one then only the options starting with "Shopping -" will display in OptSubCategory

```<code>Sub Reset()

    Dim iRow As Long

    iRow = [Counta(Database!A:A)] 'indentify the last row

    With UserForm1
        .TxtItem.Value = ""
        .TxtAmount.Value = ""
        .OptIncome.Value = False
        .OptExpense.Value = False
        .CmbCategory.Clear
            .CmbCategory.AddItem "Income"
            .CmbCategory.AddItem "Dining"
            .CmbCategory.AddItem "Shopping"
            .CmbCategory.AddItem "Travel"
            .CmbCategory.AddItem "Holiday"
            .CmbCategory.AddItem "Fine"
            .CmbCategory.AddItem "Bill"
        .CmbSubCategory.Clear
            .CmbSubCategory.AddItem "Dining - Food"
            .CmbSubCategory.AddItem "Dining - Coffee"
            .CmbSubCategory.AddItem "Dining - Alcohol"
            .CmbSubCategory.AddItem "Dining - Other"
            .CmbSubCategory.AddItem "Shopping - Food"
            .CmbSubCategory.AddItem "Shopping - Toiletries"
            .CmbSubCategory.AddItem "Shopping - Amazon"
            .CmbSubCategory.AddItem "Shopping - Other"
            .CmbSubCategory.AddItem "Travel - Taxi"
            .CmbSubCategory.AddItem "Travel - Train"
            .CmbSubCategory.AddItem "Travel - Bus"
            .CmbSubCategory.AddItem "Travel - Fuel"
            .CmbSubCategory.AddItem "Travel - Other"
            .CmbSubCategory.AddItem "Holiday - Flights"
            .CmbSubCategory.AddItem "Holiday - Hotel"
            .CmbSubCategory.AddItem "Fine - Parking"
            .CmbSubCategory.AddItem "Fine - Driving"
            .CmbSubCategory.AddItem "Fine - Accomodation"
            .CmbSubCategory.AddItem "Fine - Other"
            .CmbSubCategory.AddItem "Bills - Mortgage"
            .CmbSubCategory.AddItem "Bills - Gas and Electric"
            .CmbSubCategory.AddItem "Bills - Council Tax"
            .CmbSubCategory.AddItem "Bills - Water"
            .CmbSubCategory.AddItem "Bills - Internet"
            .CmbSubCategory.AddItem "Bills - Other"
            .CmbSubCategory.AddItem "Income - bet365 Wage"
            .CmbSubCategory.AddItem "Income - Secondment Wage"
        .OptMonzo.Value = False
        .OptNatwest.Value = False
        .OptSavings.Value = False

        .LstDatabase.ColumnCount = 10
        .LstDatabase.ColumnHeads = True

        .LstDatabase.ColumnWidths = "30,60,75,40,60,45,55,70,70,70"

            If iRow > 1 Then
            .LstDatabase.RowSource = "Database!A2:I" & iRow
            Else
            .LstDatabase.RowSource = "Database!A2:I2"
            End If
    End With
End Sub

Sub Submit()
    Dim sh As Worksheet
    Dim iRow As Long

    Set sh = ThisWorkbook.Sheets("Database")

    iRow = [Counta(Database!A:A)] + 1

    With sh
        .Cells(iRow, 1) = iRow - 1
        .Cells(iRow, 2) = UserForm1.TxtItem.Value
        .Cells(iRow, 3) = IIf(UserForm1.OptIncome = True, UserForm1.TxtAmount.Value, "")
        .Cells(iRow, 4) = IIf(UserForm1.OptExpense = True, UserForm1.TxtAmount.Value, "")
        .Cells(iRow, 5) = UserForm1.CmbCategory.Value
        .Cells(iRow, 6) = UserForm1.CmbSubCategory.Value
        .Cells(iRow, 8) = IIf(UserForm1.OptNatwest = True, "Yes", "")
        .Cells(iRow, 9) = IIf(UserForm1.OptSavings = True, "Yes", "")
        .Cells(iRow, 10) = IIf(UserForm1.OptMonzo = True, "Yes", "")
        .Cells(iRow, 7) = [Text(Now(), "DD-MM-YYYY")]
    End With
</code>```

I have checked on youtube and other sites, however can not find an answer and have tried to figure it out myself with no luck

Title: vba IF function for Combo Boxes

Body:
I am trying to create a user form on vba Excel, and want it so that if a combo box displays a certain value, the next combo box will only show certain options. For Example, if shopping is chosen in the first one then only the options starting with "Shopping -" will display in OptSubCategory

Sub Reset()

    Dim iRow As Long

    iRow = [Counta(Database!A:A)] 'indentify the last row

    With UserForm1
        .TxtItem.Value = ""
        .TxtAmount.Value = ""
        .OptIncome.Value = False
        .OptExpense.Value = False
        .CmbCategory.Clear
            .CmbCategory.AddItem "Income"
            .CmbCategory.AddItem "Dining"
            .CmbCategory.AddItem "Shopping"
            .CmbCategory.AddItem "Travel"
            .CmbCategory.AddItem "Holiday"
            .CmbCategory.AddItem "Fine"
            .CmbCategory.AddItem "Bill"
        .CmbSubCategory.Clear
            .CmbSubCategory.AddItem "Dining - Food"
            .CmbSubCategory.AddItem "Dining - Coffee"
            .CmbSubCategory.AddItem "Dining - Alcohol"
            .CmbSubCategory.AddItem "Dining - Other"
            .CmbSubCategory.AddItem "Shopping - Food"
            .CmbSubCategory.AddItem "Shopping - Toiletries"
            .CmbSubCategory.AddItem "Shopping - Amazon"
            .CmbSubCategory.AddItem "Shopping - Other"
            .CmbSubCategory.AddItem "Travel - Taxi"
            .CmbSubCategory.AddItem "Travel - Train"
            .CmbSubCategory.AddItem "Travel - Bus"
            .CmbSubCategory.AddItem "Travel - Fuel"
            .CmbSubCategory.AddItem "Travel - Other"
            .CmbSubCategory.AddItem "Holiday - Flights"
            .CmbSubCategory.AddItem "Holiday - Hotel"
            .CmbSubCategory.AddItem "Fine - Parking"
            .CmbSubCategory.AddItem "Fine - Driving"
            .CmbSubCategory.AddItem "Fine - Accomodation"
            .CmbSubCategory.AddItem "Fine - Other"
            .CmbSubCategory.AddItem "Bills - Mortgage"
            .CmbSubCategory.AddItem "Bills - Gas and Electric"
            .CmbSubCategory.AddItem "Bills - Council Tax"
            .CmbSubCategory.AddItem "Bills - Water"
            .CmbSubCategory.AddItem "Bills - Internet"
            .CmbSubCategory.AddItem "Bills - Other"
            .CmbSubCategory.AddItem "Income - bet365 Wage"
            .CmbSubCategory.AddItem "Income - Secondment Wage"
        .OptMonzo.Value = False
        .OptNatwest.Value = False
        .OptSavings.Value = False

        .LstDatabase.ColumnCount = 10
        .LstDatabase.ColumnHeads = True

        .LstDatabase.ColumnWidths = "30,60,75,40,60,45,55,70,70,70"

            If iRow > 1 Then
            .LstDatabase.RowSource = "Database!A2:I" & iRow
            Else
            .LstDatabase.RowSource = "Database!A2:I2"
            End If
    End With
End Sub

Sub Submit()
    Dim sh As Worksheet
    Dim iRow As Long

    Set sh = ThisWorkbook.Sheets("Database")

    iRow = [Counta(Database!A:A)] + 1

    With sh
        .Cells(iRow, 1) = iRow - 1
        .Cells(iRow, 2) = UserForm1.TxtItem.Value
        .Cells(iRow, 3) = IIf(UserForm1.OptIncome = True, UserForm1.TxtAmount.Value, "")
        .Cells(iRow, 4) = IIf(UserForm1.OptExpense = True, UserForm1.TxtAmount.Value, "")
        .Cells(iRow, 5) = UserForm1.CmbCategory.Value
        .Cells(iRow, 6) = UserForm1.CmbSubCategory.Value
        .Cells(iRow, 8) = IIf(UserForm1.OptNatwest = True, "Yes", "")
        .Cells(iRow, 9) = IIf(UserForm1.OptSavings = True, "Yes", "")
        .Cells(iRow, 10) = IIf(UserForm1.OptMonzo = True, "Yes", "")
        .Cells(iRow, 7) = [Text(Now(), "DD-MM-YYYY")]
    End With

I have checked on youtube and other sites, however can not find an answer and have tried to figure it out myself with no luck


问:
How I can pass hardcoded location arrays to Mappls Direction Widget React Native?
I need way-points like Pune-Bengaluru-Kerala  is there any prop to pass locations arr.
currently I have,

destination : {longitude:77.56,latitude:28.67,name:"MapmyIndia",address:"Okhla,New Delhi"},
source : {longitude:73.7228769,latitude:18.5248904,name:"Pune",address:"Pune,Maharashtra"},

currently my code look like this

```<code>const data = await MapplsDirectionWidget.openDirectionWidget({
        // destination : {longitude:77.56,latitude:28.67,name:"MapmyIndia",address:"Okhla,New Delhi"},
        // source : {longitude:73.7228769,latitude:18.5248904,name:"Pune",address:"Pune,Maharashtra"},
)}
</code>```

Body:
I need way-points like Pune-Bengaluru-Kerala  is there any prop to pass locations arr.
currently I have,

destination : {longitude:77.56,latitude:28.67,name:"MapmyIndia",address:"Okhla,New Delhi"},
source : {longitude:73.7228769,latitude:18.5248904,name:"Pune",address:"Pune,Maharashtra"},

currently my code look like this

const data = await MapplsDirectionWidget.openDirectionWidget({
        // destination : {longitude:77.56,latitude:28.67,name:"MapmyIndia",address:"Okhla,New Delhi"},
        // source : {longitude:73.7228769,latitude:18.5248904,name:"Pune",address:"Pune,Maharashtra"},
)}


问:
SQL query return Error "Function "has_column_privilege(oid,smallint,text)" not supported
i have built Join query on redshift, but it doesn't work. Do you know why?

```<code>select
table_schema,
table_name,
sizeMB,
tbl_rows
from
(

select
table_schema ,
table_name

from information_schema.columns
where column_name =  'abcdef' -- enter table name here
      and table_schema = 'prev'
      and table_name not like '%crfg%'

group by table_schema, table_name

) as  a(table_schema, table_name)

 join

(
select "table" as tablename, size as sizeMB, tbl_rows
from svv_table_info
where  "schema" = 'prev'
group by "table", size , tbl_rows
)  as  b(tablename, sizeMB,tbl_rows)
on a.table_name = b.tablename
</code>```

and it got Error: "Function "has_column_privilege(oid,smallint,text)" not supported."

Body:
i have built Join query on redshift, but it doesn't work. Do you know why?

select
table_schema,
table_name,
sizeMB,
tbl_rows
from
(

select
table_schema ,
table_name

from information_schema.columns
where column_name =  'abcdef' -- enter table name here
      and table_schema = 'prev'
      and table_name not like '%crfg%'

group by table_schema, table_name

) as  a(table_schema, table_name)

 join

(
select "table" as tablename, size as sizeMB, tbl_rows
from svv_table_info
where  "schema" = 'prev'
group by "table", size , tbl_rows
)  as  b(tablename, sizeMB,tbl_rows)
on a.table_name = b.tablename

and it got Error: "Function "has_column_privilege(oid,smallint,text)" not supported."


问:
Elasticsearch 8.5.3 ECK Services
There are 4 kubernetes Services in the cluster:

```<code>-es-data            ClusterIP   None            <none>        9200/TCP         22h
-es-http            ClusterIP   172.20.88.236   <none>        9200/TCP         22h
-es-internal-http   ClusterIP   172.20.255.73   <none>        9200/TCP         22h
-es-master          ClusterIP   None            <none>        9200/TCP         22h
</code>```

What are the use cases for them? Which one should be used for EFK logging? Which one should I use to add / update the _template?

Title: Elasticsearch 8.5.3 ECK Services

Body:
There are 4 kubernetes Services in the cluster:

-es-data            ClusterIP   None            <none>        9200/TCP         22h
-es-http            ClusterIP   172.20.88.236   <none>        9200/TCP         22h
-es-internal-http   ClusterIP   172.20.255.73   <none>        9200/TCP         22h
-es-master          ClusterIP   None            <none>        9200/TCP         22h

What are the use cases for them? Which one should be used for EFK logging? Which one should I use to add / update the _template?


问:
keyup is not working in mobile browser , Vue.JS

    <input
      type="text"
      placeholder="Search"
      @keyup.enter="startSearching"
      v-model="searchInput"
      class="search-box-input"
      :disabled="!isActive"
    />
```

I am expecting to trigger startSearching() function in mobile browser

Body:
    <input
      type="text"
      placeholder="Search"
      @keyup.enter="startSearching"
      v-model="searchInput"
      class="search-box-input"
      :disabled="!isActive"
    />

I am expecting to trigger startSearching() function in mobile browser


问:
First iteration of WHILE loop runs out of memory despite manual reconstruction of query succeeding
Environment: SQL Server 2019 (v15).

I have a large query that uses too much space when run as a single SELECT statement. When I try to run it, I get the following error:

Could not allocate a new page for database 'TEMPDB' because of insufficient disk space in filegroup 'DEFAULT'.

However, the problem breaks down naturally into a dozen or so pieces, so I wrote a WHILE loop to iterate through each piece and insert into a results table. Unfortunately, the first iteration of the WHILE loop also returns the same memory error. All the WHILE loop is doing is changing a few values in the WHERE clause.

The key thing confusing me here, is that when I manually run one iteration of the INSERT statement, absent all looping logic, it works perfectly.

Manually coding the first iteration to use the first institution_name just works, so I don't think the joins here are going wrong and causing the memory error.

```<code>WITH my_cte AS
(
    SELECT [columns]
    FROM mytable a
    INNER JOIN bigtable b ON a.institution_name = b.institution_name
                          AND a.personID = b.personID
    WHERE a.institution_name = 'ABC'
      AND b.institution_name = 'ABC'
)
INSERT INTO results (personID, institution_name, ...)
SELECT personID, institution_name, [some aggregations]
FROM my_cte
GROUP BY personID, institution_name;
</code>```

The version with the WHILE loop fails. I need to run the query with different values for institution_name.

Here I show three different values but even just the first iteration fails.

```<code>DECLARE @INSTITUTION varchar(10)
DECLARE @COUNTER int
SET @COUNTER = 0
DECLARE @LOOKUP table (temp_val varchar(10), temp_id int)

INSERT INTO @LOOKUP (temp_val, temp_id)
VALUES ('ABC', 1), ('DEF', 2), ('GHI', 3)

WHILE @COUNTER < 3
BEGIN
    SET @COUNTER = @COUNTER + 1

    SELECT @INSTITUTION = temp_val
    FROM @LOOKUP
    WHERE temp_id = @COUNTER;

    WITH my_cte AS
    (
        SELECT [columns]
        FROM mytable a
        INNER JOIN bigtable b ON a.institution_name = b.institution_name
                              AND a.personID = b.personID
        WHERE a.institution_name = @INSTITUTION
          AND b.institution_name = @INSTITUTION
    )
    INSERT INTO results (personID, institution_name, ...)
    SELECT personID, institution_name, [some aggregations]
    FROM my_cte
    GROUP BY personID, institution_name
END
</code>```

As I write this question, I have quite literally just copy-pasted the insert statement a dozen times, changed the relevant WHERE clause, and run it without errors. Could it be some kind of datatype issue where the query can properly subset if a string literal is put in the WHERE column, but the lookup on my temporary table is failing due to the datatype?  I notice that mytable.institution_name is varchar(10) while bigtable.institution_name is nvarchar(10). Setting the temp table to use nvarchar(10) didn't fix it either.

Body:
Environment: SQL Server 2019 (v15).

I have a large query that uses too much space when run as a single SELECT statement. When I try to run it, I get the following error:

Could not allocate a new page for database 'TEMPDB' because of insufficient disk space in filegroup 'DEFAULT'.

However, the problem breaks down naturally into a dozen or so pieces, so I wrote a WHILE loop to iterate through each piece and insert into a results table. Unfortunately, the first iteration of the WHILE loop also returns the same memory error. All the WHILE loop is doing is changing a few values in the WHERE clause.

The key thing confusing me here, is that when I manually run one iteration of the INSERT statement, absent all looping logic, it works perfectly.

Manually coding the first iteration to use the first institution_name just works, so I don't think the joins here are going wrong and causing the memory error.

WITH my_cte AS
(
    SELECT [columns]
    FROM mytable a
    INNER JOIN bigtable b ON a.institution_name = b.institution_name
                          AND a.personID = b.personID
    WHERE a.institution_name = 'ABC'
      AND b.institution_name = 'ABC'
)
INSERT INTO results (personID, institution_name, ...)
SELECT personID, institution_name, [some aggregations]
FROM my_cte
GROUP BY personID, institution_name;

The version with the WHILE loop fails. I need to run the query with different values for institution_name.

Here I show three different values but even just the first iteration fails.

DECLARE @INSTITUTION varchar(10)
DECLARE @COUNTER int
SET @COUNTER = 0
DECLARE @LOOKUP table (temp_val varchar(10), temp_id int)

INSERT INTO @LOOKUP (temp_val, temp_id)
VALUES ('ABC', 1), ('DEF', 2), ('GHI', 3)

WHILE @COUNTER < 3
BEGIN
    SET @COUNTER = @COUNTER + 1

    SELECT @INSTITUTION = temp_val
    FROM @LOOKUP
    WHERE temp_id = @COUNTER;

    WITH my_cte AS
    (
        SELECT [columns]
        FROM mytable a
        INNER JOIN bigtable b ON a.institution_name = b.institution_name
                              AND a.personID = b.personID
        WHERE a.institution_name = @INSTITUTION
          AND b.institution_name = @INSTITUTION
    )
    INSERT INTO results (personID, institution_name, ...)
    SELECT personID, institution_name, [some aggregations]
    FROM my_cte
    GROUP BY personID, institution_name
END

As I write this question, I have quite literally just copy-pasted the insert statement a dozen times, changed the relevant WHERE clause, and run it without errors. Could it be some kind of datatype issue where the query can properly subset if a string literal is put in the WHERE column, but the lookup on my temporary table is failing due to the datatype?  I notice that mytable.institution_name is varchar(10) while bigtable.institution_name is nvarchar(10). Setting the temp table to use nvarchar(10) didn't fix it either.


问:
Session not saving in ios flutter webview app
I have some issue with storing session details in my ios app. I created a webview app. Whenever i close the app after logging in, it logs me out and asks for credentials everytime. This is working fine for my android app. Any fix for this.</p>


问:
Badge is not displaying OSX cocoa swift
I am trying to display badge count in MacOS Ventura for my application, Here is my code

```<code>NSApplication.shared.dockTile.showsApplicationBadge = true
NSApplication.shared.dockTile.badgeLabel = "2"
NSApplication.shared.dockTile.display()
</code>```

I also requested for notification allow

```<code>//create the notificationCenter
    let center = UNUserNotificationCenter.current()
    center.delegate = self
    // set the type as sound or badge
    center.requestAuthorization(options: [.sound,.alert,.badge]) { (granted, error) in
        if granted {
            print("Notification Enable Successfully")
        }else{
            print(error.debugDescription) // prints "Notifications are not allowed for this application"
        }
    }
</code>```

but it is always going into error part, I don't know what's issue there.
I also checked in Notification settings in System preference, It's showing only alert there. There is no badge setting there.

How to add badge setting in notification setting? Here is the screenshot

Any help would be appreciated.

Title: Badge is not displaying OSX cocoa swift

Body:
I am trying to display badge count in MacOS Ventura for my application, Here is my code

NSApplication.shared.dockTile.showsApplicationBadge = true
NSApplication.shared.dockTile.badgeLabel = "2"
NSApplication.shared.dockTile.display()

I also requested for notification allow

//create the notificationCenter
    let center = UNUserNotificationCenter.current()
    center.delegate = self
    // set the type as sound or badge
    center.requestAuthorization(options: [.sound,.alert,.badge]) { (granted, error) in
        if granted {
            print("Notification Enable Successfully")
        }else{
            print(error.debugDescription) // prints "Notifications are not allowed for this application"
        }
    }

but it is always going into error part, I don't know what's issue there.
I also checked in Notification settings in System preference, It's showing only alert there. There is no badge setting there.

How to add badge setting in notification setting? Here is the screenshot

Any help would be appreciated.


问:
Can I express the size of some function whose 3arguments are equivalent to (x,y,z), by the density of color at each point on 3 dimension?
In the following program, is it possible to express the size of p[r0,gamma,a] at each point in 3 dimensions, where the X coordinate is r0, the Y coordinate is gamma, and the Z coordinate is a, by the intensity of the color?
And if I want to do that, what kind of code and how/where should I implement it?
Or is it impossible to that by R?
http://okadasan.com/S_P.R

I tried to use plot3d
But I notice it's impossible, because not 4 ones but only 3 arguments can be used in this plot3d.

#######################################
library(rgl)

p = array(1:72000, dim=c(20,36,100))
q = c(1:20)

k = 4187         # phase constant [rad/m] = (2pi)/lambda =(23.14)/(1500/1000000)
f = 1000000   # frequency [Hz]
rou = 1.06      # density

for (r0 in 1:20)     # Depth [5 mm]
{
for (gamma in 1:36)
{
for (a in 1:10)  # Radius of Daiphragm  [m]
{
a = a0.0005
Jn_z = 0
for (m in 1:100)
{
z = kasin(gamma10)
P_Jn = (((-1)^m)/(factorial(m)factorial(m+1)))(z/2)^(2m+1)
Jn_z = Jn_z + P_Jn
}
Imp<-complex(real=0,imaginary=2pifrou)
Phase<-complex(real=0,imaginary=2pif-kr0)

```<code>          # Sound Pressure
          p[r0,gamma,a] = Imp*(a^2*5*exp(Phase))/(r0*(Jn_z/(k*a*sin(gamma*10))))
     }
}
</code>```

}

Body:
In the following program, is it possible to express the size of p[r0,gamma,a] at each point in 3 dimensions, where the X coordinate is r0, the Y coordinate is gamma, and the Z coordinate is a, by the intensity of the color?
And if I want to do that, what kind of code and how/where should I implement it?
Or is it impossible to that by R?
http://okadasan.com/S_P.R

I tried to use plot3d
But I notice it's impossible, because not 4 ones but only 3 arguments can be used in this plot3d.

#######################################
library(rgl)

p = array(1:72000, dim=c(20,36,100))
q = c(1:20)

k = 4187         # phase constant [rad/m] = (2pi)/lambda =(23.14)/(1500/1000000)
f = 1000000   # frequency [Hz]
rou = 1.06      # density

for (r0 in 1:20)     # Depth [5 mm]
{
for (gamma in 1:36)
{
for (a in 1:10)  # Radius of Daiphragm  [m]
{
a = a0.0005
Jn_z = 0
for (m in 1:100)
{
z = kasin(gamma10)
P_Jn = (((-1)^m)/(factorial(m)factorial(m+1)))(z/2)^(2m+1)
Jn_z = Jn_z + P_Jn
}
Imp<-complex(real=0,imaginary=2pifrou)
Phase<-complex(real=0,imaginary=2pif-kr0)

          # Sound Pressure
          p[r0,gamma,a] = Imp*(a^2*5*exp(Phase))/(r0*(Jn_z/(k*a*sin(gamma*10))))
     }
}

}


问:
Cloudfront differentiate origin based on hostname of the request
I have a Cloudfront distribution that I want to use it to serve two different hostnames (let's say 1.hostname.com and 2.hostname.com). In my CloudFormation template, I include these as aliases like below.

```<code>AppDistribution:
    Type: AWS::CloudFront::Distribution
    Properties:
        DistributionConfig:
            Origins:
                - DomainName: !Ref ALBDomainName1
                  Id: ALBOrigin1
                  CustomOriginConfig:
                      OriginProtocolPolicy: https-only
                      OriginSSLProtocols:
                          - TLSv1.2
                - DomainName: !Ref ALBDomainName2
                  Id: ALBOrigin2
                  CustomOriginConfig:
                      OriginProtocolPolicy: https-only
                      OriginSSLProtocols:
                          - TLSv1.2
            Aliases:
                - "1.hostname.com"
                - "2.hostname.com"
            DefaultCacheBehavior:
                AllowedMethods:
                    - GET
                    - HEAD
                    - OPTIONS
                    - PUT
                    - PATCH
                    - POST
                    - DELETE
                TargetOriginId: ALBOrigin1
                ForwardedValues:
                    QueryString: False
                    Cookies:
                        Forward: none
                ViewerProtocolPolicy: redirect-to-https
                MinTTL: 0
                DefaultTTL: 60
                MaxTTL: 60
                ResponseHeadersPolicyId: "123123"
</code>```

I want to configure the cloudformation to use one origin if the request is coming to 1.hostname.com and the other origin if the request is coming to 2.hostname.com. The path pattern can be the same in both cases. Is there a way to add CacheBehaviors achieve this?

Body:
I have a Cloudfront distribution that I want to use it to serve two different hostnames (let's say 1.hostname.com and 2.hostname.com). In my CloudFormation template, I include these as aliases like below.

AppDistribution:
    Type: AWS::CloudFront::Distribution
    Properties:
        DistributionConfig:
            Origins:
                - DomainName: !Ref ALBDomainName1
                  Id: ALBOrigin1
                  CustomOriginConfig:
                      OriginProtocolPolicy: https-only
                      OriginSSLProtocols:
                          - TLSv1.2
                - DomainName: !Ref ALBDomainName2
                  Id: ALBOrigin2
                  CustomOriginConfig:
                      OriginProtocolPolicy: https-only
                      OriginSSLProtocols:
                          - TLSv1.2
            Aliases:
                - "1.hostname.com"
                - "2.hostname.com"
            DefaultCacheBehavior:
                AllowedMethods:
                    - GET
                    - HEAD
                    - OPTIONS
                    - PUT
                    - PATCH
                    - POST
                    - DELETE
                TargetOriginId: ALBOrigin1
                ForwardedValues:
                    QueryString: False
                    Cookies:
                        Forward: none
                ViewerProtocolPolicy: redirect-to-https
                MinTTL: 0
                DefaultTTL: 60
                MaxTTL: 60
                ResponseHeadersPolicyId: "123123"

I want to configure the cloudformation to use one origin if the request is coming to 1.hostname.com and the other origin if the request is coming to 2.hostname.com. The path pattern can be the same in both cases. Is there a way to add CacheBehaviors achieve this?


问:
How to change behavior of JS auto complete in Vs Code
I'd like to keep the intellisense and auto complete for Javascript but as it is, it has an annoying behavior where it will autocomplete the text it thinks I'm trying to input without me pressing tab or enter.

For instance if I want to make a function called "matrix()", I'll type out "matrix" and then when I enter the opening parenthesis "(" it autocomplete the function name to "SVGFEColorMatrixElement()" which is not what I wanted. I looked and it doesn't seem I have any 3rd party JS plugins installed.

My question is how do I tell Vs Code to only auto complete the text if I hit tab or enter?


问:
Solution not working for safeareaview in react native for android while using, paddingTop: Platform.OS === 'android' ? StatusBar.currentHeight : 0
I use the alternative style in <SafeAreaView>. but this method not working for me? The code of my application is given below.

```<code>import { StatusBar } from 'expo-status-bar';
import { Platform, SafeAreaView, StyleSheet, Text} from 'react-native';

export default function App() {

  return (
    <SafeAreaView style={styles.AndroidSafeArea} >
      <Text>this is my app</Text>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  AndroidSafeArea: {
    flex: 1,
    backgroundColor: 'white',
    paddingTop: Platform.OS === 'android' ? StatusBar.currentHeight : 0
    *// working only when I use paddingTop: 25, (directly num)*

  }
});

</code>```

I try to add a paddingTop according to the Platform that user use, unfortunetly condition is not working. But if I give paddingTop directly like paddingTop: 25, it work normally

Body:
I use the alternative style in <SafeAreaView>. but this method not working for me? The code of my application is given below.

import { StatusBar } from 'expo-status-bar';
import { Platform, SafeAreaView, StyleSheet, Text} from 'react-native';

export default function App() {

  return (
    <SafeAreaView style={styles.AndroidSafeArea} >
      <Text>this is my app</Text>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  AndroidSafeArea: {
    flex: 1,
    backgroundColor: 'white',
    paddingTop: Platform.OS === 'android' ? StatusBar.currentHeight : 0
    *// working only when I use paddingTop: 25, (directly num)*

  }
});

I try to add a paddingTop according to the Platform that user use, unfortunetly condition is not working. But if I give paddingTop directly like paddingTop: 25, it work normally


问:
Change Google's map SDK current location button possition
I've added a position button to my app with this snipped

self.mapView?.settings.myLocationButton = true

```

The button appeared in right bottom corner of my app. But because it contains some another content I would like to move the button little bit higher to be able to touch it.
Is there some kind of settings to do this in Swift please?

Body:
I've added a position button to my app with this snipped

self.mapView?.settings.myLocationButton = true

The button appeared in right bottom corner of my app. But because it contains some another content I would like to move the button little bit higher to be able to touch it.
Is there some kind of settings to do this in Swift please?


问:
Is it possible to block push notifaction from OS level in browser using JS?
Im working on a fullscreen mode featured Next js application. I need to restrict any push notications while user in full screen mode. because i need to take a count that is how many time users switching tab from currenty working tab in browser or any other app. these kind of notifications affects that count. example: battery low , telegram notification.
So Can we restrict those using Javascript or any js pakages are available for that same.

need to restrict os level notification in browser fullscreen mode


问:
Does Skaffold risk overloading a registry when used with a remote cluster?
While most layers of a given image would probably be reused during development and only pushed once, it seems that pushing new images/layers to a registry on each code change would fill up a registry rather quickly - especially with a team of developers.

Is this the case with Skaffold or does it have a way to manage that?


问:
No signature of method: build_cty56gqldtdqwan75oxbx5n0x.android() is applicable for argument types:... i am getting this error when i tried to sync
/error=No signature of method: build_cty56gqldtdqwan75oxbx5n0x.android() is applicable for argument types: (build_cty56gqldtdqwan75oxbx5n0x$_run_closure1) values: [build_cty56gqldtdqwan75oxbx5n0x$_run_closure1@45b216ed]/

/* Build file 'C:\Users\jaman\AndroidStudioProjects\GAPSAP\app\build.gradle' line: 6

A problem occurred evaluating project ':app'.

No signature of method: build_cty56gqldtdqwan75oxbx5n0x.android() is applicable for argument types: (build_cty56gqldtdqwan75oxbx5n0x$_run_closure1) values: [build_cty56gqldtdqwan75oxbx5n0x$_run_closure1@45b216ed]

Try:

Run with --info or --debug option to get more log output.
Run with --scan to get full insights.*/

```<code>plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services'
}

android {
    namespace 'com.example.gapsap'
    compileSdk 33

    defaultConfig {
        applicationId "com.example.gapsap"
        minSdk 28
        targetSdk 33
        versionCode 2
       versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    buildToolsVersion '29.0.2'
}

dependencies {

    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'androidx.appcompat:appcompat:1.5.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'

    implementation 'com.google.firebase:firebase-analytics'
    implementation 'com.firebaseui:firebase-ui-database:8.0.2'
    implementation 'com.google.firebase:firebase-auth:21.1.0'
    implementation 'com.google.firebase:firebase-database:20.1.0'
    implementation 'com.google.android.material:material:1.8.0-beta01'

}
</code>```
```<code>buildscript {

    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:4.1.3'
        classpath 'com.google.gms:google-services:4.3.14'
        classpath 'com.google.firebase:firebase-crashlytics-gradle:2.9.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()

        maven { url 'https://jitpack.io' }
        mavenCentral()
    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

Body:
/error=No signature of method: build_cty56gqldtdqwan75oxbx5n0x.android() is applicable for argument types: (build_cty56gqldtdqwan75oxbx5n0x$_run_closure1) values: [build_cty56gqldtdqwan75oxbx5n0x$_run_closure1@45b216ed]/

/* Build file 'C:\Users\jaman\AndroidStudioProjects\GAPSAP\app\build.gradle' line: 6

A problem occurred evaluating project ':app'.

No signature of method: build_cty56gqldtdqwan75oxbx5n0x.android() is applicable for argument types: (build_cty56gqldtdqwan75oxbx5n0x$_run_closure1) values: [build_cty56gqldtdqwan75oxbx5n0x$_run_closure1@45b216ed]

Try:

Run with --info or --debug option to get more log output.
Run with --scan to get full insights.*/

plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services'
}

android {
    namespace 'com.example.gapsap'
    compileSdk 33

    defaultConfig {
        applicationId "com.example.gapsap"
        minSdk 28
        targetSdk 33
        versionCode 2
       versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    buildToolsVersion '29.0.2'
}

dependencies {

    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'androidx.appcompat:appcompat:1.5.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'

    implementation 'com.google.firebase:firebase-analytics'
    implementation 'com.firebaseui:firebase-ui-database:8.0.2'
    implementation 'com.google.firebase:firebase-auth:21.1.0'
    implementation 'com.google.firebase:firebase-database:20.1.0'
    implementation 'com.google.android.material:material:1.8.0-beta01'

}

buildscript {

    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:4.1.3'
        classpath 'com.google.gms:google-services:4.3.14'
        classpath 'com.google.firebase:firebase-crashlytics-gradle:2.9.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()

        maven { url 'https://jitpack.io' }
        mavenCentral()
    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}


问:
Angular14 new project doesn't want to start - app.component.css issue
Environment :

Windows 10

Node - v16.18.1

npm - 8.19.2

AngularJS - 14.2.10

I did create new project using

```<code>ng new client
</code>```

after I opened location with new project and tried to start it.

```<code>cd client
ng serve
</code>```

Unfortunately, the application showed an error:

Error: Module not found: Error: Can't resolve 'O:/Sources/C#/testAngular/client/src/app/app.component.css?ngResource' in 'O:\Sources\C#\testAngular\client'

Error: Module not found: Error: Can't resolve 'O:\Sources\C#\testAngular\client\node_modules\webpack-dev-server\client\index.js?protocol=auto%3A&username=&password=&hostname=0.0.0.0&port=0&pathname=%2Fng-cli-ws&logging=info&overlay=%7B%22errors%22%3Atrue%2C%22warnings%22%3Afalse%7D&reconnect=10&hot=false&live-reload=true' in 'O:\Sources\C#\testAngular\client'

Error: The loader "O:/Sources/C#/testAngular/client/src/app/app.component.css" didn't return a string.

Everything was working last month and suddenly it stop building any angular projects. I can't understand what am I missing to make it working.

UPD: Solved.
I had an issue with file path. Angular/cli doesn't like symbols in the file path. I have moved the project into a folder without any symbols and it did work.

Body:
Environment :

Windows 10

Node - v16.18.1

npm - 8.19.2

AngularJS - 14.2.10

I did create new project using

ng new client

after I opened location with new project and tried to start it.

cd client
ng serve

Unfortunately, the application showed an error:

Error: Module not found: Error: Can't resolve 'O:/Sources/C#/testAngular/client/src/app/app.component.css?ngResource' in 'O:\Sources\C#\testAngular\client'

Error: Module not found: Error: Can't resolve 'O:\Sources\C#\testAngular\client\node_modules\webpack-dev-server\client\index.js?protocol=auto%3A&username=&password=&hostname=0.0.0.0&port=0&pathname=%2Fng-cli-ws&logging=info&overlay=%7B%22errors%22%3Atrue%2C%22warnings%22%3Afalse%7D&reconnect=10&hot=false&live-reload=true' in 'O:\Sources\C#\testAngular\client'

Error: The loader "O:/Sources/C#/testAngular/client/src/app/app.component.css" didn't return a string.

Everything was working last month and suddenly it stop building any angular projects. I can't understand what am I missing to make it working.

UPD: Solved.
I had an issue with file path. Angular/cli doesn't like symbols in the file path. I have moved the project into a folder without any symbols and it did work.


问:
Using Python Repositories in Swift for iOS app
I need to import a repository on GitHub called populartimes located here https://github.com/m-wrzr/populartimes into swift for an iOS app for iPhone. I tried importing pythonkit to run scripts, but actually importing the repository onto my project leads to errors:

I'm not sure if I should copy the repository or pip install it and to make sure the python file knows what the import is.

Attempting to import the module after installing the dependancy package to project:

I'm not sure if it installed correctly. If anyone knows how to install it properly, if there is even a way that'll be appreciated.


问:
Amazon Redshift - Intermittent session timeout error
I am currently investigating an issue regarding an intermittent session timeout error when querying Amazon Redshift.

This error tends to happen on the first connection of the "day", I am not sure the exact window. However, afterwards this error doesn't appear again for the rest of the "day".

Audit logs from Amazon Redshift do not seem to contain in reference to the error, we can see the connection been initialized and then nothing.

We suspect it might have something to do with pooling, however, we have been unable to reliably replicate this error in our other environments, so it has been hard to investigate.

Exception as follows:

Npgsql.PostgresException: 57P01: terminating connection due to session timeout
  ?, in async IBackendMessage NpgsqlConnector.ReadMessage(DataRowLoadingMode dataRowLoadingMode)+ReadMessageLong(?)
  ?, in async Task<bool> NpgsqlDataReader.NextResult(bool async, bool isConsuming, CancellationToken cancellationToken)
  ?, in bool NpgsqlDataReader.NextResult()
  ?, in async ValueTask<NpgsqlDataReader> NpgsqlCommand.ExecuteReader(CommandBehavior behavior, bool async, CancellationToken cancellationToken) x 2
  ?, in NpgsqlDataReader NpgsqlCommand.ExecuteReader(CommandBehavior behavior)
....
```

I was wandering if anybody has encountered similar scenarios, or may have an idea of where to investigate.

Body:
I am currently investigating an issue regarding an intermittent session timeout error when querying Amazon Redshift.

This error tends to happen on the first connection of the "day", I am not sure the exact window. However, afterwards this error doesn't appear again for the rest of the "day".

Audit logs from Amazon Redshift do not seem to contain in reference to the error, we can see the connection been initialized and then nothing.

We suspect it might have something to do with pooling, however, we have been unable to reliably replicate this error in our other environments, so it has been hard to investigate.

Exception as follows:

Npgsql.PostgresException: 57P01: terminating connection due to session timeout
  ?, in async IBackendMessage NpgsqlConnector.ReadMessage(DataRowLoadingMode dataRowLoadingMode)+ReadMessageLong(?)
  ?, in async Task<bool> NpgsqlDataReader.NextResult(bool async, bool isConsuming, CancellationToken cancellationToken)
  ?, in bool NpgsqlDataReader.NextResult()
  ?, in async ValueTask<NpgsqlDataReader> NpgsqlCommand.ExecuteReader(CommandBehavior behavior, bool async, CancellationToken cancellationToken) x 2
  ?, in NpgsqlDataReader NpgsqlCommand.ExecuteReader(CommandBehavior behavior)
....

I was wandering if anybody has encountered similar scenarios, or may have an idea of where to investigate.


问:
Spring Kafka: Consumption is paused indefinitely with out of order commit enabled (setAsyncAcks:true)
Similar to - Reactor Kafka: Consumption is stopped with out of order commit enabled (maxDeferredCommits>0)
it's happening in spring kafka as well, Consumption paused indefinitely with out of order commit enabled

Is there any way we can add timeout for paused consumer or any other solution?

Enabled out of order commit :
factory.getContainerProperties().setAsyncAcks(true);


问:
How to make Inside curve in container in Dart Flutter
I making this this application in which I have to make a bottom navigation bar like this which is curved inside of the container so is there any perticular solution for this it will be appreciated. Thanksenter image description here

I making this this application in which I have to make a bottom navigation bar like this which is curved inside of the container so is there any perticular solution for this it will be appreciated. Thanks


问:
Proper way to indirectly reference a function in Powershell
I've found that I can use Get-Content function:NAME to get ScriptBlock, and use that as function reference.

```<code>function plusOne {
  param([int] $p)
  $p + 1
}

plusOne 100    #--> 101

$intOp = (Get-Content function:plusOne)

&$intOp 100    # --> 101
</code>```

I just wonder if this is the proper way to do this ? Is there any other option ?

Body:
I've found that I can use Get-Content function:NAME to get ScriptBlock, and use that as function reference.

function plusOne {
  param([int] $p)
  $p + 1
}

plusOne 100    #--> 101

$intOp = (Get-Content function:plusOne)

&$intOp 100    # --> 101

I just wonder if this is the proper way to do this ? Is there any other option ?


问:
SQLZOO - Lots of trailing 0s when using CONCAT with ROUND
Doing a problem in SQLZOO: (https://i.stack.imgur.com/dkxnr.png)

Everything makes sense up to the point when I use CONCAT to add the '%' at the end of the rounded number. Suddenly the query returns with lots of meaningless trailing 0s after the decimal.

My code:

```<code>SELECT name,
CONCAT(ROUND(100*population/(SELECT population
                          FROM world
                         WHERE name = 'Germany'),0),'%') AS percentage
FROM world
WHERE continent = 'Europe'
</code>```

The result:(https://i.stack.imgur.com/TGUXP.png)
The result without the CONCAT function:(https://i.stack.imgur.com/aeNAP.png)

Body:
Doing a problem in SQLZOO: (https://i.stack.imgur.com/dkxnr.png)

Everything makes sense up to the point when I use CONCAT to add the '%' at the end of the rounded number. Suddenly the query returns with lots of meaningless trailing 0s after the decimal.

My code:

SELECT name,
CONCAT(ROUND(100*population/(SELECT population
                          FROM world
                         WHERE name = 'Germany'),0),'%') AS percentage
FROM world
WHERE continent = 'Europe'

The result:(https://i.stack.imgur.com/TGUXP.png)
The result without the CONCAT function:(https://i.stack.imgur.com/aeNAP.png)


问:
MongoDB Convert String to Binary
Mongo DB Shell, Need help with script to convert a string to Binary

I can change the datatype of string to Binary in MongoDB Compass.

Need help with the script for running it in the Mongo DB Shell

I tried to create the scripts but they kept failing

db.xx.updateMany({fileType: 'PDF'},[{"$set": {"contentBytes": {5: "$contentBytes"}}}]);

Title: MongoDB Convert String to Binary


问:
How to restart git bash in Windows
I update the PATH variable in Windows but it doesn't affect git bash. the PATH update only after restarting the computer. I want to restart the git bash without restarting the whole computer.</p>

Title: How to restart git bash in Windows


问:
app crash while getting following of Instragram more than 500
please suggest me a solution

```<code>let username = 'cristiano'
let followers = [], followings = []
try {
  let res = await fetch(`https://www.instagram.com/${username}/?__a=1&__d=dis`)
console.log('Invalid username',res)
  res = await res.json()
  let userId = res.graphql.user.id

  let after = null, has_next = true
  while (has_next) {
    await fetch(`https://www.instagram.com/graphql/query/?query_hash=c76146de99bb02f6415203be841dd25a&variables=` + encodeURIComponent(JSON.stringify({
      id: userId,
      include_reel: true,
      fetch_mutual: true,
      first: 50,
      after: after
    }))).then(res => res.json()).then(res => {
      has_next = res.data.user.edge_followed_by.page_info.has_next_page
      after = res.data.user.edge_followed_by.page_info.end_cursor
      followers = followers.concat(res.data.user.edge_followed_by.edges.map(({node}) => {
        return {
          username: node.username,
          full_name: node.full_name
        }
      }))
    })
  }
  console.log('Followers', followers)

  has_next = true
  after = null
  while (has_next) {
    await fetch(`https://www.instagram.com/graphql/query/?query_hash=d04b0a864b4b54837c0d870b0e77e076&variables=` + encodeURIComponent(JSON.stringify({
      id: userId,
      include_reel: true,
      fetch_mutual: true,
      first: 50,
      after: after
    }))).then(res => res.json()).then(res => {
      has_next = res.data.user.edge_follow.page_info.has_next_page
      after = res.data.user.edge_follow.page_info.end_cursor
      followings = followings.concat(res.data.user.edge_follow.edges.map(({node}) => {
        return {
          username: node.username,
          full_name: node.full_name
        }
      }))
    })
  }
  console.log('Followings', followings)
} catch (err) {
  console.log('Invalid username')
}
</code>```

this work fine if follower & following is less than 500 , but app crash more than 500

GET https://www.instagram.com/graphql/query/?query_hash=c76146de99bb02f6415203be841dd25a&variables=%7B%22id%22%3A%22173560420%22%2C%22include_reel%22%3Atrue%2C%22fetch_mutual%22%3Atrue%2C%22first%22%3A50%2C%22after%22%3A%22QVFDVUZvVEVacU5lY183TXBMQ0NEbmo0Z2RLOUVJNWU3amowSU1NU05reWtobjdGQndTMGZ2OFhndXh3eTd0YzBDSzZPOTNDUXA2Y1l4T2pCWFB6Yktneg%3D%3D%22%7D 429

I want to get all followers of cristiano but can`t

Body:
please suggest me a solution

let username = 'cristiano'
let followers = [], followings = []
try {
  let res = await fetch(`https://www.instagram.com/${username}/?__a=1&__d=dis`)
console.log('Invalid username',res)
  res = await res.json()
  let userId = res.graphql.user.id

  let after = null, has_next = true
  while (has_next) {
    await fetch(`https://www.instagram.com/graphql/query/?query_hash=c76146de99bb02f6415203be841dd25a&variables=` + encodeURIComponent(JSON.stringify({
      id: userId,
      include_reel: true,
      fetch_mutual: true,
      first: 50,
      after: after
    }))).then(res => res.json()).then(res => {
      has_next = res.data.user.edge_followed_by.page_info.has_next_page
      after = res.data.user.edge_followed_by.page_info.end_cursor
      followers = followers.concat(res.data.user.edge_followed_by.edges.map(({node}) => {
        return {
          username: node.username,
          full_name: node.full_name
        }
      }))
    })
  }
  console.log('Followers', followers)

  has_next = true
  after = null
  while (has_next) {
    await fetch(`https://www.instagram.com/graphql/query/?query_hash=d04b0a864b4b54837c0d870b0e77e076&variables=` + encodeURIComponent(JSON.stringify({
      id: userId,
      include_reel: true,
      fetch_mutual: true,
      first: 50,
      after: after
    }))).then(res => res.json()).then(res => {
      has_next = res.data.user.edge_follow.page_info.has_next_page
      after = res.data.user.edge_follow.page_info.end_cursor
      followings = followings.concat(res.data.user.edge_follow.edges.map(({node}) => {
        return {
          username: node.username,
          full_name: node.full_name
        }
      }))
    })
  }
  console.log('Followings', followings)
} catch (err) {
  console.log('Invalid username')
}

this work fine if follower & following is less than 500 , but app crash more than 500

GET https://www.instagram.com/graphql/query/?query_hash=c76146de99bb02f6415203be841dd25a&variables=%7B%22id%22%3A%22173560420%22%2C%22include_reel%22%3Atrue%2C%22fetch_mutual%22%3Atrue%2C%22first%22%3A50%2C%22after%22%3A%22QVFDVUZvVEVacU5lY183TXBMQ0NEbmo0Z2RLOUVJNWU3amowSU1NU05reWtobjdGQndTMGZ2OFhndXh3eTd0YzBDSzZPOTNDUXA2Y1l4T2pCWFB6Yktneg%3D%3D%22%7D 429

I want to get all followers of cristiano but can`t


问:
Android Deeplink Website Association Keystore Password Issue
I am trying to add my website to my app for deeplink, but when I try to generate digital asset links file using my release keystore file, getting the following error.

I know that this keystore file has a password, but there is no option to enter the password in this page. Where can I enter the password?


问:
Is there anyway to cut a slice of code from code object for execute in python?
This is a continuation of the problem i asked before Is there any special method on python class definition or metaclass about "After class is defined"

To deal with circular reference, I implement a lazy import keeping type hints with above code:

```<code>import dataclasses
import inspect

lazy_chunks_key = '__lazy_chunks__'

@dataclasses.dataclass
class LazyChunk:
    _code: str
    _global: dict
    _local: dict

    def _load(self):
        if self._code:
            exec(self._code, self._global, self._local)
            self._code = ''

    def __getattr__(self, item):
        self._load()
        if item in self._local:
            return self._local[item]
        if item in self._global:
            return self._global[item]
        raise NameError(item)

    def __bool__(self):
        return False

def lazy_chunk():
    import re
    stack = inspect.stack()[1]
    with open(stack.filename, encoding='utf-8') as _src:
        src = iter(_src)
        for _ in range(stack.lineno): next(src)
        spacing, code = re.match(r"( *)([^ ].*)?", next(src)).groups()
        chunk_ind = len(spacing)
        code += '\n'
        while (line := next(src, None)) is not None:
            spacing, line_code = re.match(r"( *)([^ ].*)?", line).groups()
            if not line_code: continue
            if (_ind := len(spacing)) < chunk_ind: break
            code += ' ' * (_ind - chunk_ind) + line_code + '\n'
    frame = stack.frame
    frame.f_locals.setdefault(lazy_chunks_key, []).append(res := LazyChunk(code.strip(), frame.f_globals, frame.f_locals))
    return res

</code>```

and in the structure factory, using the lazy chunk to get above type

```<code>def set_fields_from_annotations(cls: typing.Type[_CStruct]) -> typing.Type[_CStruct]:
    if not (annotations := getattr(cls, '__annotations__', None)): return cls
    global_namespace = getattr(sys.modules.get(cls.__module__, None), '__dict__', {})
    global_namespace[cls.__name__] = cls
    local_namespace = dict(vars(cls))

    def str_eval_with_lazy(v):
        if isinstance(v, str):
            for chunk in global_namespace.pop(lazy_chunks_key, ()):
                chunk._load()
            return eval(v, global_namespace, local_namespace)
        return v

    ... # passing `str_eval_with_lazy` to fields and call it to get actual type when it is needed
</code>```

but when expanding my uses, cut codes from source file is not feasible. for example zipimport or import from pre compiled codes. to deal with this problem, is there any method to get module code object,get slice and run the slice in eval?

edit: an example usage of lazy_chunk

```<code># tree.py
from .node import Node

@set_fields_from_annotations
class Node(ctypes.Structure):
    first_node: Node

# node.py
if lazy_chunk():
    from .tree import Tree

@set_fields_from_annotations
class Node(ctypes.Structure):
    tree: 'Tree'
    value: ctypes.c_uint
    key: ctypes.c_uint
    parent: 'ctypes.POINTER(Node)'
    child: 'ctypes.POINTER(Node)'
</code>```

Body:
This is a continuation of the problem i asked before Is there any special method on python class definition or metaclass about "After class is defined"

To deal with circular reference, I implement a lazy import keeping type hints with above code:

import dataclasses
import inspect

lazy_chunks_key = '__lazy_chunks__'

@dataclasses.dataclass
class LazyChunk:
    _code: str
    _global: dict
    _local: dict

    def _load(self):
        if self._code:
            exec(self._code, self._global, self._local)
            self._code = ''

    def __getattr__(self, item):
        self._load()
        if item in self._local:
            return self._local[item]
        if item in self._global:
            return self._global[item]
        raise NameError(item)

    def __bool__(self):
        return False

def lazy_chunk():
    import re
    stack = inspect.stack()[1]
    with open(stack.filename, encoding='utf-8') as _src:
        src = iter(_src)
        for _ in range(stack.lineno): next(src)
        spacing, code = re.match(r"( *)([^ ].*)?", next(src)).groups()
        chunk_ind = len(spacing)
        code += '\n'
        while (line := next(src, None)) is not None:
            spacing, line_code = re.match(r"( *)([^ ].*)?", line).groups()
            if not line_code: continue
            if (_ind := len(spacing)) < chunk_ind: break
            code += ' ' * (_ind - chunk_ind) + line_code + '\n'
    frame = stack.frame
    frame.f_locals.setdefault(lazy_chunks_key, []).append(res := LazyChunk(code.strip(), frame.f_globals, frame.f_locals))
    return res

and in the structure factory, using the lazy chunk to get above type

def set_fields_from_annotations(cls: typing.Type[_CStruct]) -> typing.Type[_CStruct]:
    if not (annotations := getattr(cls, '__annotations__', None)): return cls
    global_namespace = getattr(sys.modules.get(cls.__module__, None), '__dict__', {})
    global_namespace[cls.__name__] = cls
    local_namespace = dict(vars(cls))

    def str_eval_with_lazy(v):
        if isinstance(v, str):
            for chunk in global_namespace.pop(lazy_chunks_key, ()):
                chunk._load()
            return eval(v, global_namespace, local_namespace)
        return v

    ... # passing `str_eval_with_lazy` to fields and call it to get actual type when it is needed

but when expanding my uses, cut codes from source file is not feasible. for example zipimport or import from pre compiled codes. to deal with this problem, is there any method to get module code object,get slice and run the slice in eval?

edit: an example usage of lazy_chunk

# tree.py
from .node import Node

@set_fields_from_annotations
class Node(ctypes.Structure):
    first_node: Node

# node.py
if lazy_chunk():
    from .tree import Tree

@set_fields_from_annotations
class Node(ctypes.Structure):
    tree: 'Tree'
    value: ctypes.c_uint
    key: ctypes.c_uint
    parent: 'ctypes.POINTER(Node)'
    child: 'ctypes.POINTER(Node)'


问:
Retrieve and display data from mysql on ReactJS frontend
I am using NodeJS, MySQL Server, and ReactJS.

I have a local mysql server running that I am retrieving data in a file named database.js

database.js

```<code>const mysql = require('mysql2');

const db = mysql.createConnection({
  host: '127.0.0.1',
  user: 'root',
  password: 'password',
  database: 'budget',
});

db.query('select * from transactions', (error, results, fields) => {
  if (error) {
    console.log(error);
  } else {
    console.log(results);
  }
});
</code>```

I would like to display the results in my ReactJS component via the transactions.jsx file.

transactions.jsx

```<code>import React from "react";
import {DataGrid, GridColDef, GridRowsProp} from "@mui/x-data-grid";
import {Box} from "@mui/material";

const Transactions = () => {
  const columns: GridColDef[] = [
    {field: 'col1', headerName: 'Column 1', width: 150},
    {field: 'col2', headerName: 'Column 2', width: 150},
  ];

  const rows: GridRowsProp = [
    {id: 1, col1: 'Hello', col2: 'World'},
    {id: 2, col1: 'DataGridPro', col2: 'is Awesome'},
    {id: 3, col1: 'MUI', col2: 'is Amazing'},
  ];

  return (
    <Box sx={{
      height: `calc(100vh - 128px)`,
    }}>
      <DataGrid columns={columns} rows={rows}/>
    </Box>
  );
}

export default Transactions;
</code>```

Ultimately I would put the data inside <DataGrid> component.

Body:
I am using NodeJS, MySQL Server, and ReactJS.

I have a local mysql server running that I am retrieving data in a file named database.js

database.js

const mysql = require('mysql2');

const db = mysql.createConnection({
  host: '127.0.0.1',
  user: 'root',
  password: 'password',
  database: 'budget',
});

db.query('select * from transactions', (error, results, fields) => {
  if (error) {
    console.log(error);
  } else {
    console.log(results);
  }
});

I would like to display the results in my ReactJS component via the transactions.jsx file.

transactions.jsx

import React from "react";
import {DataGrid, GridColDef, GridRowsProp} from "@mui/x-data-grid";
import {Box} from "@mui/material";

const Transactions = () => {
  const columns: GridColDef[] = [
    {field: 'col1', headerName: 'Column 1', width: 150},
    {field: 'col2', headerName: 'Column 2', width: 150},
  ];

  const rows: GridRowsProp = [
    {id: 1, col1: 'Hello', col2: 'World'},
    {id: 2, col1: 'DataGridPro', col2: 'is Awesome'},
    {id: 3, col1: 'MUI', col2: 'is Amazing'},
  ];

  return (
    <Box sx={{
      height: `calc(100vh - 128px)`,
    }}>
      <DataGrid columns={columns} rows={rows}/>
    </Box>
  );
}

export default Transactions;

Ultimately I would put the data inside <DataGrid> component.


问:
CVXPY constraint formulation
I'm creating a long short market neutral portfolio using following function.

```<code>import cvxpy as cp
def create_gross_exposure_constraint(w):
    return cp.norm1(w)  <= 2
def create_market_neutral_constraint(w):
    return cp.sum(w) == 0
</code>```

I'm trying to add net asset value constraints as explained below:

I want the net exposure < 1 Million USD (this number can be changed). What does this mean is If i do allocation using above weight: abs(Position_of_Asset * Price_of_Asset) < 1 Million USD.

I tried creating it using below. But it is not working.

```<code>def create_value_exposure_constraint(w, idx):
    x = cp.sum(cp.abs(w))
    return w[idx] / x  <= 0.1
</code>```

Title: CVXPY constraint formulation

Body:
I'm creating a long short market neutral portfolio using following function.

import cvxpy as cp
def create_gross_exposure_constraint(w):
    return cp.norm1(w)  <= 2
def create_market_neutral_constraint(w):
    return cp.sum(w) == 0

I'm trying to add net asset value constraints as explained below:

I want the net exposure < 1 Million USD (this number can be changed). What does this mean is If i do allocation using above weight: abs(Position_of_Asset * Price_of_Asset) < 1 Million USD.

I tried creating it using below. But it is not working.

def create_value_exposure_constraint(w, idx):
    x = cp.sum(cp.abs(w))
    return w[idx] / x  <= 0.1


问:
How to write multiple times to the child process from the several part of the parent code(QProcess)?
I'm a beginner in QT, and I'm trying to send/write some data from the parent process(C++) to the child process(python) and the child process need to receive that data.

Parent code:

```<code>    if(PythonProcess.state() == QProcess::Running){
            QString data1 = "starttttttttttttttt123";
            PythonProcess.write(data1.toStdString().c_str());
            PythonProcess.write("\n\r");
            PythonProcess.closeWriteChannel();
            //PythonProcess.start();
            //PythonProcess.waitForBytesWritten();
            data1 = "newwwwwoneeee\n";
            //PythonProcess.write(data1.toStdString().c_str());
            PythonProcess.write("\n");
            //std::cout <<data1.toStdString().c_str()<<endl;
            //PythonProcess.waitForBytesWritten();
            //PythonProcess.closeWriteChannel();
        }
</code>```

Child process:

```<code>    while True:
        for line in sys.stdin:
            print(line)
</code>```

Problems:

When I'm using QProcess::write() to write data, I need to put QProcess::closeWriteChannel() to write the data to stdin. Without this the data isn't written to the child process.
But once I closed the write channel, there's no way back to open it again without restarting the process.
So if I write one time, and close the channel,  the 2nd time it won't work in the same process.
But I must send multiple data time to time to the child process without restarting it.

Question

How can I send the data multiple time to the child process without closing the write channel or without restarting the child process?
An example will be great.

Body:
I'm a beginner in QT, and I'm trying to send/write some data from the parent process(C++) to the child process(python) and the child process need to receive that data.

Parent code:

    if(PythonProcess.state() == QProcess::Running){
            QString data1 = "starttttttttttttttt123";
            PythonProcess.write(data1.toStdString().c_str());
            PythonProcess.write("\n\r");
            PythonProcess.closeWriteChannel();
            //PythonProcess.start();
            //PythonProcess.waitForBytesWritten();
            data1 = "newwwwwoneeee\n";
            //PythonProcess.write(data1.toStdString().c_str());
            PythonProcess.write("\n");
            //std::cout <<data1.toStdString().c_str()<<endl;
            //PythonProcess.waitForBytesWritten();
            //PythonProcess.closeWriteChannel();
        }

Child process:

    while True:
        for line in sys.stdin:
            print(line)

Problems:

When I'm using QProcess::write() to write data, I need to put QProcess::closeWriteChannel() to write the data to stdin. Without this the data isn't written to the child process.
But once I closed the write channel, there's no way back to open it again without restarting the process.
So if I write one time, and close the channel,  the 2nd time it won't work in the same process.
But I must send multiple data time to time to the child process without restarting it.

Question

How can I send the data multiple time to the child process without closing the write channel or without restarting the child process?
An example will be great.


问:
How to run HTML_CodeSniffer inside Java code
I have a Test automation framework built using Java, Selenium and trying to run HTML_CodeSniffer inside java code to get the desired Accessibility violation logs.

https://github.com/squizlabs/HTML_CodeSniffer

I tried to embed this into our Java code and run using using trireme (https://github.com/apigee/trireme) as we dont have Node.JS setup but this isn't providing desired Accessibility violation logs.

How do we get HTML CodeSniffer run inside our Java code ?

Tried to integrate HTML CodeSniffer with Java code using Trireme, it didn't produce desired Accessibility violation logs.


问:
Two Arrays in a single definition in Groovy
I have to pass two different parameters from my Jenkin job, to my groovy function . I am trying to read them in two different arrays as shown below. But somehow, it is not working. its working, if I pass only one parameter to one array.

Parameter 1 = imagelist1

parameter 2 = imagelist2

```<code>def abc = {
  container('xyz') {

    String[] arrspt = imagelist1.split(' ')
    for(int i=0; i < arrspt.length; i++) {
      env.image_name = arrspt[i]
      sh 'echo "${image_name}" >> images_to_scan.txt'
    }

    String[] arrStr = imagelist2.split(' ')
    for(int i=0; i < arrStr.length; i++) {
       env.image_name2 =  arrStr[i]
       sh 'echo "${image_name2}" >> images_to_scan.txt
    }
  }
}
</code>```

when I run the Jenkin Job, I am getting error as below :

[Pipeline] Start of Pipeline

[Pipeline] End of Pipeline

org.jenkinsci.plugins.workflow.cps.CpsCompilationErrorsException:
startup failed:

General error during class generation: Method too large:
Pipeline.___cps___19086323
()Lcom/cloudbees/groovy/cps/impl/CpsFunction;

groovyjarjarasm.asm.MethodTooLargeException: Method too large:
Pipeline.___cps___19086323
()Lcom/cloudbees/groovy/cps/impl/CpsFunction;`

Am I doing something wrong in declaring the 2 different arrays in Groovy?

Any help here is highly appreciated !

Body:
I have to pass two different parameters from my Jenkin job, to my groovy function . I am trying to read them in two different arrays as shown below. But somehow, it is not working. its working, if I pass only one parameter to one array.

Parameter 1 = imagelist1

parameter 2 = imagelist2

def abc = {
  container('xyz') {

    String[] arrspt = imagelist1.split(' ')
    for(int i=0; i < arrspt.length; i++) {
      env.image_name = arrspt[i]
      sh 'echo "${image_name}" >> images_to_scan.txt'
    }

    String[] arrStr = imagelist2.split(' ')
    for(int i=0; i < arrStr.length; i++) {
       env.image_name2 =  arrStr[i]
       sh 'echo "${image_name2}" >> images_to_scan.txt
    }
  }
}

when I run the Jenkin Job, I am getting error as below :

[Pipeline] Start of Pipeline

[Pipeline] End of Pipeline

org.jenkinsci.plugins.workflow.cps.CpsCompilationErrorsException:
startup failed:

General error during class generation: Method too large:
Pipeline.___cps___19086323
()Lcom/cloudbees/groovy/cps/impl/CpsFunction;

groovyjarjarasm.asm.MethodTooLargeException: Method too large:
Pipeline.___cps___19086323
()Lcom/cloudbees/groovy/cps/impl/CpsFunction;`

Am I doing something wrong in declaring the 2 different arrays in Groovy?

Any help here is highly appreciated !