问:
R cmdstanr randomly triggering system error 5
I am writing up a statistical test R, specifically using the brm() function in cmdstanr, and more than half the time it is erroring out as "system error 5".

For reference this is the code for the test:

```<code>model.A <- brm(distance ~ time + (1|sid), data = r01,
             family = lognormal(),
             prior = c(set_prior("normal(0,1)",
                        class = "b")),
             init = "random",
             chains = 5, iter = 5000, warmup = 5000,
                         thin = 1,
             cores = getOption("mc.cores", 4L),
             control = list(adapt_delta = 0.95,
                max_treedepth = 15),
             silent = TRUE, seed = 13,
               backend = "cmdstanr",
               save_pars = save_pars(all = TRUE))
</code>```

The error message is telling me that processx_exec fails due to a System Error 5 (my access is being denied).

```<code>Error in `process_initialize(self, private, command, args,
           stdin, stdout, …`:
! Native call to `processx_exec` failed
Caused by error in `chain_call(c_processx_exec, command,
    c(command, args), pty, pty_options, …`:
! create process
'model_a8c28d1d22bbcc6d3551b6bad81f1aee.exe'
   (system error 5, Access is denied.
) @win/processx.c:1040 (processx_exec)
</code>```

The strange thing is that the sometimes the program runs perfectly and I get recognizably accurate statistic. But the vast majority of time the processx_exec fails. I know system error 5 is related to permissions, however I have tried changing the permissions of all the directories associated with the R and this bit of code, but that is having no noticeable effect. I'm at my wits end trying to figure out what access is being denied where. If anyone can help me sort this out you would be a life saver.

Body:
I am writing up a statistical test R, specifically using the brm() function in cmdstanr, and more than half the time it is erroring out as "system error 5".

For reference this is the code for the test:

model.A <- brm(distance ~ time + (1|sid), data = r01,
             family = lognormal(),
             prior = c(set_prior("normal(0,1)",
                        class = "b")),
             init = "random",
             chains = 5, iter = 5000, warmup = 5000,
                         thin = 1,
             cores = getOption("mc.cores", 4L),
             control = list(adapt_delta = 0.95,
                max_treedepth = 15),
             silent = TRUE, seed = 13,
               backend = "cmdstanr",
               save_pars = save_pars(all = TRUE))

The error message is telling me that processx_exec fails due to a System Error 5 (my access is being denied).

Error in `process_initialize(self, private, command, args,
           stdin, stdout, …`:
! Native call to `processx_exec` failed
Caused by error in `chain_call(c_processx_exec, command,
    c(command, args), pty, pty_options, …`:
! create process
'model_a8c28d1d22bbcc6d3551b6bad81f1aee.exe'
   (system error 5, Access is denied.
) @win/processx.c:1040 (processx_exec)

The strange thing is that the sometimes the program runs perfectly and I get recognizably accurate statistic. But the vast majority of time the processx_exec fails. I know system error 5 is related to permissions, however I have tried changing the permissions of all the directories associated with the R and this bit of code, but that is having no noticeable effect. I'm at my wits end trying to figure out what access is being denied where. If anyone can help me sort this out you would be a life saver.


来源: stackexchange

问:
need help debugging to output if the adjusted list is in order of ascension
The task question is:

You are given an array of non-negative integers numbers. You are allowed to choose any number from this array and swap any two digits in it. If after the swap operation the number contains leading zeros, they can be omitted and not considered (eg: 010 will be considered just 10).

Your task is to check whether it is possible to apply the swap operation at most once, so that the elements of the resulting array are strictly increasing.
For numbers = [1, 5, 10, 20], the output should be solution(numbers) = true.

Here are some examples to show what they mean:

The initial array is already strictly increasing, so no actions are required.
For numbers = [1, 3, 900, 10], the output should be solution(numbers) = true.

By choosing numbers[2] = 900 and swapping its first and third digits, the resulting number 009 is considered to be just 9. So the updated array will look like [1, 3, 9, 10], which is strictly increasing.

For numbers = [13, 31, 30], the output should be solution(numbers) = false.

The initial array elements are not increasing.

By swapping the digits of numbers[0] = 13, the array becomes [31, 31, 30] which is not strictly increasing;

By swapping the digits of numbers[1] = 31, the array becomes [13, 13, 30] which is not strictly increasing;

By swapping the digits of numbers[2] = 30, the array becomes [13, 31, 3] which is not strictly increasing;

So, it's not possible to obtain a strictly increasing array, and the answer is false.

I did this bit of code but there is something wrong with it.
When I do a test run, it is only appending the number that needs the swapping, not all the numbers.

I am just wondering if there's a way to fix the appending error or if there are more things wrong with my code.

```<code>def solution(numbers):
    if numbers == sorted(numbers):
        return True
    else:
        for i in range(0,len(numbers)-1):
            num_new = []
            num = 0
            if numbers[i] % 100 != 0:
                num_new.append(num) #issue around here, it's only appending the 900 as 9 not the rest
            else:
                num = numbers[i] / 100
                num_new.append(num)
        if num_new == sorted(numbers):
            return True
        else:
            return False

solution([1, 3, 900, 10])
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The task question is:

You are given an array of non-negative integers numbers. You are allowed to choose any number from this array and swap any two digits in it. If after the swap operation the number contains leading zeros, they can be omitted and not considered (eg: 010 will be considered just 10).

Your task is to check whether it is possible to apply the swap operation at most once, so that the elements of the resulting array are strictly increasing.
For numbers = [1, 5, 10, 20], the output should be solution(numbers) = true.

Here are some examples to show what they mean:

The initial array is already strictly increasing, so no actions are required.
For numbers = [1, 3, 900, 10], the output should be solution(numbers) = true.

By choosing numbers[2] = 900 and swapping its first and third digits, the resulting number 009 is considered to be just 9. So the updated array will look like [1, 3, 9, 10], which is strictly increasing.

For numbers = [13, 31, 30], the output should be solution(numbers) = false.

The initial array elements are not increasing.

By swapping the digits of numbers[0] = 13, the array becomes [31, 31, 30] which is not strictly increasing;

By swapping the digits of numbers[1] = 31, the array becomes [13, 13, 30] which is not strictly increasing;

By swapping the digits of numbers[2] = 30, the array becomes [13, 31, 3] which is not strictly increasing;

So, it's not possible to obtain a strictly increasing array, and the answer is false.

I did this bit of code but there is something wrong with it.
When I do a test run, it is only appending the number that needs the swapping, not all the numbers.

I am just wondering if there's a way to fix the appending error or if there are more things wrong with my code.

def solution(numbers):
    if numbers == sorted(numbers):
        return True
    else:
        for i in range(0,len(numbers)-1):
            num_new = []
            num = 0
            if numbers[i] % 100 != 0:
                num_new.append(num) #issue around here, it's only appending the 900 as 9 not the rest
            else:
                num = numbers[i] / 100
                num_new.append(num)
        if num_new == sorted(numbers):
            return True
        else:
            return False

solution([1, 3, 900, 10])


问:
Result does not exist in indexedDB
I'm reading the documentation through mdn, but the interface which is in onupgradeneeded, doesn't return the result and with that I can't create the objects in the database.

```<code>const request = window.indexedDB.open("MyTestDatabase", 3);

request.onupgradeneeded = (event) => {
    const db = event.target?.result;
    const objectStore = db.createObjectStore("name", { keyPath: "myKey" });
};
</code>```

ERROR:

```<code>Property 'result' does not exist on type 'EventTarget'.ts(2339)
</code>```

SIGNATURE:

```<code>/** Also inherits methods from its parents IDBRequest and EventTarget. */
interface IDBOpenDBRequest extends IDBRequest<IDBDatabase> {
    onblocked: ((this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any) | null;
    onupgradeneeded: ((this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any) | null;
    addEventListener<K extends keyof IDBOpenDBRequestEventMap>(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
    addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
    removeEventListener<K extends keyof IDBOpenDBRequestEventMap>(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
    removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
}
</code>```

Title: Result does not exist in indexedDB

Body:
I'm reading the documentation through mdn, but the interface which is in onupgradeneeded, doesn't return the result and with that I can't create the objects in the database.

const request = window.indexedDB.open("MyTestDatabase", 3);

request.onupgradeneeded = (event) => {
    const db = event.target?.result;
    const objectStore = db.createObjectStore("name", { keyPath: "myKey" });
};

ERROR:

Property 'result' does not exist on type 'EventTarget'.ts(2339)

SIGNATURE:

/** Also inherits methods from its parents IDBRequest and EventTarget. */
interface IDBOpenDBRequest extends IDBRequest<IDBDatabase> {
    onblocked: ((this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any) | null;
    onupgradeneeded: ((this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any) | null;
    addEventListener<K extends keyof IDBOpenDBRequestEventMap>(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
    addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
    removeEventListener<K extends keyof IDBOpenDBRequestEventMap>(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
    removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
}


问:
Change OBS Filename before replay buffer is saved using obspython
I am writing an OBS python script to add your current active window to the filename formatting before saving with replay buffer. So far, I've gotten it to update the active window name in the filename, but it's updating the filename after I press "save replay buffer"

Here's the working code I have so far:

import win32gui
import obswebsocket
import obspython
from obswebsocket import obsws, events, requests

def on_event(event):
    if event == obspython.OBS_FRONTEND_EVENT_REPLAY_BUFFER_SAVED:
        print("Setting file name to active window title...")
        windowTitle = win32gui.GetWindowText (win32gui.GetForegroundWindow())
        print("Window Title: " + windowTitle)
        client = obswebsocket.obsws("localhost", 4444, "")
        client.connect()
        client.call(obswebsocket.requests.SetFilenameFormatting("%CCYY-%MM-%DD %hh:%mm:%ss - " + windowTitle))
        client.disconnect()
        print("Done!")

def script_load(settings):
    obspython.obs_frontend_add_event_callback(on_event)

print("get-window-title.py Loaded!")
```

I've thought of trying a different approach where I set up a keypress listener to run "save replay buffer" after the title change in the code. I wanted to see if there was a simpler way using the obspython.OBS_FRONTEND_EVENT_REPLAY_BUFFER_SAVED event handler.

Body:
I am writing an OBS python script to add your current active window to the filename formatting before saving with replay buffer. So far, I've gotten it to update the active window name in the filename, but it's updating the filename after I press "save replay buffer"

Here's the working code I have so far:

import win32gui
import obswebsocket
import obspython
from obswebsocket import obsws, events, requests

def on_event(event):
    if event == obspython.OBS_FRONTEND_EVENT_REPLAY_BUFFER_SAVED:
        print("Setting file name to active window title...")
        windowTitle = win32gui.GetWindowText (win32gui.GetForegroundWindow())
        print("Window Title: " + windowTitle)
        client = obswebsocket.obsws("localhost", 4444, "")
        client.connect()
        client.call(obswebsocket.requests.SetFilenameFormatting("%CCYY-%MM-%DD %hh:%mm:%ss - " + windowTitle))
        client.disconnect()
        print("Done!")

def script_load(settings):
    obspython.obs_frontend_add_event_callback(on_event)

print("get-window-title.py Loaded!")

I've thought of trying a different approach where I set up a keypress listener to run "save replay buffer" after the title change in the code. I wanted to see if there was a simpler way using the obspython.OBS_FRONTEND_EVENT_REPLAY_BUFFER_SAVED event handler.


问:
Mocking 3rd party integrations outside of the context of a test
In a lot of the apps I work on, we have this problem where we heavily rely on 1st and 3rd party APIs. So much so, in some of our apps, it is useless to try to login without those APIs being in place. Either critical pieces of data are not there or the entire app is like a server side render SPA where it houses no data on its own but pulls that data from an API at the time of a request (we cache it when we can).

This raises a huge problem when trying to develop the app locally since we do not have a sandbox environment. Our current solution is to create a service layer in between our business logic and the actual HTTP calls. We then, in our local environments, swap out the HTTP implementation for a class that just returns fake data. This works pretty well most of the time except for a couple of issues:

This only really gives us one state of the application at a time. Unlike data in the database, we are not able to easily run different seeders to replicate different scenarios.

If we run into a bug in production, we have no way of replicating the api response without actually diving into the code and adding some conditional to return that specific response. With data that is stored in the database, it is easy to login to TablePlus and manually setup some condition or even pull down select table from production.

In our mocks, our functions can get quite large and nasty if we do try to have it dynamically respond with a different response based on the resource id being request, as an example.

This makes the overhead to create each test for each scenario quite high in my opinion. If we could use something similar to a database factory to generate a bunch of different request-response pairs, we could test a lot more cases and if we could somehow, dynamically, setup certain scenarios when we are trying to replicate bugs we are running into production.

Since our applications are built with Laravel and PHP, unlike the database, mocks don't persist from one request to another. We cannot simple throw open a tinker and start seeding out API integrations with data like we can in the database.

I was trying to think of a way to do it with a cache and set request-response pairs. This could also be move to the database but would prefer not to have that extra table there that is only used locally.

Any ideas?


问:
Super expression must either be null or a function, not undefined
Everything works fine on dev (npm run dev) but after build I have this error:

Super expression must either be null or a function, not undefined.

Without BlotFormatter module it also works fine.

It is laravel + vue + inertia + vite + VueQuill

<template>

        <QuillEditor theme="snow" :modules="modules"/>

</template>

```


问:
Xamarin custom keyboard. How to hide popupCharacters when touch on regular keys
I wrote custom keyboard with diacritics in popupCharacters. When I longpress on letter 'A' to show diacritics I can't dismiss it by touching anywhere on the rest of the keyboard (see image).

Image

I've implemented SetOnTouchListener() for keyboard and popup view and get MotionEvent etc. only for keyboard, but I don't know how can I detect that touch is out of bounds of popupCharacters and hide it. It looks like the whole keyboard is deactivated and ignore touches outside popups.

OnCreate

```<code>
 public override void OnCreate()
        {
            base.OnCreate();
            _currentKeyboardView =     (KeyboardView)LayoutInflater.Inflate(Resource.Layout.keyboard_view, null);
            _popupView = (KeyboardView)LayoutInflater.Inflate(Resource.Layout.popup_view, null);

            App.Init(Application);
        }

</code>```

Here is OnTouch() implementation

```<code>        public bool OnTouch(View v, MotionEvent e)
        {
            Rect popupRect = new Rect();
            _popupView.GetHitRect(popupRect);

            if (!popupRect.Contains((int)e.GetX(), (int)e.GetY()))
            {
                Console.WriteLine("Outside view");
                _popupView.Visibility = ViewStates.Gone;
            }
            else Console.WriteLine("Inside view");

            _currentKeyboardView.OnTouchEvent(e);

            return true;
        }
</code>```

Popup_view:

```<code><?xml version="1.0" encoding="utf-8"?>

<android.inputmethodservice.KeyboardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/keyboardView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:keyBackground="@layout/key_background"
    android:keyPreviewLayout="@null"
    android:keyPreviewOffset="0px"
    android:keyPreviewHeight="20px"
    android:keyTextColor="@android:color/black"
    android:background="@android:color/white"
    android:shadowRadius="0.0"
    android:horizontalGap="5px"
    android:verticalGap="0px" >

</android.inputmethodservice.KeyboardView>
</code>```

Body:
I wrote custom keyboard with diacritics in popupCharacters. When I longpress on letter 'A' to show diacritics I can't dismiss it by touching anywhere on the rest of the keyboard (see image).

Image

I've implemented SetOnTouchListener() for keyboard and popup view and get MotionEvent etc. only for keyboard, but I don't know how can I detect that touch is out of bounds of popupCharacters and hide it. It looks like the whole keyboard is deactivated and ignore touches outside popups.

OnCreate

 public override void OnCreate()
        {
            base.OnCreate();
            _currentKeyboardView =     (KeyboardView)LayoutInflater.Inflate(Resource.Layout.keyboard_view, null);
            _popupView = (KeyboardView)LayoutInflater.Inflate(Resource.Layout.popup_view, null);

            App.Init(Application);
        }

Here is OnTouch() implementation

        public bool OnTouch(View v, MotionEvent e)
        {
            Rect popupRect = new Rect();
            _popupView.GetHitRect(popupRect);

            if (!popupRect.Contains((int)e.GetX(), (int)e.GetY()))
            {
                Console.WriteLine("Outside view");
                _popupView.Visibility = ViewStates.Gone;
            }
            else Console.WriteLine("Inside view");

            _currentKeyboardView.OnTouchEvent(e);

            return true;
        }

Popup_view:

<?xml version="1.0" encoding="utf-8"?>

<android.inputmethodservice.KeyboardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/keyboardView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:keyBackground="@layout/key_background"
    android:keyPreviewLayout="@null"
    android:keyPreviewOffset="0px"
    android:keyPreviewHeight="20px"
    android:keyTextColor="@android:color/black"
    android:background="@android:color/white"
    android:shadowRadius="0.0"
    android:horizontalGap="5px"
    android:verticalGap="0px" >

</android.inputmethodservice.KeyboardView>


问:
How do I pull in a supporting json data file in an electron-react-boilerplate app
I created an app using electron-react-boilerplate. I am pulling in a JSON file to serve as a source of data. When I run the build command -

```<code>npm run package
</code>```

I get it successfully packaged. But the JSON file is not pulled in. How can I pull in supporting files in an electron-react-boilerplate  deployed app?

Body:
I created an app using electron-react-boilerplate. I am pulling in a JSON file to serve as a source of data. When I run the build command -

npm run package

I get it successfully packaged. But the JSON file is not pulled in. How can I pull in supporting files in an electron-react-boilerplate  deployed app?


问:
Product tab heading not showing
trust y'all good. I have an issue with woocommerce product tab heading(title) not showing. I have tried function.php via a child theme and CSS but none seem working. These I have tried

function.php

```<code>add_action( ‘after_setup_theme’, ‘cg_add_desc_tab_title’, 99 );
function cg_add_desc_tab_title() {
remove_filter( ‘woocommerce_product_description_heading’, ‘__return_null’ );
}
</code>```

CSS.

```<code>.panel.woocommerce-Tabs-panel–additional_information h2:first-of-type,
.panel.woocommerce-Tabs-panel–reviews h2:first-of-type {
display: block;
}
</code>```

Any help is appreciated.

```<code>add_action( ‘after_setup_theme’, ‘cg_add_desc_tab_title’, 99 );
function cg_add_desc_tab_title() {
remove_filter( ‘woocommerce_product_description_heading’, ‘__return_null’ );
}

CSS.

.panel.woocommerce-Tabs-panel–additional_information h2:first-of-type,
.panel.woocommerce-Tabs-panel–reviews h2:first-of-type {
display: block;
}
</code>```

Title: Product tab heading not showing

Body:
trust y'all good. I have an issue with woocommerce product tab heading(title) not showing. I have tried function.php via a child theme and CSS but none seem working. These I have tried

function.php

add_action( ‘after_setup_theme’, ‘cg_add_desc_tab_title’, 99 );
function cg_add_desc_tab_title() {
remove_filter( ‘woocommerce_product_description_heading’, ‘__return_null’ );
}

CSS.

.panel.woocommerce-Tabs-panel–additional_information h2:first-of-type,
.panel.woocommerce-Tabs-panel–reviews h2:first-of-type {
display: block;
}

Any help is appreciated.

add_action( ‘after_setup_theme’, ‘cg_add_desc_tab_title’, 99 );
function cg_add_desc_tab_title() {
remove_filter( ‘woocommerce_product_description_heading’, ‘__return_null’ );
}

CSS.

.panel.woocommerce-Tabs-panel–additional_information h2:first-of-type,
.panel.woocommerce-Tabs-panel–reviews h2:first-of-type {
display: block;
}


问:
CloudWatch Logs Insights query, How to return only last request set of data
Having this AWS Cloudwatch Logs Insights query:

fields @timestamp as ``invoke time``, @requestId, id, name, status, nextStatus, nextStatusDelay | filter @message like /nextStatusDelay/ | filter @message not like /handlerObject/ | sort ``invoke time`` desc

That returns data set shown in image.

Is there a way to filter the result to show only data for the latest request?
In this example rows that include requestId "ca04da81-5061-4986-b2f1-681de2bd9995".
I can't pass any hardcoded value like requestId or number of row returned. I would like those arguments to be dynamic.


问:
My active directory accounts are not being created properly
Once I create the users using my script , It will create fine but I cant login using them and I will get errors like

Account Restrictions Are Preventing This User from Signing in.

The issue is I cant sign in with my users

```<code>Import-Module ActiveDirectory
$ADUsers = Import-Csv C:\users.csv
foreach ($User in $ADUsers) {
    $Name = $User.Name
    $username = $User.username
    $password = $User.passcode
    $Title=$User.Title
    New-ADUser -Name $Name -SamAccountName $username -AccountPassword (ConvertTo-secureString $password -AsPlainText -Force) -Title $Title
    Enable-AdAccount -Identity $username
    }
</code>```

Here is my script I would love to know if i am missing a parameter or something.

I have tried enabling the user accounts in my script yet that did not work. I was hoping to use these accounts to login.

Body:
Once I create the users using my script , It will create fine but I cant login using them and I will get errors like

Account Restrictions Are Preventing This User from Signing in.

The issue is I cant sign in with my users

Import-Module ActiveDirectory
$ADUsers = Import-Csv C:\users.csv
foreach ($User in $ADUsers) {
    $Name = $User.Name
    $username = $User.username
    $password = $User.passcode
    $Title=$User.Title
    New-ADUser -Name $Name -SamAccountName $username -AccountPassword (ConvertTo-secureString $password -AsPlainText -Force) -Title $Title
    Enable-AdAccount -Identity $username
    }

Here is my script I would love to know if i am missing a parameter or something.

I have tried enabling the user accounts in my script yet that did not work. I was hoping to use these accounts to login.


问:
Spark History Server not reading rolling event Logs from IBM Object Storage (COS)
Unable to see the rolling event logs when the files are read from COS (IBM storage service) but the local apache-spark setup works fine (with logDirectory set to something like file:///tmp/spark-logs).

the eventLogs without rolling logs are working in local as well as COS file read.


问:
Image map wrongly in android update of React Native app
I experience the same issue as stated here enter link description here

Whenever I update to a new version on android with any image added to the source code and imported via require... I will see the icons and images mapped to the wrong places. On fresh install everything works fine and on iOS there is no problem at all.

With the exception that it happens on any build when updating on android.
The fix that was described over in the other question did not help unfortunately. Neither the one in the link over in github.

So I tried already adding:

```<code>implementation 'com.facebook.fresco:animated-gif:2.5.0'
</code>```

which did not help. (Also maybe obviously because it is animated gif?)
And I tried adding:

```<code>configurations.all {
resolutionStrategy {
    force "com.facebook.fresco:fresco:2.5.0"
}
</code>```

}

Each time I build the whole bundle in that version and try the update. Each time the results will slightly differ and some other image or icon will get replaced in the wrong place.

Actually it seems weird to me as the dependency tree shows 2.5.0 everywhere. So why would there be the need for this?

I am running  "react": "18.1.0", "react-native": "0.70.1",

Body:
I experience the same issue as stated here enter link description here

Whenever I update to a new version on android with any image added to the source code and imported via require... I will see the icons and images mapped to the wrong places. On fresh install everything works fine and on iOS there is no problem at all.

With the exception that it happens on any build when updating on android.
The fix that was described over in the other question did not help unfortunately. Neither the one in the link over in github.

So I tried already adding:

implementation 'com.facebook.fresco:animated-gif:2.5.0'

which did not help. (Also maybe obviously because it is animated gif?)
And I tried adding:

configurations.all {
resolutionStrategy {
    force "com.facebook.fresco:fresco:2.5.0"
}

}

Each time I build the whole bundle in that version and try the update. Each time the results will slightly differ and some other image or icon will get replaced in the wrong place.

Actually it seems weird to me as the dependency tree shows 2.5.0 everywhere. So why would there be the need for this?

I am running  "react": "18.1.0", "react-native": "0.70.1",


问:
How to fetch data from a server inside of `addEventListener` in a Chrome extension application?
I am creating a Chrome extension and try to fetch data from a server inside of addEventListener when a button is clicked. I get an error Uncaught (in promise) TypeError: Failed to fetch at request. I tried to run the request in a separate file with node file.js and it worked. I thought that I eventually need to add a permission inside of manifest.json for fetching data from a server but I cannot find any ressources for that. How can I fetch data from a server in a Chrome extension?

content.js

document.addEventListener("click", (event) => {
  if (event.target.innerText == "Reply") {
    console.log("reply clicked");
    function request(email) {
      let _data = {
          prompt: email,
      }
      fetch('fetch_address', {
          method: "POST",
          body: JSON.stringify(_data),
          headers: {"Content-type": "application/json; charset=UTF-8"}
      })
      .then(response => response.json())
      .then(json => console.log(json['response']));
    }
    request('this is a test message to check the API');
  }
});
```
<p><strong>background.js</strong></p>
<pre class="lang-js prettyprint-override"><code>console.log("background.js loaded");
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  console.log("message received in background.js");
  if (request.type == "click_event") {
    console.log("click event captured in current webpage");
  }
});

</code>```

Body:
I am creating a Chrome extension and try to fetch data from a server inside of addEventListener when a button is clicked. I get an error Uncaught (in promise) TypeError: Failed to fetch at request. I tried to run the request in a separate file with node file.js and it worked. I thought that I eventually need to add a permission inside of manifest.json for fetching data from a server but I cannot find any ressources for that. How can I fetch data from a server in a Chrome extension?

content.js

document.addEventListener("click", (event) => {
  if (event.target.innerText == "Reply") {
    console.log("reply clicked");
    function request(email) {
      let _data = {
          prompt: email,
      }
      fetch('fetch_address', {
          method: "POST",
          body: JSON.stringify(_data),
          headers: {"Content-type": "application/json; charset=UTF-8"}
      })
      .then(response => response.json())
      .then(json => console.log(json['response']));
    }
    request('this is a test message to check the API');
  }
});

background.js

console.log("background.js loaded");
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  console.log("message received in background.js");
  if (request.type == "click_event") {
    console.log("click event captured in current webpage");
  }
});


问:
How can I reference the Window object in a function without passing it as an argument?
I have a main Window object in my script and I want to reference the Window object in a function without having to pass the Window object as a parameter.

How can I reference my Window object ?

Regards,
Mike

I can make it works passing the reference as an argument like in :

```<code>import PySimpleGUI as sg

def func1(msg,window):
    for i in range (10):
        log = msg + str(i)
        update_log(log,window)
    return
def update_log(msg,window):
    print(msg)
    window.Element('_LOGWINDOW_').update(msg + '\n', append=True)

mylog = [sg.Multiline(size=(20, 15), enable_events=True, horizontal_scroll=True, key='_LOGWINDOW_',autoscroll=True, default_text='')]
layout =[ [mylog
        ,sg.Button('Run',key='_RUN_')]]
window = sg.Window('Test',layout)

while True:
    event, values = window.read()
    if event in (sg.WIN_CLOSED, '_CLOSE_'):
        break
    if event == '_RUN_':
        func1('Hello world',window)

window.close()

</code>```

But I don't want to pass the reference as an argument because my function will call another function where I want to reference the Window object.

Body:
I have a main Window object in my script and I want to reference the Window object in a function without having to pass the Window object as a parameter.

How can I reference my Window object ?

Regards,
Mike

I can make it works passing the reference as an argument like in :

import PySimpleGUI as sg

def func1(msg,window):
    for i in range (10):
        log = msg + str(i)
        update_log(log,window)
    return
def update_log(msg,window):
    print(msg)
    window.Element('_LOGWINDOW_').update(msg + '\n', append=True)

mylog = [sg.Multiline(size=(20, 15), enable_events=True, horizontal_scroll=True, key='_LOGWINDOW_',autoscroll=True, default_text='')]
layout =[ [mylog
        ,sg.Button('Run',key='_RUN_')]]
window = sg.Window('Test',layout)

while True:
    event, values = window.read()
    if event in (sg.WIN_CLOSED, '_CLOSE_'):
        break
    if event == '_RUN_':
        func1('Hello world',window)

window.close()

But I don't want to pass the reference as an argument because my function will call another function where I want to reference the Window object.


问:
How do I add binary media types to an existing API Gateway that I've imported into a CDK stack?
I have an AWS CDK stack in which I'm referencing an existing API Gateway like this:

```<code>api = apigateway.RestApi.from_rest_api_attributes(self, "API",
    rest_api_id="api-id", root_resource_id="root-resource-id")
</code>```

After I have the reference, I want to configure the allowed binary media types to be "application/pdf" and "image/*". The problem is that I can't find a method where I can set these. The only place I've found where you can set the binary media types is in the constructor for the RestApi class and I can't use that because the API has already been created.

There is a binary_media_types property on the RestApi class, but that had no effect when I tried setting its value:

```<code>api.binary_media_types = ["application/pdf", "image/*"]
</code>```

Does anyone know another way to change the binary media types in this situation by using the CDK library?

Body:
I have an AWS CDK stack in which I'm referencing an existing API Gateway like this:

api = apigateway.RestApi.from_rest_api_attributes(self, "API",
    rest_api_id="api-id", root_resource_id="root-resource-id")

After I have the reference, I want to configure the allowed binary media types to be "application/pdf" and "image/*". The problem is that I can't find a method where I can set these. The only place I've found where you can set the binary media types is in the constructor for the RestApi class and I can't use that because the API has already been created.

There is a binary_media_types property on the RestApi class, but that had no effect when I tried setting its value:

api.binary_media_types = ["application/pdf", "image/*"]

Does anyone know another way to change the binary media types in this situation by using the CDK library?


问:
IniFile.Create throws an exception EAccessViolation
This code seems to be in every example that I can find on the web ...

```<code>var IniFile: TIniFile;
    IniFileName : String;

IniFileName := ChangeFileExt(Application.ExeName, '.ini') ;
IniFile := IniFile.Create(IniFileName);
</code>```

The IniFile.Create throws an exception EAccessViolation.

IniFileName is a full path, avoiding the trap of trying to write to the Windows directory. I can save a file to to it from a text editor, so there are no permission problems.

Any ideas what I am doing wrongly?

Body:
This code seems to be in every example that I can find on the web ...

var IniFile: TIniFile;
    IniFileName : String;

IniFileName := ChangeFileExt(Application.ExeName, '.ini') ;
IniFile := IniFile.Create(IniFileName);

The IniFile.Create throws an exception EAccessViolation.

IniFileName is a full path, avoiding the trap of trying to write to the Windows directory. I can save a file to to it from a text editor, so there are no permission problems.

Any ideas what I am doing wrongly?


问:
How to select only elements that have pseudoelements
I need to select only those elements that have pseudo-elements ::before & ::after (not necessarily at the same time). Also, I need to apply styles to these pseudo-elements.

I thought this solution would work:

```<code>*:has(::before, ::after) {
  content: '';
  /* Something else ... */
}
</code>```

Body:
I need to select only those elements that have pseudo-elements ::before & ::after (not necessarily at the same time). Also, I need to apply styles to these pseudo-elements.

I thought this solution would work:

*:has(::before, ::after) {
  content: '';
  /* Something else ... */
}


问:
Embed a PySide6/PyQT5 Widget into a QT C++ application?
While this question has already been answered at Embeding PySide/PyQt widget into Qt/C++ application . I could not reproduce the code because I did not have OPs functions and more importantly the post is 8+ years old and QT has developed a lot since then, especially when it comes to Python.

I need a method to have my PySide widget called by C++ QT main window/application and essentially work as a QColor, I need to call it and it will return a value just like how QColor works.

Simplified explanation:

I need to call my PySide widget in C++ QT like this

a = CustomPySideWidget()

I need to be able to recieve data to the variable a, this data can be returned as a simple string so the data type will be C++ compatible.

Is there any methods to do this via PySide or PyQT?

Thank you for any help.


问:
For each order calculate total calories
I know that this is a noobie question but I really need help.

If I make a table that is like this.

OrderNo.
Food
Calories

1
Fries
400 kcals

1
Chicken
327 kcals

1
Thighs
454 kcals

2
Rice
291 kcals

2
Meat
167 kcals

I need to know for each order what is the there total calories
like this

OrderNo.
Calories

1
1181 kcals

2
458 Kcals

So what to do? I need help.

So.
I tried to make both of them variables but it didn't work out

Title: For each order calculate total calories


问:
Is it okay to extend the Flutter built-in TextStyle class with my own custom methods?
Is there a problem if I extend some of the framework's built-in classes, specifically TextStyle, with my own extension methods? docs here

I'll layout an example of what I mean so that it resembles the actual implementation I'm using in my project - but not fully, it's just to be as clear and clean as possible:

In this example I'm declaring some common-use text styles (for context, in my project I have many many more), and later I'm extending the built-in flutter class TextStyle to have a faster and smoother implementation of further customization:

// some text styles I'll use across the whole app
const TextStyle titleLarge600 = TextStyle(
  fontSize: 20.0,
  fontWeight: FontWeight.w600,
);

const TextStyle titleSmall500 = TextStyle(
  fontSize: 16.0,
  fontWeight: FontWeight.w500,
);

const TextStyle bodyRegular400 = TextStyle(
  fontSize: 14.0,
  fontWeight: FontWeight.w400,
);

// ...

//* Here it comes
extension CopyWithStyles on TextStyle {
  /// Copy with [MyColors.primaryFontColor] color.
  TextStyle get primaryColor => copyWith(color: MyColors.primaryFontColor);

  /// Copy with [MyColors.accentColor] color.
  TextStyle get accentColor => copyWith(color: MyColors.accentColor);

  // ... several colors later

  /// Copy with [TextDecoration.underline] decoration.
  TextStyle get underline => copyWith(decoration: TextDecoration.underline);

  /// Copy with [TextStyle.letterSpacing] of 0.4.
  TextStyle get withLetterSpacing => copyWith(letterSpacing: 0.4);

  // etc ...
}
```
<p>This allows me to later just import these styles and methods and implement them in my <code>Text</code> widgets:</p>
<pre class="lang-dart prettyprint-override"><code>// ...
Text('Some title', style: titleSmall500.primaryColor),
</code>```

... and even concatenate them:

// ...
Text(
  'Some action here',
  style: bodyRegular400.accentColor.underline.withLetterSpacing, // ← THIS WORKS! it has no limits really
),
```

I'm amazed as to how flexible extension methods are, but in this particular case (extending TextStyle) I'm wondering about performance issues, and compatibility with the framework, or if maybe I'm missing something and actually should not do this.

For the moment I'm not experiencing any issues. Still, I'm wondering if there could be any potential problems. Is there a problem if I implement something like this in my projects? Is there something I'm not considering and should take into account in the future?

TY

Body:
Is there a problem if I extend some of the framework's built-in classes, specifically TextStyle, with my own extension methods? docs here

I'll layout an example of what I mean so that it resembles the actual implementation I'm using in my project - but not fully, it's just to be as clear and clean as possible:

In this example I'm declaring some common-use text styles (for context, in my project I have many many more), and later I'm extending the built-in flutter class TextStyle to have a faster and smoother implementation of further customization:

// some text styles I'll use across the whole app
const TextStyle titleLarge600 = TextStyle(
  fontSize: 20.0,
  fontWeight: FontWeight.w600,
);

const TextStyle titleSmall500 = TextStyle(
  fontSize: 16.0,
  fontWeight: FontWeight.w500,
);

const TextStyle bodyRegular400 = TextStyle(
  fontSize: 14.0,
  fontWeight: FontWeight.w400,
);

// ...

//* Here it comes
extension CopyWithStyles on TextStyle {
  /// Copy with [MyColors.primaryFontColor] color.
  TextStyle get primaryColor => copyWith(color: MyColors.primaryFontColor);

  /// Copy with [MyColors.accentColor] color.
  TextStyle get accentColor => copyWith(color: MyColors.accentColor);

  // ... several colors later

  /// Copy with [TextDecoration.underline] decoration.
  TextStyle get underline => copyWith(decoration: TextDecoration.underline);

  /// Copy with [TextStyle.letterSpacing] of 0.4.
  TextStyle get withLetterSpacing => copyWith(letterSpacing: 0.4);

  // etc ...
}

This allows me to later just import these styles and methods and implement them in my Text widgets:

// ...
Text('Some title', style: titleSmall500.primaryColor),

... and even concatenate them:

// ...
Text(
  'Some action here',
  style: bodyRegular400.accentColor.underline.withLetterSpacing, // ← THIS WORKS! it has no limits really
),

I'm amazed as to how flexible extension methods are, but in this particular case (extending TextStyle) I'm wondering about performance issues, and compatibility with the framework, or if maybe I'm missing something and actually should not do this.

For the moment I'm not experiencing any issues. Still, I'm wondering if there could be any potential problems. Is there a problem if I implement something like this in my projects? Is there something I'm not considering and should take into account in the future?

TY


问:
Basler Pylon camera parameter set command causing image grab timeout
I have code to control the settings of and grab images from a Basler acA720-290gm camera. After a period of running, if the exposure time is changed, the Pylon::CBaslerUniversalInstantCamera.RetrieveResult call starts timing out and the camera becomes unresponsive to further requests to change the exposure time. The exposure time is not set to be large enough that it should be causing a timeout.

This is the heart of the code in question:

```<code>void process_pylon(Pylon::String_t serial_number, int64_t width, int64_t height, int64_t packet_size, int64_t inter_packet_delay) {
    try {
        Pylon::CBaslerUniversalInstantCamera camera;
        Pylon::CTlFactory& tlFactory = Pylon::CTlFactory::GetInstance();
        Pylon::CDeviceInfo info;
        Pylon::DeviceInfoList_t filter;
        info.SetSerialNumber(serial_number);
        filter.push_back(info);
        Pylon::DeviceInfoList_t devices;

        while (1) {
            try {
                while (1) {
                    if (tlFactory.EnumerateDevices(devices, filter) > 0) {
                        g_print("The camera is connected.\n");
                        break;
                    }
                    else {
                        g_printerr("The camera is not connected.\n");
                        Pylon::WaitObject::Sleep(5000);
                    }
                }

                g_print("Attaching camera.\n");
                camera.Attach(tlFactory.CreateFirstDevice(info));

                g_print("Opening camera.\n");
                camera.Open();

                g_print("Setting width: %li\n", width);
                camera.Width.TrySetValue(width);

                g_print("Setting height: %li\n", height);
                camera.Height.TrySetValue(height);

                g_print("Setting GevSCPSPacketSize (packet size): %li\n", packet_size);
                camera.GevSCPSPacketSize.TrySetValue(packet_size);

                g_print("Setting GevSCPD (inter-packet delay): %li\n", inter_packet_delay);
                camera.GevSCPD.TrySetValue(inter_packet_delay);

                g_print("Starting grabbing.\n");
                camera.StartGrabbing(Pylon::GrabStrategy_LatestImageOnly);

                Pylon::CGrabResultPtr ptrGrabResult;

                exposure_auto_set = 1;
                exposure_time_raw_set = 1;
                gain_auto_set = 1;
                gain_raw_set = 1;

                while (1) {
                    // Exposure Time

                    int32_t epics_exposure_auto_req = exposure_auto_req;
                    int32_t epics_exposure_auto_set = exposure_auto_set;

                    if (epics_exposure_auto_set > 0) {
                        g_print("Setting auto exposure: %i\n", epics_exposure_auto_req);
                        camera.ExposureAuto.SetIntValue((int64_t) epics_exposure_auto_req);
                        exposure_auto_set = 0;
                    }
                    exposure_auto = camera.ExposureAuto.GetIntValue();

                    int32_t epics_exposure_time_raw_req = exposure_time_raw_req;
                    int32_t epics_exposure_time_raw_set = exposure_time_raw_set;

                    if (epics_exposure_time_raw_set > 0) {
                        g_print("Setting exposure time: %i\n", epics_exposure_time_raw_req);
                        camera.ExposureTimeRaw.TrySetValue((int64_t) epics_exposure_time_raw_req, Pylon::IntegerValueCorrection_Nearest);
                        exposure_time_raw_set = 0;
                    }
                    exposure_time_raw = camera.ExposureTimeRaw.GetValue();

                    // Gain

                    int32_t epics_gain_auto_req = gain_auto_req;
                    int32_t epics_gain_auto_set = gain_auto_set;

                    if (epics_gain_auto_set > 0) {
                        g_print("Setting auto gain: %i\n", epics_gain_auto_req);
                        camera.GainAuto.SetIntValue((int64_t) epics_gain_auto_req);
                        gain_auto_set = 0;
                    }
                    gain_auto = camera.GainAuto.GetIntValue();

                    int32_t epics_gain_raw_req = gain_raw_req;
                    int32_t epics_gain_raw_set = gain_raw_set;

                    if (epics_gain_raw_set > 0) {
                        g_print("Setting gain: %i\n", epics_gain_raw_req);
                        camera.GainRaw.TrySetValue((int64_t) epics_gain_raw_req, Pylon::IntegerValueCorrection_Nearest);
                        gain_raw_set = 0;
                    }
                    gain_raw = camera.GainRaw.GetValue();

                    try {
                        camera.RetrieveResult((unsigned int) timeout_ms, ptrGrabResult, Pylon::TimeoutHandling_ThrowException);
                        if (ptrGrabResult->GrabSucceeded()) {
                            if (image_mutex.try_lock()) {
                                image.AttachGrabResultBuffer(ptrGrabResult);
                                image_mutex.unlock();
                            }
                        }
                        else {
                            g_printerr("The grab failed.\n");
                            g_printerr("%s\n", ptrGrabResult->GetErrorDescription().c_str());
                        }
                    }
                    catch (const Pylon::TimeoutException e) {
                        g_printerr("%s\n", e.GetDescription());
                    }
                }
            }
            catch (const Pylon::GenericException& e) {
                Pylon::WaitObject::Sleep(1000);

                if (camera.IsCameraDeviceRemoved()) {
                    g_printerr("The connection to the camera has been lost.\n");
                    camera.DestroyDevice();
                }
                else {
                    g_printerr("%s\n", e.GetDescription());
                }
            }
        }
    }
    catch (const Pylon::GenericException& e) {
        g_printerr("An exception occurred.\n");
        g_printerr("%s\n", e.GetDescription());
        exit(-1);
    }
}
</code>```

Body:
I have code to control the settings of and grab images from a Basler acA720-290gm camera. After a period of running, if the exposure time is changed, the Pylon::CBaslerUniversalInstantCamera.RetrieveResult call starts timing out and the camera becomes unresponsive to further requests to change the exposure time. The exposure time is not set to be large enough that it should be causing a timeout.

This is the heart of the code in question:

void process_pylon(Pylon::String_t serial_number, int64_t width, int64_t height, int64_t packet_size, int64_t inter_packet_delay) {
    try {
        Pylon::CBaslerUniversalInstantCamera camera;
        Pylon::CTlFactory& tlFactory = Pylon::CTlFactory::GetInstance();
        Pylon::CDeviceInfo info;
        Pylon::DeviceInfoList_t filter;
        info.SetSerialNumber(serial_number);
        filter.push_back(info);
        Pylon::DeviceInfoList_t devices;

        while (1) {
            try {
                while (1) {
                    if (tlFactory.EnumerateDevices(devices, filter) > 0) {
                        g_print("The camera is connected.\n");
                        break;
                    }
                    else {
                        g_printerr("The camera is not connected.\n");
                        Pylon::WaitObject::Sleep(5000);
                    }
                }

                g_print("Attaching camera.\n");
                camera.Attach(tlFactory.CreateFirstDevice(info));

                g_print("Opening camera.\n");
                camera.Open();

                g_print("Setting width: %li\n", width);
                camera.Width.TrySetValue(width);

                g_print("Setting height: %li\n", height);
                camera.Height.TrySetValue(height);

                g_print("Setting GevSCPSPacketSize (packet size): %li\n", packet_size);
                camera.GevSCPSPacketSize.TrySetValue(packet_size);

                g_print("Setting GevSCPD (inter-packet delay): %li\n", inter_packet_delay);
                camera.GevSCPD.TrySetValue(inter_packet_delay);

                g_print("Starting grabbing.\n");
                camera.StartGrabbing(Pylon::GrabStrategy_LatestImageOnly);

                Pylon::CGrabResultPtr ptrGrabResult;

                exposure_auto_set = 1;
                exposure_time_raw_set = 1;
                gain_auto_set = 1;
                gain_raw_set = 1;

                while (1) {
                    // Exposure Time

                    int32_t epics_exposure_auto_req = exposure_auto_req;
                    int32_t epics_exposure_auto_set = exposure_auto_set;

                    if (epics_exposure_auto_set > 0) {
                        g_print("Setting auto exposure: %i\n", epics_exposure_auto_req);
                        camera.ExposureAuto.SetIntValue((int64_t) epics_exposure_auto_req);
                        exposure_auto_set = 0;
                    }
                    exposure_auto = camera.ExposureAuto.GetIntValue();

                    int32_t epics_exposure_time_raw_req = exposure_time_raw_req;
                    int32_t epics_exposure_time_raw_set = exposure_time_raw_set;

                    if (epics_exposure_time_raw_set > 0) {
                        g_print("Setting exposure time: %i\n", epics_exposure_time_raw_req);
                        camera.ExposureTimeRaw.TrySetValue((int64_t) epics_exposure_time_raw_req, Pylon::IntegerValueCorrection_Nearest);
                        exposure_time_raw_set = 0;
                    }
                    exposure_time_raw = camera.ExposureTimeRaw.GetValue();

                    // Gain

                    int32_t epics_gain_auto_req = gain_auto_req;
                    int32_t epics_gain_auto_set = gain_auto_set;

                    if (epics_gain_auto_set > 0) {
                        g_print("Setting auto gain: %i\n", epics_gain_auto_req);
                        camera.GainAuto.SetIntValue((int64_t) epics_gain_auto_req);
                        gain_auto_set = 0;
                    }
                    gain_auto = camera.GainAuto.GetIntValue();

                    int32_t epics_gain_raw_req = gain_raw_req;
                    int32_t epics_gain_raw_set = gain_raw_set;

                    if (epics_gain_raw_set > 0) {
                        g_print("Setting gain: %i\n", epics_gain_raw_req);
                        camera.GainRaw.TrySetValue((int64_t) epics_gain_raw_req, Pylon::IntegerValueCorrection_Nearest);
                        gain_raw_set = 0;
                    }
                    gain_raw = camera.GainRaw.GetValue();

                    try {
                        camera.RetrieveResult((unsigned int) timeout_ms, ptrGrabResult, Pylon::TimeoutHandling_ThrowException);
                        if (ptrGrabResult->GrabSucceeded()) {
                            if (image_mutex.try_lock()) {
                                image.AttachGrabResultBuffer(ptrGrabResult);
                                image_mutex.unlock();
                            }
                        }
                        else {
                            g_printerr("The grab failed.\n");
                            g_printerr("%s\n", ptrGrabResult->GetErrorDescription().c_str());
                        }
                    }
                    catch (const Pylon::TimeoutException e) {
                        g_printerr("%s\n", e.GetDescription());
                    }
                }
            }
            catch (const Pylon::GenericException& e) {
                Pylon::WaitObject::Sleep(1000);

                if (camera.IsCameraDeviceRemoved()) {
                    g_printerr("The connection to the camera has been lost.\n");
                    camera.DestroyDevice();
                }
                else {
                    g_printerr("%s\n", e.GetDescription());
                }
            }
        }
    }
    catch (const Pylon::GenericException& e) {
        g_printerr("An exception occurred.\n");
        g_printerr("%s\n", e.GetDescription());
        exit(-1);
    }
}


问:
Android studio on Ubuntu to Pixel 6 phone
I am attempting to put an application on my pixel phone when I attempt to install it I get the message that the version of java needs to be java 11 or greater.

the version that android studio uses is located in .../android-studio/jre/bin and is a compressed file.

First, I don't understand why android would require a version of a tool that it supplies the wrong version of?

Do I have to reinstall android studio to get the correct version, I can't find a simple button to press for android to do an incremental update or something?


问:
upgrading byte enums to c++17
I have a codebase with byte defined like so:

```<code>typedef unsigned char byte;
</code>```

And this enum:

enum SymbolTypes
{
    VARIABLE_SYMBOL_TYPE = 0,
    IDENTIFIER_SYMBOL_TYPE = 1,
    STR_CONSTANT_SYMBOL_TYPE = 2,
    INT_CONSTANT_SYMBOL_TYPE = 3,
    FLOAT_CONSTANT_SYMBOL_TYPE = 4,
    UNDEFINED_SYMBOL_TYPE = 5
};
```
<p>At some point there is a comparison between a <code>byte</code> value and a member of this enum:</p>
<pre class="lang-cpp prettyprint-override"><code>byte symbol_type = 0;
...
bool is_variable() { return (symbol_type == VARIABLE_SYMBOL_TYPE); }
</code>```

When setting the compiler to use C++17, I get these errors:

```<code>error: reference to ‘byte’ is ambiguous
</code>```

So I figured that maybe I'm supposed to be using std::byte now. After changing symbol_type to a std::byte, there is a new compiler error telling me that there's no operator == that matches the operands of std::byte and SymbolTypes. This SO answer says we can use an underlying type of std::byte like so:

enum SymbolTypes : std::underlying_type_t<std::byte>
{
    VARIABLE_SYMBOL_TYPE = 0,
    IDENTIFIER_SYMBOL_TYPE = 1,
    STR_CONSTANT_SYMBOL_TYPE = 2,
    INT_CONSTANT_SYMBOL_TYPE = 3,
    FLOAT_CONSTANT_SYMBOL_TYPE = 4,
    UNDEFINED_SYMBOL_TYPE = 5
};
```

However, the compiler still complains that there's no == operator with operands of type std::byte and SymbolTypes. How do I get this simple comparison line to compile correctly? Or should I be doing something else to avoid the usage of std::byte?

Title: upgrading byte enums to c++17

Body:
I have a codebase with byte defined like so:

typedef unsigned char byte;

And this enum:

enum SymbolTypes
{
    VARIABLE_SYMBOL_TYPE = 0,
    IDENTIFIER_SYMBOL_TYPE = 1,
    STR_CONSTANT_SYMBOL_TYPE = 2,
    INT_CONSTANT_SYMBOL_TYPE = 3,
    FLOAT_CONSTANT_SYMBOL_TYPE = 4,
    UNDEFINED_SYMBOL_TYPE = 5
};

At some point there is a comparison between a byte value and a member of this enum:

byte symbol_type = 0;
...
bool is_variable() { return (symbol_type == VARIABLE_SYMBOL_TYPE); }

When setting the compiler to use C++17, I get these errors:

error: reference to ‘byte’ is ambiguous

So I figured that maybe I'm supposed to be using std::byte now. After changing symbol_type to a std::byte, there is a new compiler error telling me that there's no operator == that matches the operands of std::byte and SymbolTypes. This SO answer says we can use an underlying type of std::byte like so:

enum SymbolTypes : std::underlying_type_t<std::byte>
{
    VARIABLE_SYMBOL_TYPE = 0,
    IDENTIFIER_SYMBOL_TYPE = 1,
    STR_CONSTANT_SYMBOL_TYPE = 2,
    INT_CONSTANT_SYMBOL_TYPE = 3,
    FLOAT_CONSTANT_SYMBOL_TYPE = 4,
    UNDEFINED_SYMBOL_TYPE = 5
};

However, the compiler still complains that there's no == operator with operands of type std::byte and SymbolTypes. How do I get this simple comparison line to compile correctly? Or should I be doing something else to avoid the usage of std::byte?


问:
Avalonia: Is there a way embed Process' Window on Linux
Hello as you know the VLCPlayer not supporting RTSP stream on debian bullseye and pardus21 anymore.

I'm searching a way put native window to Control on Linux for Avalonia.

On windows it's so easy.

```<code>[DllImport("user32.dll", SetLastError = true)]
private static extern bool SetWindowPos(IntPtr hWnd, int X, int Y, int cx, int cy, uint flags);

[DllImport("user32.dll")]
private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
...
if (ffProcess.MainWindowHandle != IntPtr.Zero) {
  SetParent(ffProcess.MainWindowHandle, ctrl.Handle);
  MoveWindow(ffProcess.MainWindowHandle, 0, 0, ctrl.Width, ctrl.Height, true);
}
</code>```

is there a way embedding process' window for Linux?

Body:
Hello as you know the VLCPlayer not supporting RTSP stream on debian bullseye and pardus21 anymore.

I'm searching a way put native window to Control on Linux for Avalonia.

On windows it's so easy.

[DllImport("user32.dll", SetLastError = true)]
private static extern bool SetWindowPos(IntPtr hWnd, int X, int Y, int cx, int cy, uint flags);

[DllImport("user32.dll")]
private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
...
if (ffProcess.MainWindowHandle != IntPtr.Zero) {
  SetParent(ffProcess.MainWindowHandle, ctrl.Handle);
  MoveWindow(ffProcess.MainWindowHandle, 0, 0, ctrl.Width, ctrl.Height, true);
}

is there a way embedding process' window for Linux?


问:
Is it possible to use the same instance of axios on a nextjs page that has client side uses, as well as server side uses?
I am using a popular library called axios in my Next.js app. Axios works on both the client (browser), and the server (node.js).

I have imported it at the top of a nextjs page component.

On the same page I export a function called getServerSideProps, per the nextjs documentation.

If I use axios on the client side, to make an ajax request, everything works fine. But when I move it into the getServerSideProps function, I get this error

```<code>ReferenceError: XMLHttpRequest is not defined
</code>```

It makes sense because XMLHttpRequest is a browser specific api, not native in node.js.

Is it possible to use the same instance of axios, which can be run on client or server, on a nextjs page that has client uses, as well as server side?

Body:
I am using a popular library called axios in my Next.js app. Axios works on both the client (browser), and the server (node.js).

I have imported it at the top of a nextjs page component.

On the same page I export a function called getServerSideProps, per the nextjs documentation.

If I use axios on the client side, to make an ajax request, everything works fine. But when I move it into the getServerSideProps function, I get this error

ReferenceError: XMLHttpRequest is not defined

It makes sense because XMLHttpRequest is a browser specific api, not native in node.js.

Is it possible to use the same instance of axios, which can be run on client or server, on a nextjs page that has client uses, as well as server side?


问:
Extra 'Undefined' parameter is adding to the api url for deleting request
I am implementing deleting record functionality where on clicking on the trash icon, the record with that id will be deleted from database. I'm using API endpoint, and mentioned it correctly in resource.js file as well.

The problem is that whenever I click on trash icon for deleting that row, and extra undefined parameter is added to the endpoint. Because of this, it's not able to reach the correct api endpoint and not able to delete the record.

Can anyone please provide any suggestion/input regarding this? I'm new to web development and not able to proceed further.

These are the code snippets I'm using:

Delete function triggering from trash icon

```<code>
        async onDelete(data) {
            console.log(data.leasing_agent_id);
            this.requestConfirmation({
                confirmationMessage: `Are you sure you want to delete agent ${data.first_name} ${data.last_name}?`,
                confirmBtnText: 'Delete',
                cancelBtnText: 'Go Back',
                confirmationType: 'warning',
            }).then(confirmed =>
                confirmed
                    ? this.$calendarDataProvider
                        .delete('calendarDeleteLeasingAgentsById', {
                            leasing_agent_id: data.leasing_agent_id,
                        })
                        .then(res => {
                            this.originalData = this.data = res;
                            this.$refs.vuetable.refresh();
                            this.notifySuccess(`Agent ${data.first_name} ${data.last_name}has been deleted`);
                        })
                        .catch(error => this.notifyError(error.message))
                    : null
            );
        },
</code>```

Button triggering the onDelete() function:

```<code><button
                    class="button"
                    @click="onDelete(props.rowData)"
                >
                    <icon
                        name="trash"
                        class="w-5 h-5 mt-2 ml-2 text-red-500"
                    />
                </button>
</code>```

All the above code is in my index.vue file.The resource.js file is like this:

```<code>    // Get leasing agents by customer id
    calendarGetLeasingAgents: '/leasing-agents/customers/{customer_id}',

    // Get leasing agents by id
    calendarGetLeasingAgentsById: '/leasing-agents/{leasing_agent_id}',

    // Save leasing agent
    calendarSaveLeasingAgents: '/leasing-agents',

    //Delete leasing agent
    calendarDeleteLeasingAgentsById: '/leasing-agents/{leasing_agent_id}',
</code>```

Also, attaching a screenshot of how error looks like:
https://drive.google.com/file/d/1aMKjLRQJGG4Eg-YsPRa6p73gs4mPIkcg/view?usp=sharing

Any input would be appreciated.

Body:
I am implementing deleting record functionality where on clicking on the trash icon, the record with that id will be deleted from database. I'm using API endpoint, and mentioned it correctly in resource.js file as well.

The problem is that whenever I click on trash icon for deleting that row, and extra undefined parameter is added to the endpoint. Because of this, it's not able to reach the correct api endpoint and not able to delete the record.

Can anyone please provide any suggestion/input regarding this? I'm new to web development and not able to proceed further.

These are the code snippets I'm using:

Delete function triggering from trash icon

        async onDelete(data) {
            console.log(data.leasing_agent_id);
            this.requestConfirmation({
                confirmationMessage: `Are you sure you want to delete agent ${data.first_name} ${data.last_name}?`,
                confirmBtnText: 'Delete',
                cancelBtnText: 'Go Back',
                confirmationType: 'warning',
            }).then(confirmed =>
                confirmed
                    ? this.$calendarDataProvider
                        .delete('calendarDeleteLeasingAgentsById', {
                            leasing_agent_id: data.leasing_agent_id,
                        })
                        .then(res => {
                            this.originalData = this.data = res;
                            this.$refs.vuetable.refresh();
                            this.notifySuccess(`Agent ${data.first_name} ${data.last_name}has been deleted`);
                        })
                        .catch(error => this.notifyError(error.message))
                    : null
            );
        },

Button triggering the onDelete() function:

<button
                    class="button"
                    @click="onDelete(props.rowData)"
                >
                    <icon
                        name="trash"
                        class="w-5 h-5 mt-2 ml-2 text-red-500"
                    />
                </button>

All the above code is in my index.vue file.The resource.js file is like this:

    // Get leasing agents by customer id
    calendarGetLeasingAgents: '/leasing-agents/customers/{customer_id}',

    // Get leasing agents by id
    calendarGetLeasingAgentsById: '/leasing-agents/{leasing_agent_id}',

    // Save leasing agent
    calendarSaveLeasingAgents: '/leasing-agents',

    //Delete leasing agent
    calendarDeleteLeasingAgentsById: '/leasing-agents/{leasing_agent_id}',

Also, attaching a screenshot of how error looks like:
https://drive.google.com/file/d/1aMKjLRQJGG4Eg-YsPRa6p73gs4mPIkcg/view?usp=sharing

Any input would be appreciated.


问:
Speed up for loop in python
I have a for loop as follows:

```<code>import MDAnalysis as mda
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from tqdm import tqdm as tq
import MDAnalysis.analysis.pca as pca
import random

def PCA_projection(pdb,dcd,atomgroup):
    u = mda.Universe(pdb,dcd)
    PSF_pca = pca.PCA(u, select=atomgroup)
    PSF_pca.run(verbose=True)
    n_pcs = np.where(PSF_pca.results.cumulated_variance > 0.95)[0][0]
    atomgroup = u.select_atoms(atomgroup)
    pca_space = PSF_pca.transform(atomgroup, n_components=n_pcs)
    PC1_proj = [pca_space[i][0] for i in range(len(pca_space))]
    PC2_proj = [pca_space[i][1] for i in range(len(pca_space))]
    return PC1_proj, PC2_proj

def Read_bias_potential(bias_potential):
    Bias_potential = pd.read_csv(bias_potential)
    Bias_potential = Bias_potential['En-User']
    Bias_potential = Bias_potential.values.tolist()
    W = [math.exp((-1 * i) / (0.001987*300)) for i in Bias_potential]
    return W

def Bin(PC1_prj, PC2_prj, frame_num, min_br1, max_br1, min_br2, max_br2, bin_num, W):
    #import pdb;pdb.set_trace()
    data1 = PC1_prj[0:frame_num]
    bins1 = np.linspace(min_br1, max_br1, bin_num)
    bins1 = np.round(bins1,2)
    digitized1 = np.digitize(data1, bins1)
    binc1 = np.arange(min_br1 + (max_br1 - min_br1)/2*bin_num,
max_br1 + (max_br1 - min_br1)/2*bin_num, (max_br1 - min_br1)/bin_num, dtype = float)
    binc1 = np.around(binc1,3)

    data2 = PC2_prj[0:frame_num]
    bins2 = np.linspace(min_br2, max_br2, bin_num)
    bins2 = np.round(bins2,2)
    digitized2 = np.digitize(data2, bins2)
    binc2 = np.arange(min_br2 + (max_br2 - min_br2)/2*bin_num, max_br2 + (max_br2 - min_br2)/2*bin_num, (max_br2 - min_br2)/bin_num, dtype = float)
    binc2 = np.around(binc2,3)

    w_array = np.zeros((bin_num,bin_num))

    for j in range(frame_num):
        w_array[digitized1[j]][digitized2[j]] += (W[digitized1[j]] + W[digitized2[j]])

    for m in range(bin_num):
        for n in range(bin_num):
            if w_array[m][n] == 0:
                w_array[m][n] = 1e-100

    return w_array, binc1, binc2

def gaussian(Sj1,Slj1,Sj2,Slj2,count):

    sigma1 = 0.5
    sigma2 = 0.5
    Kb = 0.001987204
    T = 300
    h0 = 0.0001
    g = 0
    C1 = 0
    C2 = 0
    for i in range((np.where(Slj2 == Sj2)[0][0] - 5),(np.where(Slj2 == Sj2)[0][0] + 6)):
        if i < 0:
            C2 = i + 1000
        elif i > 999:
            C2 = i - 1000
        else:
            C2 = i

        for j in range((np.where(Slj1 == Sj1)[0][0] - 5),(np.where(Slj2 == Sj2)[0][0] + 6)):
            if j < 0:
                C1 = j + 1000
            elif j > 999:
                C1 = j -1000
            else:
                C1 = j

            g = g + count[C2,C1] * h0 * np.exp( (-(Sj1 - Slj1[C1]) ** 2 / (2 * sigma1 ** 2)) + (-(Sj2 - Slj2[C2]) ** 2 / (2 * sigma2 ** 2)) )

    return np.exp(-g / (Kb * T))

def resampling(binc1, binc2, w_array):
#    import pdb;pdb.set_trace()
    l =1000
    F = np.zeros((l,l))
    count = np.zeros((l,l))
    Wn = w_array

    for i in tq(range(10000000)):
        SK1 = random.choice(binc1)
        SK2 = random.choice(binc2)
        SL1 = random.choice(binc1)
        SL2 = random.choice(binc2)
        while SK1 == SL1:
            SL1 = random.choice(binc1)
        while SK2 == SL2:
            SL2 = random.choice(binc2)
        F[np.where(binc2 == SK2)[0][0]][np.where(binc1 == SK1)[0][0]] = gaussian(SK1,binc1,SK2,binc2,count)
        F[np.where(binc2 == SK2)[0][0]][np.where(binc1 == SK1)[0][0]] = gaussian(SL1,binc1,SL2,binc2,count)
        W_SK = Wn[np.where(binc2 == SK2)[0][0]][np.where(binc1 == SK1)[0][0]] * F[np.where(binc2 == SK2)[0][0]][np.where(binc1 == SK1)[0][0]]
        W_SL = Wn[np.where(binc2 == SL2)[0][0]][np.where(binc1 == SL1)[0][0]] * F[np.where(binc2 == SL2)[0][0]][np.where(binc1 == SL1)[0][0]]
        if W_SK <= W_SL:
            SK1 = SL1
            SK2 = SL2
        else:
            a = random.random()
            if W_SL/W_SK >= a:
                SK1 = SL1
                SK2 = SL2
            else:
                SK1 = SK1
                SK2 = SK2
    #print('SK =',SK)
        count[np.where(binc2 == SK2)[0][0]][np.where(binc1 == SK1)[0][0]] += 1
    return F

</code>```

where binc1 and binc2 are two np.arrays, gaussian is a gaussian fxn I defined, is there anyway I can speed up this for loop? Now 1000000 steps takes approximately 50 mins. I am thinking about using pytorch but I got no idea on how to do it. Any suggestions would be helpful!

Thanks

I tried to use pytorch, like put all the variables on gpu but it only does worse.

Title: Speed up for loop in python

Body:
I have a for loop as follows:

import MDAnalysis as mda
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from tqdm import tqdm as tq
import MDAnalysis.analysis.pca as pca
import random

def PCA_projection(pdb,dcd,atomgroup):
    u = mda.Universe(pdb,dcd)
    PSF_pca = pca.PCA(u, select=atomgroup)
    PSF_pca.run(verbose=True)
    n_pcs = np.where(PSF_pca.results.cumulated_variance > 0.95)[0][0]
    atomgroup = u.select_atoms(atomgroup)
    pca_space = PSF_pca.transform(atomgroup, n_components=n_pcs)
    PC1_proj = [pca_space[i][0] for i in range(len(pca_space))]
    PC2_proj = [pca_space[i][1] for i in range(len(pca_space))]
    return PC1_proj, PC2_proj

def Read_bias_potential(bias_potential):
    Bias_potential = pd.read_csv(bias_potential)
    Bias_potential = Bias_potential['En-User']
    Bias_potential = Bias_potential.values.tolist()
    W = [math.exp((-1 * i) / (0.001987*300)) for i in Bias_potential]
    return W

def Bin(PC1_prj, PC2_prj, frame_num, min_br1, max_br1, min_br2, max_br2, bin_num, W):
    #import pdb;pdb.set_trace()
    data1 = PC1_prj[0:frame_num]
    bins1 = np.linspace(min_br1, max_br1, bin_num)
    bins1 = np.round(bins1,2)
    digitized1 = np.digitize(data1, bins1)
    binc1 = np.arange(min_br1 + (max_br1 - min_br1)/2*bin_num,
max_br1 + (max_br1 - min_br1)/2*bin_num, (max_br1 - min_br1)/bin_num, dtype = float)
    binc1 = np.around(binc1,3)

    data2 = PC2_prj[0:frame_num]
    bins2 = np.linspace(min_br2, max_br2, bin_num)
    bins2 = np.round(bins2,2)
    digitized2 = np.digitize(data2, bins2)
    binc2 = np.arange(min_br2 + (max_br2 - min_br2)/2*bin_num, max_br2 + (max_br2 - min_br2)/2*bin_num, (max_br2 - min_br2)/bin_num, dtype = float)
    binc2 = np.around(binc2,3)

    w_array = np.zeros((bin_num,bin_num))

    for j in range(frame_num):
        w_array[digitized1[j]][digitized2[j]] += (W[digitized1[j]] + W[digitized2[j]])

    for m in range(bin_num):
        for n in range(bin_num):
            if w_array[m][n] == 0:
                w_array[m][n] = 1e-100

    return w_array, binc1, binc2

def gaussian(Sj1,Slj1,Sj2,Slj2,count):

    sigma1 = 0.5
    sigma2 = 0.5
    Kb = 0.001987204
    T = 300
    h0 = 0.0001
    g = 0
    C1 = 0
    C2 = 0
    for i in range((np.where(Slj2 == Sj2)[0][0] - 5),(np.where(Slj2 == Sj2)[0][0] + 6)):
        if i < 0:
            C2 = i + 1000
        elif i > 999:
            C2 = i - 1000
        else:
            C2 = i

        for j in range((np.where(Slj1 == Sj1)[0][0] - 5),(np.where(Slj2 == Sj2)[0][0] + 6)):
            if j < 0:
                C1 = j + 1000
            elif j > 999:
                C1 = j -1000
            else:
                C1 = j

            g = g + count[C2,C1] * h0 * np.exp( (-(Sj1 - Slj1[C1]) ** 2 / (2 * sigma1 ** 2)) + (-(Sj2 - Slj2[C2]) ** 2 / (2 * sigma2 ** 2)) )

    return np.exp(-g / (Kb * T))

def resampling(binc1, binc2, w_array):
#    import pdb;pdb.set_trace()
    l =1000
    F = np.zeros((l,l))
    count = np.zeros((l,l))
    Wn = w_array

    for i in tq(range(10000000)):
        SK1 = random.choice(binc1)
        SK2 = random.choice(binc2)
        SL1 = random.choice(binc1)
        SL2 = random.choice(binc2)
        while SK1 == SL1:
            SL1 = random.choice(binc1)
        while SK2 == SL2:
            SL2 = random.choice(binc2)
        F[np.where(binc2 == SK2)[0][0]][np.where(binc1 == SK1)[0][0]] = gaussian(SK1,binc1,SK2,binc2,count)
        F[np.where(binc2 == SK2)[0][0]][np.where(binc1 == SK1)[0][0]] = gaussian(SL1,binc1,SL2,binc2,count)
        W_SK = Wn[np.where(binc2 == SK2)[0][0]][np.where(binc1 == SK1)[0][0]] * F[np.where(binc2 == SK2)[0][0]][np.where(binc1 == SK1)[0][0]]
        W_SL = Wn[np.where(binc2 == SL2)[0][0]][np.where(binc1 == SL1)[0][0]] * F[np.where(binc2 == SL2)[0][0]][np.where(binc1 == SL1)[0][0]]
        if W_SK <= W_SL:
            SK1 = SL1
            SK2 = SL2
        else:
            a = random.random()
            if W_SL/W_SK >= a:
                SK1 = SL1
                SK2 = SL2
            else:
                SK1 = SK1
                SK2 = SK2
    #print('SK =',SK)
        count[np.where(binc2 == SK2)[0][0]][np.where(binc1 == SK1)[0][0]] += 1
    return F

where binc1 and binc2 are two np.arrays, gaussian is a gaussian fxn I defined, is there anyway I can speed up this for loop? Now 1000000 steps takes approximately 50 mins. I am thinking about using pytorch but I got no idea on how to do it. Any suggestions would be helpful!

Thanks

I tried to use pytorch, like put all the variables on gpu but it only does worse.


问:
In Python unit test , how to mock a function with a input parameter changed in the function
I have following Python code:

```<code>para={is_done: False}
def func_1(para):
    para[is_done] = func_4()

def func_2(para):
    para[is_done] = func_5()

def func_3():
    # do something here
    return

def do_something(para):
    if not para[is_done]:
        func_1(para)
    if not para[is_done]:
        func_2(para)
    if not para[is_done]:
        func_3()
</code>```

How can I unit test the function do_something(para)?
The problem is that para={is_done: False} is a parameter for func_1 and changed based on the func_4 returns in it. Then the func_2(para) will or will not be called based on the modified is_done. I can mock func_1 and func_2 in do_something function, but I do not know how to mock para[is_done].

In my real code, para is a big dictionary and is_done is just one of them.

Any help will be greatly appreciated.

Body:
I have following Python code:

para={is_done: False}
def func_1(para):
    para[is_done] = func_4()

def func_2(para):
    para[is_done] = func_5()

def func_3():
    # do something here
    return

def do_something(para):
    if not para[is_done]:
        func_1(para)
    if not para[is_done]:
        func_2(para)
    if not para[is_done]:
        func_3()

How can I unit test the function do_something(para)?
The problem is that para={is_done: False} is a parameter for func_1 and changed based on the func_4 returns in it. Then the func_2(para) will or will not be called based on the modified is_done. I can mock func_1 and func_2 in do_something function, but I do not know how to mock para[is_done].

In my real code, para is a big dictionary and is_done is just one of them.

Any help will be greatly appreciated.


问:
how to save a plot map on .tiff format on R
I am plotting an image with this code but I am having some trouble when I Try to save it.

```<code>library(markovchain)
library(expm)
library(diagram)
library(pracma)

stateNames <- c("Fischer", "Lewis", "Medium")

q0 <- new("markovchain", states = stateNames,
          transitionMatrix =matrix(c(0.08,0.15,0.77,
                                     0.25,0.13,0.62,
                                     0.16,0.18,0.66),
                         byrow = TRUE, nrow = 3), name = "state t0")

q0_p <- matrix(c(0.08,0.15,0.77,
                    0.25,0.13,0.62,
                    0.16,0.18,0.66),
                    byrow = TRUE, nrow = 3)
row.names(q0_p) <- stateNames; colnames(q0_p) <- stateNames

plotmat(q0_p,pos = c(1,2),
        lwd = 1, box.lwd = 1,
        cex.txt = 0.8,
        box.size = 0.1,
        box.type = "circle",
        box.prop = 0.7,
        box.col = c("#F8766D", "#00BA38","#619CFF"),
        shadow.size = 0,
        arr.length=.2,
        arr.width=.1,
        self.cex =.4,
        self.shifty = -.01,
        self.shiftx = .13,
        main = "")

tiff(file="plotq0_3.tiff",width=15,height=10,units="cm",res=300)
</code>```

but when I go to the file, it weight 6128 kb but I can't see the image. Here is a copy.

Body:
I am plotting an image with this code but I am having some trouble when I Try to save it.

library(markovchain)
library(expm)
library(diagram)
library(pracma)

stateNames <- c("Fischer", "Lewis", "Medium")

q0 <- new("markovchain", states = stateNames,
          transitionMatrix =matrix(c(0.08,0.15,0.77,
                                     0.25,0.13,0.62,
                                     0.16,0.18,0.66),
                         byrow = TRUE, nrow = 3), name = "state t0")

q0_p <- matrix(c(0.08,0.15,0.77,
                    0.25,0.13,0.62,
                    0.16,0.18,0.66),
                    byrow = TRUE, nrow = 3)
row.names(q0_p) <- stateNames; colnames(q0_p) <- stateNames

plotmat(q0_p,pos = c(1,2),
        lwd = 1, box.lwd = 1,
        cex.txt = 0.8,
        box.size = 0.1,
        box.type = "circle",
        box.prop = 0.7,
        box.col = c("#F8766D", "#00BA38","#619CFF"),
        shadow.size = 0,
        arr.length=.2,
        arr.width=.1,
        self.cex =.4,
        self.shifty = -.01,
        self.shiftx = .13,
        main = "")

tiff(file="plotq0_3.tiff",width=15,height=10,units="cm",res=300)

but when I go to the file, it weight 6128 kb but I can't see the image. Here is a copy.


问:
Error trying to create a microservice using mino-cli
I'm trying to run this command minos new microservice wallet, and I get this error:

How can I resolve this?


问:
Python Tried everything. Still getting this error: TypeError(f"Invalid comparison between dtype={left.dtype} and {typ}")
I hope you can help me with this issue, I've been having for a while. I keep getting this error no matter what i try:

This is the type as I know it:

```<code>tweets['post_date'] = pd.to_datetime(tweets['post_date'], unit='s')
tweets['date'] = pd.to_datetime(tweets['post_date'].apply(lambda date: date.date()))

tweets.head()
</code>```

Output:

```<code>

    post_date   body    ticker_symbol   date
19  2015-01-01 00:11:17 $UNP $ORCL $QCOM $MSFT $AAPL Top scoring mega ...   MSFT    2015-01-01
43  2015-01-01 00:55:58 http://StockAviator.com....Top penny stocks, N...   MSFT    2015-01-01

</code>```

```<code>TypeError                                 Traceback (most recent call last)
/usr/local/lib/python3.8/dist-packages/pandas/core/arrays/datetimelike.py in _validate_comparison_value(self, other)
    539             try:
--> 540                 self._check_compatible_with(other)
    541             except (TypeError, IncompatibleFrequency) as err:

13 frames
TypeError: Cannot compare tz-naive and tz-aware datetime-like objects.

The above exception was the direct cause of the following exception:

InvalidComparison                         Traceback (most recent call last)
InvalidComparison: 2015-01-01 12:00:00-05:00

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
/usr/local/lib/python3.8/dist-packages/pandas/core/ops/invalid.py in invalid_comparison(left, right, op)
     32     else:
     33         typ = type(right).__name__
---> 34         raise TypeError(f"Invalid comparison between dtype={left.dtype} and {typ}")
     35     return res_values
     36

TypeError: Invalid comparison between dtype=datetime64[ns] and Timestamp
</code>```

This error comes from this column in my code:

```<code>#market opens 14:30 closes 21:00
def getAvgPerPrice (tweets,stockk):
    stock = stockk.copy()
    result = pd.DataFrame([])
    for i in range(0,len(stock)-1):
        d = stock.index[i]
        next_d = stock.index[i+1]
        wanted_tweets = tweets[((tweets.post_date - timedelta(hours = 3)) >=( d + timedelta(hours = h))) & ((tweets.post_date - timedelta(hours = 3)) < (next_d + timedelta(hours = h)))]
        result.at[i,'date'] = d
        result.at[i,'close'] = stock.iloc[i].Close
        result.at[i,'avgScore'] = wanted_tweets['score'].mean()
</code>```

I would really appreciate if anyone could help me find the issue. I have tried many things already but no luck. Thank you in advance

Body:
I hope you can help me with this issue, I've been having for a while. I keep getting this error no matter what i try:

This is the type as I know it:

tweets['post_date'] = pd.to_datetime(tweets['post_date'], unit='s')
tweets['date'] = pd.to_datetime(tweets['post_date'].apply(lambda date: date.date()))

tweets.head()

Output:

    post_date   body    ticker_symbol   date
19  2015-01-01 00:11:17 $UNP $ORCL $QCOM $MSFT $AAPL Top scoring mega ...   MSFT    2015-01-01
43  2015-01-01 00:55:58 http://StockAviator.com....Top penny stocks, N...   MSFT    2015-01-01

TypeError                                 Traceback (most recent call last)
/usr/local/lib/python3.8/dist-packages/pandas/core/arrays/datetimelike.py in _validate_comparison_value(self, other)
    539             try:
--> 540                 self._check_compatible_with(other)
    541             except (TypeError, IncompatibleFrequency) as err:

13 frames
TypeError: Cannot compare tz-naive and tz-aware datetime-like objects.

The above exception was the direct cause of the following exception:

InvalidComparison                         Traceback (most recent call last)
InvalidComparison: 2015-01-01 12:00:00-05:00

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
/usr/local/lib/python3.8/dist-packages/pandas/core/ops/invalid.py in invalid_comparison(left, right, op)
     32     else:
     33         typ = type(right).__name__
---> 34         raise TypeError(f"Invalid comparison between dtype={left.dtype} and {typ}")
     35     return res_values
     36

TypeError: Invalid comparison between dtype=datetime64[ns] and Timestamp

This error comes from this column in my code:

#market opens 14:30 closes 21:00
def getAvgPerPrice (tweets,stockk):
    stock = stockk.copy()
    result = pd.DataFrame([])
    for i in range(0,len(stock)-1):
        d = stock.index[i]
        next_d = stock.index[i+1]
        wanted_tweets = tweets[((tweets.post_date - timedelta(hours = 3)) >=( d + timedelta(hours = h))) & ((tweets.post_date - timedelta(hours = 3)) < (next_d + timedelta(hours = h)))]
        result.at[i,'date'] = d
        result.at[i,'close'] = stock.iloc[i].Close
        result.at[i,'avgScore'] = wanted_tweets['score'].mean()

I would really appreciate if anyone could help me find the issue. I have tried many things already but no luck. Thank you in advance


问:
Drawing lines from pivot points that meet a specific conditions
I have successfully created a script that draws a line from one pivot point to another based on some conditions.

The conditions are:

The next (or following next) pivot points must have a high that is lower than the original pivot point high

The next (or following next) pivot points must have its wick "touching" the original wick

It is not allowed to draw a line if there is any higher high in the range between the original pivothigh wick and the current pivothigh wick. If several conditions are meet, a "fan of lines" from the original pivot high can be created.

I asked a question about this before here Creating a fan of lines in pinescript

I managed to do this using arrays. Result can been seen here. Purple lines are "hand drawn" and the white dashed lines comes from the script.

So far so good. BUT I have 3 problems/issues:

When a new candle is created the script fails due to "range out of bounds". I know it comes from the var declarations of the arrays on lines 19-22. If on the 1h or above timeframe it's not a big issue but on 1m it's very annoying. But deleting the var it doesn't compile correctly.

It's slow. Takes a couple of seconds to compute even though I'm using a while statement that prevents the "lookback" if a "top" has been detected. Then it's no longer necessary to look back anymore.

Related to (2). I'm suspecting there is a much smarter way to do this in pinescript but I haven't figured it out yet without the use of arrays.

Here's the code.

Is it possible to do this without arrays to solve all my 3 issues above?

```<code>// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © sincereStork12718

//@version=5
indicator("Pivot lines", overlay=true, max_boxes_count=500, max_lines_count=500)

//---------------------------------------
//Variable declaration
//---------------------------------------
nbrBars =  bar_index
plot (nbrBars, title = "nbrBars", display = display.data_window)
plot(last_bar_index, title = "last_bar_index", display = display.data_window)

//---------------------------------------
// Pivot to downside with ARRAYS working 99.9%
//---------------------------------------

//Declare arrays
var index_array_bear = array.new<int>(last_bar_index)
var high_array = array.new<float>(last_bar_index)
var upwick_array = array.new<float>(last_bar_index)
var shadow_high = array.new<float>(last_bar_index+1)

isAttFUBear = ta.pivothigh(1,1) // For this example ta.pivothigh(1,1) will produce the same result
isFUBear = ta.pivothigh(1,1) //For this example ta.pivothigh(1,1) will produce the same result

//Get bar_index, the high and the start of the upper wick for all AttFU/FU to the downside in the series from first to last bar
var i_dn = 0
if (isAttFUBear or isFUBear) == 1
    array.set(index_array_bear, i_dn, bar_index[1])
    array.set(high_array, i_dn, high[1])
    array.set(upwick_array, i_dn, math.max(open[1], close[1]))
    i_dn += 1

var j_dn = 0
array.set(shadow_high, j_dn, high)
j_dn += 1

//Draw line from index n to all index n++ that satisfies the condition below
//1. n++ index must be lower than the n:th index, i.e. high[n++] < high[n]
//2. n++ index must have it's high above upwick of the n:th, i.e. high[n++] > upwick[n]
//3. There must be a filter that removes any high higher than high[n] and high[n++] to not draw any unneccesary lines, i.e. if a "top" is found is not longer neccecary to look backwards

cnt1 = 1
top_found = false
while i_dn >= 2 and i_dn-1-cnt1 >= 0 and top_found == false
    if array.get(high_array, i_dn-1-cnt1) > array.get(high_array, i_dn-1) //Checking if previous FU is higher than the current, if NOT, check the next previous etc.
        if array.get(high_array, i_dn-1) >= array.get(upwick_array, i_dn-1-cnt1) //Check if current high is retesting the wick of the previous
            //testing filter high in between
            high_in_range = array.new<float>(nbrBars) //Create temporary array that stores all high values between the first and last endpoints of the line
            for cnt2 = array.get(index_array_bear, i_dn-1-cnt1) to array.get(index_array_bear, i_dn-1)
                array.set(high_in_range, cnt2, array.get(shadow_high, cnt2))
            max_high_in_range = array.max(high_in_range, 2) //Return the second highest high within the range (excluding the i-1-cnt1 which is the higest)
            if array.get(high_array, i_dn-1) > max_high_in_range
                line.new(array.get(index_array_bear, i_dn-1-cnt1), array.get(high_array, i_dn-1-cnt1), array.get(index_array_bear, i_dn-1), array.get(high_array, i_dn-1), color = color.white, style = line.style_dashed, width = 1)
        if i_dn-1-cnt1-1 > 0 //Checking if current lookback FU is higher than previous and next. If true then stop the search
            if array.get(high_array, i_dn-1-cnt1) > array.get(high_array, i_dn-1-cnt1+1) and array.get(high_array, i_dn-1-cnt1) > array.get(high_array, i_dn-1-cnt1-1)
                top_found := true
    cnt1 := cnt1 +1
</code>```

Body:
I have successfully created a script that draws a line from one pivot point to another based on some conditions.

The conditions are:

The next (or following next) pivot points must have a high that is lower than the original pivot point high

The next (or following next) pivot points must have its wick "touching" the original wick

It is not allowed to draw a line if there is any higher high in the range between the original pivothigh wick and the current pivothigh wick. If several conditions are meet, a "fan of lines" from the original pivot high can be created.

I asked a question about this before here Creating a fan of lines in pinescript

I managed to do this using arrays. Result can been seen here. Purple lines are "hand drawn" and the white dashed lines comes from the script.

So far so good. BUT I have 3 problems/issues:

When a new candle is created the script fails due to "range out of bounds". I know it comes from the var declarations of the arrays on lines 19-22. If on the 1h or above timeframe it's not a big issue but on 1m it's very annoying. But deleting the var it doesn't compile correctly.

It's slow. Takes a couple of seconds to compute even though I'm using a while statement that prevents the "lookback" if a "top" has been detected. Then it's no longer necessary to look back anymore.

Related to (2). I'm suspecting there is a much smarter way to do this in pinescript but I haven't figured it out yet without the use of arrays.

Here's the code.

Is it possible to do this without arrays to solve all my 3 issues above?

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © sincereStork12718

//@version=5
indicator("Pivot lines", overlay=true, max_boxes_count=500, max_lines_count=500)

//---------------------------------------
//Variable declaration
//---------------------------------------
nbrBars =  bar_index
plot (nbrBars, title = "nbrBars", display = display.data_window)
plot(last_bar_index, title = "last_bar_index", display = display.data_window)

//---------------------------------------
// Pivot to downside with ARRAYS working 99.9%
//---------------------------------------

//Declare arrays
var index_array_bear = array.new<int>(last_bar_index)
var high_array = array.new<float>(last_bar_index)
var upwick_array = array.new<float>(last_bar_index)
var shadow_high = array.new<float>(last_bar_index+1)

isAttFUBear = ta.pivothigh(1,1) // For this example ta.pivothigh(1,1) will produce the same result
isFUBear = ta.pivothigh(1,1) //For this example ta.pivothigh(1,1) will produce the same result

//Get bar_index, the high and the start of the upper wick for all AttFU/FU to the downside in the series from first to last bar
var i_dn = 0
if (isAttFUBear or isFUBear) == 1
    array.set(index_array_bear, i_dn, bar_index[1])
    array.set(high_array, i_dn, high[1])
    array.set(upwick_array, i_dn, math.max(open[1], close[1]))
    i_dn += 1

var j_dn = 0
array.set(shadow_high, j_dn, high)
j_dn += 1

//Draw line from index n to all index n++ that satisfies the condition below
//1. n++ index must be lower than the n:th index, i.e. high[n++] < high[n]
//2. n++ index must have it's high above upwick of the n:th, i.e. high[n++] > upwick[n]
//3. There must be a filter that removes any high higher than high[n] and high[n++] to not draw any unneccesary lines, i.e. if a "top" is found is not longer neccecary to look backwards

cnt1 = 1
top_found = false
while i_dn >= 2 and i_dn-1-cnt1 >= 0 and top_found == false
    if array.get(high_array, i_dn-1-cnt1) > array.get(high_array, i_dn-1) //Checking if previous FU is higher than the current, if NOT, check the next previous etc.
        if array.get(high_array, i_dn-1) >= array.get(upwick_array, i_dn-1-cnt1) //Check if current high is retesting the wick of the previous
            //testing filter high in between
            high_in_range = array.new<float>(nbrBars) //Create temporary array that stores all high values between the first and last endpoints of the line
            for cnt2 = array.get(index_array_bear, i_dn-1-cnt1) to array.get(index_array_bear, i_dn-1)
                array.set(high_in_range, cnt2, array.get(shadow_high, cnt2))
            max_high_in_range = array.max(high_in_range, 2) //Return the second highest high within the range (excluding the i-1-cnt1 which is the higest)
            if array.get(high_array, i_dn-1) > max_high_in_range
                line.new(array.get(index_array_bear, i_dn-1-cnt1), array.get(high_array, i_dn-1-cnt1), array.get(index_array_bear, i_dn-1), array.get(high_array, i_dn-1), color = color.white, style = line.style_dashed, width = 1)
        if i_dn-1-cnt1-1 > 0 //Checking if current lookback FU is higher than previous and next. If true then stop the search
            if array.get(high_array, i_dn-1-cnt1) > array.get(high_array, i_dn-1-cnt1+1) and array.get(high_array, i_dn-1-cnt1) > array.get(high_array, i_dn-1-cnt1-1)
                top_found := true
    cnt1 := cnt1 +1


问:
TransferHttpCacheModule for POST calls
So I'm creating an Angular Universal SSR site. Fortunately with Angular 15 TransferHttpCacheModule is now automatically included.

But I can't believe considering how long that module has been around it can still only handle GET calls and not POST calls. The Back End api I have to work with have some POST calls which require me to send a body in order to get some search results. Is there an alternative library that anyone can recommend? Of course if I disable Javascript I can see the call working properly and printing out on my page. But then it will disappear when Javascript is enabled.

Title: TransferHttpCacheModule for POST calls


问:
window.getSelection in the ManifestV3 extension
What to use instead window.getSelection() in the ManifestV3 extension? It uses a service worker and doesn't have DOM or window.</p>


问:
DLL load failed while importing cv2: The specified module could not be found
I'm working on a CNN image classification project , and I'm using jupyter lab and python .
Well , I'm facing this problem and could not resolve it .
Ps : ( My windows edition is "Windows 10 Pro N" )enter image description here

I tried these two cmd "pip install opencv-python" & "pip install opencv-contrib-python" and i installed the dependencies manually .
Also the visual studio c++ is installed
But i get the same error enter image description here


问:
Classification of time-series according to the time intervals in python
I have several time series in a dataframe. The idea is detecting those ids that have shorter time between periods recently rather than the past and distinguish them from the others. After detecting them, I want to assign them to a specific class.
I am not looking for any codes, just want to get some ideas and hints to figure out the best approach. The following table is just a part of the data as a sample to show how it looks like. Thank you.

id
date
count

23
2/2/2016
24

24
2/4/2016
56

25
2/3/2016
135

23
3/4/2016
46

24
3/8/2016
176

25
3/9/2016
23

23
3/16/2016
98

24
3/13/2016
114

25
3/17/2016
43


问:
Extraction of unique audio features for audio classification
I want to identify unique features in an audio/speech file so that I may classify them properly. Which are the unique features that I may consider?

For example, I have files for the words 'TV' and 'CV'. Which features make them different? Please note that all the files have same length and same sampling rate. Also, the feature should be independent of the accent used.