问:
Azure Function v4 Triggered by Service Bus Sitting Idle
I have an Azure function running on a consumption service plan (Y1:0) on a Windows OS that is triggered by an Azure Service Bus queue item. However, the Azure function idles for extended periods of time and will not pull in queue items from the Service Bus. The following represent some of the idling issues:

Items being added onto the Service Bus and waiting 30-minutes to 1 hour or more to be dequeued and processed by the Azure function.

The Azure function processes a few items from the Service Bus and stops, leaving all other queued items to sit idle for similar time spans to the above point.

Items in the Service Bus dead lettering after 3 delivery attempts, but there are no logs or execution counts on Azure that indicate the function attempted to execute

The problem here isn't that a cold start takes a few minutes to get going, it's that the function seems to sit idle for extended periods of time and when or how long these idle periods happen seem to be random. During these idle periods, sometimes the function's memory working set will be above 0 and after long periods of time, it will drop to 0.

If items were left long enough in the Service Bus queue and did not dead letter, the Azure function would eventually process them. And occasionally, the function pulls from the Service Bus quickly. However, I need the function to run more consistently. From what I have read, the idle times I am experiencing are uncharacteristic for a consumption-based Azure function.

Here is more information on the function and Service Bus:

Service Bus

```<code>lockDuration: 'PT5M'
requiresDuplicateDetection: false
requiresSession: false
defaultMessageTimeToLive: 'P14D'
deadLetteringOnMessageExpiration: false
enableBatchedOperations: true
duplicateDetectionHistoryTimeWindow: 'PT10M'
maxDeliveryCount: 3
status: 'Active'
enablePartitioning: false
enableExpress: false
</code>```

Function

```<code>sku: {
    name: Y1
}
kind: 'windows'
netFrameworkVersion: 'v6.0'
</code>```

The following is the host.json file. However, I am using Azure Infrastructure as Code so some shared properties are defined in a bicep file.

```<code>{
"version": "2.0",
"logging": {
    "applicationInsights": {
        "samplingSettings": {
            "isEnabled": true,
            "excludedTypes": "Request"
        }
    }
}
</code>```

}

Based on other posts, I have tried switching the managed identity permissions of the function to be an owner instead of a receiver (since I am not using connection strings) but that has not solved any of the issues outlined previously.

Body:
I have an Azure function running on a consumption service plan (Y1:0) on a Windows OS that is triggered by an Azure Service Bus queue item. However, the Azure function idles for extended periods of time and will not pull in queue items from the Service Bus. The following represent some of the idling issues:

Items being added onto the Service Bus and waiting 30-minutes to 1 hour or more to be dequeued and processed by the Azure function.

The Azure function processes a few items from the Service Bus and stops, leaving all other queued items to sit idle for similar time spans to the above point.

Items in the Service Bus dead lettering after 3 delivery attempts, but there are no logs or execution counts on Azure that indicate the function attempted to execute

The problem here isn't that a cold start takes a few minutes to get going, it's that the function seems to sit idle for extended periods of time and when or how long these idle periods happen seem to be random. During these idle periods, sometimes the function's memory working set will be above 0 and after long periods of time, it will drop to 0.

If items were left long enough in the Service Bus queue and did not dead letter, the Azure function would eventually process them. And occasionally, the function pulls from the Service Bus quickly. However, I need the function to run more consistently. From what I have read, the idle times I am experiencing are uncharacteristic for a consumption-based Azure function.

Here is more information on the function and Service Bus:

Service Bus

lockDuration: 'PT5M'
requiresDuplicateDetection: false
requiresSession: false
defaultMessageTimeToLive: 'P14D'
deadLetteringOnMessageExpiration: false
enableBatchedOperations: true
duplicateDetectionHistoryTimeWindow: 'PT10M'
maxDeliveryCount: 3
status: 'Active'
enablePartitioning: false
enableExpress: false

Function

sku: {
    name: Y1
}
kind: 'windows'
netFrameworkVersion: 'v6.0'

The following is the host.json file. However, I am using Azure Infrastructure as Code so some shared properties are defined in a bicep file.

{
"version": "2.0",
"logging": {
    "applicationInsights": {
        "samplingSettings": {
            "isEnabled": true,
            "excludedTypes": "Request"
        }
    }
}

}

Based on other posts, I have tried switching the managed identity permissions of the function to be an owner instead of a receiver (since I am not using connection strings) but that has not solved any of the issues outlined previously.


来源: stackexchange

问:
SVG Polyline using relative (percentage) values in javascript
I have two divs connecting with an SVG line. My divs are not part of my SVG, so this works by placing one above the other. All divs and lines are placed relatively (like: position:absolute but with percents like: top:10%)

I would like to change my line to a polyline but I seem to be incapable of finding a solid documentation on how to do this.

right now, my lines work by adding a setAttribute:

```<code>const line: SVGLineElement = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('x1', `${from.x}%`);
line.setAttribute('y1', `${from.y}%`);
line.setAttribute('x2', `${to.x}%`);
line.setAttribute('y2', `${to.y}%`);
line.setAttribute('stroke', 'black');
this.connectionLines.nativeElement.appendChild(line);
</code>```

this has the intended effect:

What I tried:

```<code>polyline.setAttribute('x3', `${from.x + distance/2}`); // line not rendered
polyline.setAttribute('y3', `${from.y}`);

polyline.setAttribute('points', `10%, 10%`) // leads to Error: <polyline> attribute points: Expected number
polyline.setAttribute('points', `calc(10%) calc(10%)` // same error
</code>```

edit: just to state the obvious: I know I can split the lines in 3 SVGLineElements, it just feels pretty clumsy

ContentLicense: CC BY-SA 4.0

Body:
I have two divs connecting with an SVG line. My divs are not part of my SVG, so this works by placing one above the other. All divs and lines are placed relatively (like: position:absolute but with percents like: top:10%)

I would like to change my line to a polyline but I seem to be incapable of finding a solid documentation on how to do this.

right now, my lines work by adding a setAttribute:

const line: SVGLineElement = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('x1', `${from.x}%`);
line.setAttribute('y1', `${from.y}%`);
line.setAttribute('x2', `${to.x}%`);
line.setAttribute('y2', `${to.y}%`);
line.setAttribute('stroke', 'black');
this.connectionLines.nativeElement.appendChild(line);

this has the intended effect:

What I tried:

polyline.setAttribute('x3', `${from.x + distance/2}`); // line not rendered
polyline.setAttribute('y3', `${from.y}`);

polyline.setAttribute('points', `10%, 10%`) // leads to Error: <polyline> attribute points: Expected number
polyline.setAttribute('points', `calc(10%) calc(10%)` // same error

edit: just to state the obvious: I know I can split the lines in 3 SVGLineElements, it just feels pretty clumsy


问:
How to unroll database transactions Spring Boot MVC
I want a Spring Boot MVC application to unroll some database transactions (create, update, delete) as soon as the user's login sessions is terminated. JpaRepository and @Service are used. I have configured auto commit disabled. But it does not work, changes are persisted in database. What should I do to prevent it?

```<code>public interface BookRepository
extends JpaRepository<Book, Long> {}

public interface BookService {

// Save operation
Book saveBook(Book Book);

// Update operation
Book updateBook(Book book, Long bookId);

// Delete operation
void deleteBookById(Long bookId);
}
</code>```

And

```<code>spring.datasource.auto-commit=false
</code>```

Body:
I want a Spring Boot MVC application to unroll some database transactions (create, update, delete) as soon as the user's login sessions is terminated. JpaRepository and @Service are used. I have configured auto commit disabled. But it does not work, changes are persisted in database. What should I do to prevent it?

public interface BookRepository
extends JpaRepository<Book, Long> {}

public interface BookService {

// Save operation
Book saveBook(Book Book);

// Update operation
Book updateBook(Book book, Long bookId);

// Delete operation
void deleteBookById(Long bookId);
}

And

spring.datasource.auto-commit=false


问:
Inject Hotjar tracking code to  in Retool - Hotjar fails to connect
I'm playing around with Retool as a live prototyping tool. It would be extremely helpful to be able to wire up Hotjar with it to see how users interact with the prototype.

Hotjar offers a tracking code that needs to be added to the  element of the page. Then Hotjar can be connected and I assume opens the page and verifies that the tracking link is in place.
https://help.hotjar.com/hc/en-us/articles/115009336727-How-to-Install-Your-Hotjar-Tracking-Code

Retool doesn't officially allow accessing the documents  element as it might interfer with its logic. However, it allows to specify and run JS.

I was able to write a function that is called on window.onload and injects the Hotjar snippet into the  element of the page.

However, upon connecting Hotjar is not able to detect the Hotjar tracking code on my Retool page. My assumption is this is because at the time of checking the Retool DOM isn't exposing the tracking code.

Do you have any ideas how I could make this work instead?

Title: Inject Hotjar tracking code to <head> in Retool - Hotjar fails to connect


问:
Why we need <T> before void?
I'm learning Java generics. I found the first <T> to be difficult to understand: if the method returns nothing, what does the <T> before void means?</p>
```<code>public static <T> void fromArrayToCollection(T[] a, Collection<T> c) {
    for (T o : a) {
        c.add(o);
    }
}
</code>```

Title: Why we need <T> before void?

Body:
I'm learning Java generics. I found the first <T> to be difficult to understand: if the method returns nothing, what does the <T> before void means?

public static <T> void fromArrayToCollection(T[] a, Collection<T> c) {
    for (T o : a) {
        c.add(o);
    }
}


问:
Nginx subdomain running the wrong web application
so I have a ubuntu server that run two different website with two different domain:

```<code>www.firstwebsite.com
www.secondwebsite.com
</code>```

But when I create an AAA record to create a subdomain with the first domain (like this)

```<code>demo.firstwebsite.com
</code>```

If I go to this subdomain it automatically run the application website of my other domain (www.secondwebsite.com)

I tried creating a specific socket&service file for the subdomain for it but it still run the web application of the second domain.

Im not sure what is causing that and how to fix that? thank you

nginx config file

```<code>server {
    listen 80;
    server_name firstwebsite.com;
    return 301 $scheme://www.firstwebsite.com$request_uri;
}

server {
    listen 80;
    server_name www.firstwebsite.com;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /var/www/firstwebsite;
    }

    location /media/ {
        root /var/www/firstwebsite;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/firstwebsite.sock;
    }
}
</code>```

Body:
so I have a ubuntu server that run two different website with two different domain:

www.firstwebsite.com
www.secondwebsite.com

But when I create an AAA record to create a subdomain with the first domain (like this)

demo.firstwebsite.com

If I go to this subdomain it automatically run the application website of my other domain (www.secondwebsite.com)

I tried creating a specific socket&service file for the subdomain for it but it still run the web application of the second domain.

Im not sure what is causing that and how to fix that? thank you

nginx config file

server {
    listen 80;
    server_name firstwebsite.com;
    return 301 $scheme://www.firstwebsite.com$request_uri;
}

server {
    listen 80;
    server_name www.firstwebsite.com;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /var/www/firstwebsite;
    }

    location /media/ {
        root /var/www/firstwebsite;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/firstwebsite.sock;
    }
}


问:
Office 365 Single Sign-On (SSO) not working in Chrome
I have already logged into the windows 10 office app. And when I try to access office.com via the browser (Edge) I am already logged in (which is good). However, when I tried to do the same in Chrome, then I have to re-enter my credentials. I tried to change the default browser to Chrome and re-logged into the windows office app and still, Chrome is not automatically logging me in.

Additionally, I installed this chrome plugin which was offered by Microsoft. But still not working.

https://chrome.google.com/webstore/detail/windows-accounts/ppnbnpeolgkicgegkbkbjmhlideopiji

Does anyone encounter this problem and resolve it?


问:
Getting only 100sample/second from MPU6050 through Raspberry pi Pico
I wanted to plot the raw sensor data like the accelerometer gyroscope and temperature data of MPU6050. For me MPU6050 is soldered with Pico and Pico is connected to my laptop via a USB connection.

Now, my problem is the frequency is quite low like 100 samples/second. I am using a serial library of python for this. And on Pico's side, I have used UART. I should get at least 1khz frequency as per the MPU6050 datasheet. But, I am seriously doing something wrong here.
I am quite new and don’t have much clue how to increase the frequency in this case. Any help on this will be really helpful for me. Thanks in advance.

I am using baudrate 115200. I did some trial and error and find out that there is no problem between Pico and Python with pyserial. It’s like Pico is not able to read data from MPU6050 that fast because I am getting a lot of empty bytes with the use of serial.in_waiting(). I am uploading my code here. Just a bit of overview, my main.py uses two external modules imu.py and vector3d.py to read data. I am getting only 100 samples/second but It is a lot less. According to the MPU6050 datasheet, I should get at least 1khz frequency.

```<code>#PICO Code(main.py)
from imu import MPU6050
import utime
import time
from machine import Pin, I2C, UART

i2c = I2C(0, sda=Pin(4), scl=Pin(5), freq=400000)
imu = MPU6050(i2c)

uart = UART(0, baudrate=115200)
print("UART Info : ", uart)

while True:
    ax = round(imu.accel.x, 2)
    ay = round(imu.accel.y, 2)
    az = round(imu.accel.z, 2)
    gx = round(imu.gyro.x)
    gy = round(imu.gyro.y)
    gz = round(imu.gyro.z)
    tem = round(imu.temperature, 2)
    print(ax, ay, az, gx, gy, gz, tem)
</code>```
```<code>#Python side code
import serial
import time
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

ser = serial.Serial('COM4', 115200)
print(ser)

file = open("serial_sample.csv", "w")
start_time = time.time()
curr_time = time.time()
output_list = []
header_string = "X_accel" + "," + "Y_accel" + "," + "Z_accel" + "," + "X_Pos" + "," + "Y_Pos" + "," + "Z_Pos" \
     + "," + "Temperature" + "\n"

output_list.append(header_string)
while curr_time - start_time < 10:
    data = ser.readline()
    data = str(data).split("\\")[0].split(" ")
    output = data[0].split("'")[1] + "," + data[1] + "," + data[2] + "," + data[3] + "," + data[4] + ","
                  +\ data[5] + "," + data[6] + "\n"
    output_list.append(output)
    curr_time = time.time()

file.writelines(output_list)
file.close()

</code>```

Body:
I wanted to plot the raw sensor data like the accelerometer gyroscope and temperature data of MPU6050. For me MPU6050 is soldered with Pico and Pico is connected to my laptop via a USB connection.

Now, my problem is the frequency is quite low like 100 samples/second. I am using a serial library of python for this. And on Pico's side, I have used UART. I should get at least 1khz frequency as per the MPU6050 datasheet. But, I am seriously doing something wrong here.
I am quite new and don’t have much clue how to increase the frequency in this case. Any help on this will be really helpful for me. Thanks in advance.

I am using baudrate 115200. I did some trial and error and find out that there is no problem between Pico and Python with pyserial. It’s like Pico is not able to read data from MPU6050 that fast because I am getting a lot of empty bytes with the use of serial.in_waiting(). I am uploading my code here. Just a bit of overview, my main.py uses two external modules imu.py and vector3d.py to read data. I am getting only 100 samples/second but It is a lot less. According to the MPU6050 datasheet, I should get at least 1khz frequency.

#PICO Code(main.py)
from imu import MPU6050
import utime
import time
from machine import Pin, I2C, UART

i2c = I2C(0, sda=Pin(4), scl=Pin(5), freq=400000)
imu = MPU6050(i2c)

uart = UART(0, baudrate=115200)
print("UART Info : ", uart)

while True:
    ax = round(imu.accel.x, 2)
    ay = round(imu.accel.y, 2)
    az = round(imu.accel.z, 2)
    gx = round(imu.gyro.x)
    gy = round(imu.gyro.y)
    gz = round(imu.gyro.z)
    tem = round(imu.temperature, 2)
    print(ax, ay, az, gx, gy, gz, tem)

#Python side code
import serial
import time
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

ser = serial.Serial('COM4', 115200)
print(ser)

file = open("serial_sample.csv", "w")
start_time = time.time()
curr_time = time.time()
output_list = []
header_string = "X_accel" + "," + "Y_accel" + "," + "Z_accel" + "," + "X_Pos" + "," + "Y_Pos" + "," + "Z_Pos" \
     + "," + "Temperature" + "\n"

output_list.append(header_string)
while curr_time - start_time < 10:
    data = ser.readline()
    data = str(data).split("\\")[0].split(" ")
    output = data[0].split("'")[1] + "," + data[1] + "," + data[2] + "," + data[3] + "," + data[4] + ","
                  +\ data[5] + "," + data[6] + "\n"
    output_list.append(output)
    curr_time = time.time()

file.writelines(output_list)
file.close()


问:
Android webview link outside of a specific folder by clicking to open it in your default browser
The pages for my webview are inserted in the apk folder in "http://www.moje_domena.cz/apk/apk_index.html" as url relative links. It's alright. I want to make links outside the "apk" folder open in the default browser viz."http://www.moje_domena.cz/index.html" open in the defaut browser.

MainActivity.java

```<code>package mainapk.online.app;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.example.app.R;

public class MainActivity extends Activity {

    private WebView mWebView;

    @Override
    @SuppressLint("SetJavaScriptEnabled")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mWebView = findViewById(R.id.activity_main_webview);
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        mWebView.setWebViewClient(new MyWebViewClient());

        // MAIN URL

        mWebView.loadUrl("http://www.moje_domena.cz/apk");

    }

    @Override
    public void onBackPressed() {
        if(mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }
}

</code>```

MyWebViewClient.java

```<code>package mainapk.online.app;

import android.content.Intent;
import android.net.Uri;
import android.webkit.WebView;
import android.webkit.WebViewClient;

class MyWebViewClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        String hostname;

        // MAIN HOSTNAME

        hostname = "moje_domena.cz";

        Uri uri = Uri.parse(url);
        if (url.startsWith("file:") || uri.getHost() != null && uri.getHost().endsWith(hostname)) {
            return false;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        view.getContext().startActivity(intent);
        return true;
    }
}
</code>```

This solution opens all links inside http://www.moje_domena.cz in webview. Not just the links outside the "apk" folder. thanks for the ideas

Body:
The pages for my webview are inserted in the apk folder in "http://www.moje_domena.cz/apk/apk_index.html" as url relative links. It's alright. I want to make links outside the "apk" folder open in the default browser viz."http://www.moje_domena.cz/index.html" open in the defaut browser.

MainActivity.java

package mainapk.online.app;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.example.app.R;

public class MainActivity extends Activity {

    private WebView mWebView;

    @Override
    @SuppressLint("SetJavaScriptEnabled")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mWebView = findViewById(R.id.activity_main_webview);
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        mWebView.setWebViewClient(new MyWebViewClient());

        // MAIN URL

        mWebView.loadUrl("http://www.moje_domena.cz/apk");

    }

    @Override
    public void onBackPressed() {
        if(mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }
}

MyWebViewClient.java

package mainapk.online.app;

import android.content.Intent;
import android.net.Uri;
import android.webkit.WebView;
import android.webkit.WebViewClient;

class MyWebViewClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        String hostname;

        // MAIN HOSTNAME

        hostname = "moje_domena.cz";

        Uri uri = Uri.parse(url);
        if (url.startsWith("file:") || uri.getHost() != null && uri.getHost().endsWith(hostname)) {
            return false;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        view.getContext().startActivity(intent);
        return true;
    }
}

This solution opens all links inside http://www.moje_domena.cz in webview. Not just the links outside the "apk" folder. thanks for the ideas


问:
how to listen for POST request with Twilio
I have a monitoring system that is able to send POST request if an event trigger an alarm,

I would like to send that POST request to Twilio so that Twilio can send an SMS to multiple phone numbers.

I am not sure where to start and I am not even sure if twilio can listen for http POST request,

I think that I should use TwiML Bins but I am not sure where to start.

Does anybody have any pointer for me ?

Thank you


问:
how to execute bash script with options in Robot Framework
I want to execute some kind of bash script in Robot Framework.
In terminal I use that command:

```<code>bash /home/Documents//script.sh --username=root --password=hello --host=100.100.100.100 --port=400 - --data='{"requestId":1,"parameters":{"name":"check","parameters":{"id":"myID"}}}'
</code>```

and it works

In robot script I try with:

```<code>Running script
${result} = Run Process bash    /home/Documents//script.sh  "username\=root"  "password\=hello"  "host\=100.100.100.100"  "port\=400"  "data\='{"requestId":1,"parameters":{"name":"check","parameters":{"id":"myID"}}}'"   shell=True  stdout=stdout.txt
Log To Console  ${result}
Log    ${result}
Log ${result.stdout}
Log ${result.stderr}
</code>```

But I get Missing required arguments: username, password, host, port.

Process doesn't recognise arguments.

How to pass script arguments in Robot Framework with Process Library?

Please show examples, I checked already doc in Process Library for Specifying command and arguments but I don't understand it.

After the night I found solution:

```<code>Running script
${result} = Run Process bash    /home/Documents//script.sh  username\=root password\=hello  host\=100.100.100.100  port\=400  data\='{"requestId":1,"parameters":{"name":"check","parameters":{"id":"myID"}}}'  shell=True  stdout=stdout.txt
</code>```

Options should be unquoted but = should be escaped with \

Body:
I want to execute some kind of bash script in Robot Framework.
In terminal I use that command:

bash /home/Documents//script.sh --username=root --password=hello --host=100.100.100.100 --port=400 - --data='{"requestId":1,"parameters":{"name":"check","parameters":{"id":"myID"}}}'

and it works

In robot script I try with:

Running script
${result} = Run Process bash    /home/Documents//script.sh  "username\=root"  "password\=hello"  "host\=100.100.100.100"  "port\=400"  "data\='{"requestId":1,"parameters":{"name":"check","parameters":{"id":"myID"}}}'"   shell=True  stdout=stdout.txt
Log To Console  ${result}
Log    ${result}
Log ${result.stdout}
Log ${result.stderr}

But I get Missing required arguments: username, password, host, port.

Process doesn't recognise arguments.

How to pass script arguments in Robot Framework with Process Library?

Please show examples, I checked already doc in Process Library for Specifying command and arguments but I don't understand it.

After the night I found solution:

Running script
${result} = Run Process bash    /home/Documents//script.sh  username\=root password\=hello  host\=100.100.100.100  port\=400  data\='{"requestId":1,"parameters":{"name":"check","parameters":{"id":"myID"}}}'  shell=True  stdout=stdout.txt

Options should be unquoted but = should be escaped with \


问:
Objects missing when packaging Cython module with submodules
I'm attempting to build a Python C extension using Cython. The problem is that when I structure the project in submodules, the defined objects in Cython are no longer available.

This is a simple project that I created to reproduce the issue I'm having:

```<code>├── foo
│   ├── bar
│   │   ├── bar.pyx
│   │   ├── cbar.pxd
│   │   ├── __init__.py
│   ├── __init__.py
├── setup.py
└── src
    ├── bar.c
    └── bar.h
</code>```

And this is the setup.py:

from setuptools import Extension, setup
from Cython.Build import cythonize

ext_modules = [
  Extension("foo.bar", ["foo/bar/bar.pyx"]),
]

setup(
  ext_modules=cythonize(ext_modules, language_level=3),
  packages=["foo", "foo.bar"]
)
```
<p>The pyx file is quite simple</p>
<pre class="lang-py prettyprint-override"><code># distutils: sources = src/bar.c
# distutils: include_dirs = src/

cimport foo.bar.cbar as s

cdef class Foobar:
  cdef int number

  def __cinit__(self):
    self.number = 357

  def double(self):
    return s.double_int(self.number)
</code>```

But when installing with

```<code>python setup.py build_ext --inplace
</code>```

and running a shell to import and try it:

```<code>>>> import foo
>>> dir(foo)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'bar', 'foo']
>>> dir(foo.bar)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__']
>>>
</code>```

There's no Foobar class available in foo.bar. Also, I don't really know why "foo" is a submodule of itself. Would appreciate any help! Thanks!

Body:
I'm attempting to build a Python C extension using Cython. The problem is that when I structure the project in submodules, the defined objects in Cython are no longer available.

This is a simple project that I created to reproduce the issue I'm having:

├── foo
│   ├── bar
│   │   ├── bar.pyx
│   │   ├── cbar.pxd
│   │   ├── __init__.py
│   ├── __init__.py
├── setup.py
└── src
    ├── bar.c
    └── bar.h

And this is the setup.py:

from setuptools import Extension, setup
from Cython.Build import cythonize

ext_modules = [
  Extension("foo.bar", ["foo/bar/bar.pyx"]),
]

setup(
  ext_modules=cythonize(ext_modules, language_level=3),
  packages=["foo", "foo.bar"]
)

The pyx file is quite simple

# distutils: sources = src/bar.c
# distutils: include_dirs = src/

cimport foo.bar.cbar as s

cdef class Foobar:
  cdef int number

  def __cinit__(self):
    self.number = 357

  def double(self):
    return s.double_int(self.number)

But when installing with

python setup.py build_ext --inplace

and running a shell to import and try it:

>>> import foo
>>> dir(foo)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'bar', 'foo']
>>> dir(foo.bar)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__']
>>>

There's no Foobar class available in foo.bar. Also, I don't really know why "foo" is a submodule of itself. Would appreciate any help! Thanks!


问:
Search box with showing results as it's find
I am working on the social media web application, in that I am building a search box just like Instagram, with 4 result, but I have been trying to achieve the algorithm that shows the result of searching as soon as its found in database, like If I have given the limit of 4 so if I send my request to search name in database and request immediately finds 2 or 3 results so I just want it to display result and meanwhile request will keep on searching until it doesn't find 2 or 1 more to complete the limt of 4, but if there are only two or three results so request will Finish after giving result

In short I want to make search box doing functionality completely same as Instagram search box does


问:
How can I constrain an image to crop the height with a fix width with CSS?
My HTML is:

```<code><div class="event-presentation-featured">
  <div class="event-presentation-featued__image-container">
    <a href="...">
      <img class="event-presentation-featued__image" src="...">
    </a>
  </div>
  <div class="event-presentation-featured__content">
    ...
  </div>
  <div class="event-presentation-featured__actions">
    ...
  </div>
</div>
</code>```

I want the image to NOT expand the height of the containing div. Presently it looks like:

The relevant classes are:

```<code>.event-presentation-featured {
    align-items: stretch;
    background-color: var(--color-white);
    display: flex;
    width: 100%;
}

.event-presentation-featued__image-container {
    flex-shrink: 1;
    max-width: 457px;
    position: relative;
}

.event-presentation-featued__image {
    top: 0;
    left: 0;
    display: block;
    object-fit: cover;
    object-position: center;
    width: 100%;
    height: 100%;
}
</code>```

Body:
My HTML is:

    ...

    ...

I want the image to NOT expand the height of the containing div. Presently it looks like:

The relevant classes are:

.event-presentation-featured {
    align-items: stretch;
    background-color: var(--color-white);
    display: flex;
    width: 100%;
}

.event-presentation-featued__image-container {
    flex-shrink: 1;
    max-width: 457px;
    position: relative;
}

.event-presentation-featued__image {
    top: 0;
    left: 0;
    display: block;
    object-fit: cover;
    object-position: center;
    width: 100%;
    height: 100%;
}


问:
VxD: Determine the size of file segments for code and data and their location
I have a sample VxD code here that just shows a message box whenever a DOS prompt is opened or closed under Windows 98.

What I need to know is which fields determine the code segment or page, the data segment, and their size in bytes or pages.
It is actually an old Linear Executable EXE that for VxDs is supposedly always has a signature of "LE".

So far I know that:

MemPagesCtr tells how many blocks there are of MemPageSZ bytes, that I can make 512 bytes in size and still be sane until now.

LastPageBytes says how many bytes the very last portion of the VxD file has, which can be less or probably equal than MemPageSZ.

Which header fields indicate which of the pages is the code, data, or are they always in the same sequence for VxD LE EXE? And how to know where the actual code entry and data start?

```;http://master.dl.sourceforge.net/project/api-simple-completa/api.7z?viasf=1

%include "../../../PC/BIOS/WinAPI/EXE/PE/snippets/DOS_Stubs/NASM/DOS_Stub_classic0xB0.asm"

PE_header:
LE_header:
LE_header_start:

  LE_header_0x00_Signature            db 'LE'
  LE_header_0x02_ByteOrder            db 0 ;0 Little or Big Endian
  LE_header_0x03_WordOrder            db 0 ;0 Little or Big Endian
  LE_header_0x04_FormatLevel          dd 0
  LE_header_0x08_CPUType              dw 2 ;1 286+, 2 386+, 3 486+, 4 586+, 20h i860 N10+, 21h N11+, 40h MIPS Mark I+ (R2000, R3000), 41h MIPS Mark II+ (R6000), 42h MIPS Mark III+ (R4000)
  LE_header_0x0A_TargetOS             dw 4 ;1 OS/2, 2 Win16, 3 DOS 4x, 4 Win386
  LE_header_0x0C_ModuleVersion        dd 0
  LE_header_0x10_Flags                dd 101000000000000000b ;
  LE_header_0x14_MemPagesCtr          dd 3
  LE_header_0x18_InitialCS            dd 0
  LE_header_0x1C_InitialEIP           dd 0  ;Explicar cómo encuentra y carga las secciones y direcciones de código y datos el VxD
  LE_header_0x20_InitialSS            dd 0
  LE_header_0x24_InitialESP           dd 0
  LE_header_0x28_MemPageSZ            dd 512   ;Tamaño de datos
  LE_header_0x2C_LastPageBytes        dd 0x31
  LE_header_0x30_FixUpSectionSZ       dd 0x85
  LE_header_0x34_FixUpSectionCheck    dd 0
  LE_header_0x38_LdrSectionSZ         dd 0x69
  LE_header_0x3C_LdrSectionCheck      dd 0
  LE_header_0x40_ObjectTableOffset    dd 0xC4  ;from where?
  LE_header_0x44_ObjectTableEntries   dd 3
  LE_header_0x48_ObjectPageMapOffset  dd 0x10C
  LE_header_0x4C_ObjectIterDataMapOff dd 0  ;always 0 for VxD?
  LE_header_0x50_RsrcTableOffset      dd 0
  LE_header_0x54_RsrcTableEntries     dd 0
  LE_header_0x58_ResidentTableOffset  dd 0x118
  LE_header_0x5C_EntryTableOffset     dd 0x123
  LE_header_0x60_ModulDirectivesTable dd 0  ;always 0 for VxD?
  LE_header_0x64_ModulDirectivesEnts  dd 0
  LE_header_0x68_FixupPageTblOffset   dd 0x12D
  LE_header_0x6C_FixupRecordTable     dd 0x13D
  LE_header_0x70_ImportModulesTable   dd 0x1B2
  LE_header_0x74_ImportModulesCount   dd 0
  LE_header_0x78_ImportProcTable      dd 0x1B2
  LE_header_0x7C_PerPageChecksums     dd 0
  LE_header_0x80_DataPagesOffset      dd 0x400   ;0x1000; 0x400;0x2E0;0x1000  ;inicio de código y datos después de la cabecera
  LE_header_0x84_PreloadPageCount     dd 1
  LE_header_0x88_NonResidentNames     dd 0x1434
  LE_header_0x8c_NonResidentNamesLen8 dd 15  ;in bytes
  LE_header_0x90_NonResidentNamesChk  dd 0
  LE_header_0x94_AutomaticDataObject  dd 0
  LE_header_0x98_DebugInformationOff  dd 0
  LE_header_0x9C_DebugInformationLen  dd 0
  LE_header_0xA0_PreloadInstPagesNum  dd 0
  LE_header_0xA4_DemandInstancePgsNum dd 0
  LE_header_0xA8_ExtraHeapAllocation  dd 0
  LE_header_0xAC                      dd 0

;File Offset 0x160, LE header offset 0xB0

;INIT:
;INIT:
;INIT:
;INIT:

times 16 db 0

dd 0x4000000
dd 0xE8
dd 0
dd 0x2045

dd 1
dd 1
db "LCOD'",0,0,0

dd 0
dd 0x2005
dd 2
dd 1
db "PCOD1",0,0,0
dd 0
dd 0x2023

dd 3
dd 1
db "PDAT"
dd 0x10000

db 0,0,2,0
db 0,0,3,0
db 7
db "MESSAGE"

db 0,0,0,1,3,1,0,3,0,0,0,0,0,0,0,0
db 0,0x60,0,0,0,0x75,0,0,0,0x75,0,0,0,7,0,0xE1
db 0,2,0x20,0,0x27,0,0x1F,1,0x5F,0,0x65,0,0x69,0,0x6D,0
db 0x71,0,0x75,0,0x79,0,0x7D,0,0x81,0,0x85,0,0x89,0,0x8D,0
db 0x91,0,0x95,0,0x99,0,0x9D,0,0xA1,0,0xA5,0,0xA9,0,0xAD,0
db 0xB1,0,0xB5,0,0xB9,0,0xBD,0,0xC1,0,0xC5,0,0xC9,0,0xCD,0
db 0xD1,0,0xD5,0,0xD9,0,0xDD,0,7,0,0x61,0,2,0,0,7
db 0,0x5B,0,1,0x61,0,7,0,0x18,0,1,0x50,0,7,0,0x21
db 0,3,0x1F,0,7,0,0x11,0,3,0,0,7,0,1,0,3
db 15,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
db 0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0
db 0,0,0,0,0,0,0,0,0,0,0,0,32,32,32,32

db "MESSAGE_DDB",0,32,0X40,0X31,0
db 32,32,32,"CLASS",0,"'RCODE",0
db 0,0,32,32,32,"PRELOAD DISCARDABLE",0,0
db "CONFORMING",0,0,0,0,0,0,0,0,0,0,0,0

;times 0xD20 db 0

;align 0x1000
align 0x400

;END:
;END:
;END:
;END:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;0x1000 en el archivo tiene .00000000
;de base en HIEW, por qué?
;;

;INIT: Page 0
;INIT: Page 0
;INIT: Page 0
;INIT: Page 0

db 0,0,0,0,0,4,0,0,1,0,0,0,"MESSAGE"
db 32,0,0,0,0x80,0,0,0,0,0,0,0,0
times 16 db 0
dd 0,0,0
db "verPP",0,0,0
db "1vsR2vsR3vsR",0x83,0xE8,7,0x83,0xF8,0x21,0x73,7,-1,0x24,0x85,0,0,0,0,0xF8
db 0xC3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

times 16*7 db 0

db 0,0,0,0,0,0xCC,0xCC,0xCC,0,0,0,0,0,0,0,0

;times 16*17 db 0

%define round(n, r) (((n+(r-1))/r)*r)
align 512

;END:  Page 0
;END:  Page 0
;END:  Page 0
;END:  Page 0

;align 512
;_s:
;times (512-_s) db 0

;dd round(_s,512)
;times (512-$$) db 0

;INIT: Page 1
;INIT: Page 1
;INIT: Page 1
;INIT: Page 1

bits 32

mov ecx,0   ;xor ecx,ecx
;xor ecx,ecx
db 0xCD,0x20,3,0,1,0 ;VMMcall Get_Sys_VM_Handle
mov eax,0x30
mov edi,0
xor esi,esi
xor edx,edx
;db 0xCD,0x20,4,0,17,0  ;VxDcall VMCPD.Set_CR0_State  ;17 en vez de 0x17, probar valores WORD o DWORD
db 0xCD,0x20,4,0,0x17,0  ;VxDcall SHELL.Message

ret
mov ecx,0
db 0xEB,0xDE  ;jmps .5

;times 9 db 0

;times 16*29 db 0

align 512

;END:  Page 1
;END:  Page 1
;END:  Page 1
;END:  Page 1

;INIT: Page 2
;INIT: Page 2
;INIT: Page 2
;INIT: Page 2

db "VxD MessageBox",0
db "A VM is created",0
db "A VM is destroyed",0
;db "SEC",0x0B
;db "MESSAGE_DDB",0,0,0

;END:  Page 2
;END:  Page 2
;END:  Page 2
;END:  Page 2
```

Body:
I have a sample VxD code here that just shows a message box whenever a DOS prompt is opened or closed under Windows 98.

What I need to know is which fields determine the code segment or page, the data segment, and their size in bytes or pages.
It is actually an old Linear Executable EXE that for VxDs is supposedly always has a signature of "LE".

So far I know that:

MemPagesCtr tells how many blocks there are of MemPageSZ bytes, that I can make 512 bytes in size and still be sane until now.

LastPageBytes says how many bytes the very last portion of the VxD file has, which can be less or probably equal than MemPageSZ.

Which header fields indicate which of the pages is the code, data, or are they always in the same sequence for VxD LE EXE? And how to know where the actual code entry and data start?

;http://master.dl.sourceforge.net/project/api-simple-completa/api.7z?viasf=1

%include "../../../PC/BIOS/WinAPI/EXE/PE/snippets/DOS_Stubs/NASM/DOS_Stub_classic0xB0.asm"

PE_header:
LE_header:
LE_header_start:

  LE_header_0x00_Signature            db 'LE'
  LE_header_0x02_ByteOrder            db 0 ;0 Little or Big Endian
  LE_header_0x03_WordOrder            db 0 ;0 Little or Big Endian
  LE_header_0x04_FormatLevel          dd 0
  LE_header_0x08_CPUType              dw 2 ;1 286+, 2 386+, 3 486+, 4 586+, 20h i860 N10+, 21h N11+, 40h MIPS Mark I+ (R2000, R3000), 41h MIPS Mark II+ (R6000), 42h MIPS Mark III+ (R4000)
  LE_header_0x0A_TargetOS             dw 4 ;1 OS/2, 2 Win16, 3 DOS 4x, 4 Win386
  LE_header_0x0C_ModuleVersion        dd 0
  LE_header_0x10_Flags                dd 101000000000000000b ;
  LE_header_0x14_MemPagesCtr          dd 3
  LE_header_0x18_InitialCS            dd 0
  LE_header_0x1C_InitialEIP           dd 0  ;Explicar cómo encuentra y carga las secciones y direcciones de código y datos el VxD
  LE_header_0x20_InitialSS            dd 0
  LE_header_0x24_InitialESP           dd 0
  LE_header_0x28_MemPageSZ            dd 512   ;Tamaño de datos
  LE_header_0x2C_LastPageBytes        dd 0x31
  LE_header_0x30_FixUpSectionSZ       dd 0x85
  LE_header_0x34_FixUpSectionCheck    dd 0
  LE_header_0x38_LdrSectionSZ         dd 0x69
  LE_header_0x3C_LdrSectionCheck      dd 0
  LE_header_0x40_ObjectTableOffset    dd 0xC4  ;from where?
  LE_header_0x44_ObjectTableEntries   dd 3
  LE_header_0x48_ObjectPageMapOffset  dd 0x10C
  LE_header_0x4C_ObjectIterDataMapOff dd 0  ;always 0 for VxD?
  LE_header_0x50_RsrcTableOffset      dd 0
  LE_header_0x54_RsrcTableEntries     dd 0
  LE_header_0x58_ResidentTableOffset  dd 0x118
  LE_header_0x5C_EntryTableOffset     dd 0x123
  LE_header_0x60_ModulDirectivesTable dd 0  ;always 0 for VxD?
  LE_header_0x64_ModulDirectivesEnts  dd 0
  LE_header_0x68_FixupPageTblOffset   dd 0x12D
  LE_header_0x6C_FixupRecordTable     dd 0x13D
  LE_header_0x70_ImportModulesTable   dd 0x1B2
  LE_header_0x74_ImportModulesCount   dd 0
  LE_header_0x78_ImportProcTable      dd 0x1B2
  LE_header_0x7C_PerPageChecksums     dd 0
  LE_header_0x80_DataPagesOffset      dd 0x400   ;0x1000; 0x400;0x2E0;0x1000  ;inicio de código y datos después de la cabecera
  LE_header_0x84_PreloadPageCount     dd 1
  LE_header_0x88_NonResidentNames     dd 0x1434
  LE_header_0x8c_NonResidentNamesLen8 dd 15  ;in bytes
  LE_header_0x90_NonResidentNamesChk  dd 0
  LE_header_0x94_AutomaticDataObject  dd 0
  LE_header_0x98_DebugInformationOff  dd 0
  LE_header_0x9C_DebugInformationLen  dd 0
  LE_header_0xA0_PreloadInstPagesNum  dd 0
  LE_header_0xA4_DemandInstancePgsNum dd 0
  LE_header_0xA8_ExtraHeapAllocation  dd 0
  LE_header_0xAC                      dd 0

;File Offset 0x160, LE header offset 0xB0

;INIT:
;INIT:
;INIT:
;INIT:

times 16 db 0

dd 0x4000000
dd 0xE8
dd 0
dd 0x2045

dd 1
dd 1
db "LCOD'",0,0,0

dd 0
dd 0x2005
dd 2
dd 1
db "PCOD1",0,0,0
dd 0
dd 0x2023

dd 3
dd 1
db "PDAT"
dd 0x10000

db 0,0,2,0
db 0,0,3,0
db 7
db "MESSAGE"

db 0,0,0,1,3,1,0,3,0,0,0,0,0,0,0,0
db 0,0x60,0,0,0,0x75,0,0,0,0x75,0,0,0,7,0,0xE1
db 0,2,0x20,0,0x27,0,0x1F,1,0x5F,0,0x65,0,0x69,0,0x6D,0
db 0x71,0,0x75,0,0x79,0,0x7D,0,0x81,0,0x85,0,0x89,0,0x8D,0
db 0x91,0,0x95,0,0x99,0,0x9D,0,0xA1,0,0xA5,0,0xA9,0,0xAD,0
db 0xB1,0,0xB5,0,0xB9,0,0xBD,0,0xC1,0,0xC5,0,0xC9,0,0xCD,0
db 0xD1,0,0xD5,0,0xD9,0,0xDD,0,7,0,0x61,0,2,0,0,7
db 0,0x5B,0,1,0x61,0,7,0,0x18,0,1,0x50,0,7,0,0x21
db 0,3,0x1F,0,7,0,0x11,0,3,0,0,7,0,1,0,3
db 15,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
db 0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0
db 0,0,0,0,0,0,0,0,0,0,0,0,32,32,32,32

db "MESSAGE_DDB",0,32,0X40,0X31,0
db 32,32,32,"CLASS",0,"'RCODE",0
db 0,0,32,32,32,"PRELOAD DISCARDABLE",0,0
db "CONFORMING",0,0,0,0,0,0,0,0,0,0,0,0

;times 0xD20 db 0

;align 0x1000
align 0x400

;END:
;END:
;END:
;END:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;0x1000 en el archivo tiene .00000000
;de base en HIEW, por qué?
;;

;INIT: Page 0
;INIT: Page 0
;INIT: Page 0
;INIT: Page 0

db 0,0,0,0,0,4,0,0,1,0,0,0,"MESSAGE"
db 32,0,0,0,0x80,0,0,0,0,0,0,0,0
times 16 db 0
dd 0,0,0
db "verPP",0,0,0
db "1vsR2vsR3vsR",0x83,0xE8,7,0x83,0xF8,0x21,0x73,7,-1,0x24,0x85,0,0,0,0,0xF8
db 0xC3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

times 16*7 db 0

db 0,0,0,0,0,0xCC,0xCC,0xCC,0,0,0,0,0,0,0,0

;times 16*17 db 0

%define round(n, r) (((n+(r-1))/r)*r)
align 512

;END:  Page 0
;END:  Page 0
;END:  Page 0
;END:  Page 0

;align 512
;_s:
;times (512-_s) db 0

;dd round(_s,512)
;times (512-$$) db 0

;INIT: Page 1
;INIT: Page 1
;INIT: Page 1
;INIT: Page 1

bits 32

mov ecx,0   ;xor ecx,ecx
;xor ecx,ecx
db 0xCD,0x20,3,0,1,0 ;VMMcall Get_Sys_VM_Handle
mov eax,0x30
mov edi,0
xor esi,esi
xor edx,edx
;db 0xCD,0x20,4,0,17,0  ;VxDcall VMCPD.Set_CR0_State  ;17 en vez de 0x17, probar valores WORD o DWORD
db 0xCD,0x20,4,0,0x17,0  ;VxDcall SHELL.Message

ret
mov ecx,0
db 0xEB,0xDE  ;jmps .5

;times 9 db 0

;times 16*29 db 0

align 512

;END:  Page 1
;END:  Page 1
;END:  Page 1
;END:  Page 1

;INIT: Page 2
;INIT: Page 2
;INIT: Page 2
;INIT: Page 2

db "VxD MessageBox",0
db "A VM is created",0
db "A VM is destroyed",0
;db "SEC",0x0B
;db "MESSAGE_DDB",0,0,0

;END:  Page 2
;END:  Page 2
;END:  Page 2
;END:  Page 2


问:
can you change the stacking order of a window using its id?
I'm trying to make a procedure that updates the stacking order of randomly created windows based on their y value (so that things that are closer to the top of the screen display under things that are lower down).
Basically I have a button that creates a window by calling a class statement. Each time a window is created, its id and y value get put in an array, which would get sorted and looped through to update the stacking order.

I figured having the id of each window that is created would be enough to change the variables of specific windows, using the id of the window.lift(), but it looks like you can't point to an object with its id like that. If I'm not mistaken I can't just use the class name because I don't want to change the whole class, just the specific window.
Anybody know what I can use instead of the id to get this to work? Is it just impossible the way I have it planned?
Here's my code in case it's helpful, unfinished because obviously it doesn't work:

```<code>import tkinter as tk
import random

# creates a new window
def makewndw(event):
    a = testwindow()

# create main window - click to create a new window
mainwindow = tk.Tk()
mainwindow.bind('<Button-1>', makewndw)

# this sorts the windows
class stacker():
    stackerwindow = tk.Toplevel()
    yarray = [{'ident': 0, 'ypos': 0}]

    def arupdate(self):
        #sort array by ypos
        self.yarray.sort(key=lambda x: x.get('ypos'))
        # print(self.yarray)
        # get length of array
        arlen = len(self.yarray)
        # loop through array between pos 1 and end
        for x in range(1,arlen):
            # extract dictionary from that position
            tempex = self.yarray[x]
            # populate temp list with values from tempex
            templist = []
            for i in tempex.values():
                templist.append(i)
            # get just the id
            tempid = templist[0]
            # use id to update stacking order
            tempid.lift()
            # ^^^ this is where i'm suck because clearly this isn't working

        self.stackerwindow.after(10, self.arupdate)

class testwindow():
    def __init__(self):
        # create a window
        self.window = tk.Toplevel()
        self.y = random.randrange(100, 500)
        self.window.geometry('200x200+800+{y}'.format(y=str(self.y)))

        # give info to sorter
        self.infdict = {'ident': id(self.window), 'ypos': self.y}
        stacker.yarray.append(self.infdict)

st = stacker()
st.arupdate()
mainwindow.mainloop()
</code>```

I'm a beginner so I'm sorry if the answer here is obvious, and sorry about how messy I'm sure my code is.

Body:
I'm trying to make a procedure that updates the stacking order of randomly created windows based on their y value (so that things that are closer to the top of the screen display under things that are lower down).
Basically I have a button that creates a window by calling a class statement. Each time a window is created, its id and y value get put in an array, which would get sorted and looped through to update the stacking order.

I figured having the id of each window that is created would be enough to change the variables of specific windows, using the id of the window.lift(), but it looks like you can't point to an object with its id like that. If I'm not mistaken I can't just use the class name because I don't want to change the whole class, just the specific window.
Anybody know what I can use instead of the id to get this to work? Is it just impossible the way I have it planned?
Here's my code in case it's helpful, unfinished because obviously it doesn't work:

import tkinter as tk
import random

# creates a new window
def makewndw(event):
    a = testwindow()

# create main window - click to create a new window
mainwindow = tk.Tk()
mainwindow.bind('<Button-1>', makewndw)

# this sorts the windows
class stacker():
    stackerwindow = tk.Toplevel()
    yarray = [{'ident': 0, 'ypos': 0}]

    def arupdate(self):
        #sort array by ypos
        self.yarray.sort(key=lambda x: x.get('ypos'))
        # print(self.yarray)
        # get length of array
        arlen = len(self.yarray)
        # loop through array between pos 1 and end
        for x in range(1,arlen):
            # extract dictionary from that position
            tempex = self.yarray[x]
            # populate temp list with values from tempex
            templist = []
            for i in tempex.values():
                templist.append(i)
            # get just the id
            tempid = templist[0]
            # use id to update stacking order
            tempid.lift()
            # ^^^ this is where i'm suck because clearly this isn't working

        self.stackerwindow.after(10, self.arupdate)

class testwindow():
    def __init__(self):
        # create a window
        self.window = tk.Toplevel()
        self.y = random.randrange(100, 500)
        self.window.geometry('200x200+800+{y}'.format(y=str(self.y)))

        # give info to sorter
        self.infdict = {'ident': id(self.window), 'ypos': self.y}
        stacker.yarray.append(self.infdict)

st = stacker()
st.arupdate()
mainwindow.mainloop()

I'm a beginner so I'm sorry if the answer here is obvious, and sorry about how messy I'm sure my code is.


问:
React-Chartjs-2: How do I add gradients in the doughnut chart?
I want to create this:

Aspiration

So far, I have managed to create this:

crap

I want to move the color label descriptions that are appearing above the chart to the left side.

Here's my code:

```<code>const data = {
    datasets: [
      {
        data: [20, 30, 50],
        backgroundColor: ["#EB6262", "#39BDE7", "#0B8878"],
        borderWidth: 8,
        borderColor: theme.palette.white,
        hoverBorderColor: theme.palette.white,
      },
    ],
    labels: ["Pending", "In Process", "Completed"],
  };

</code>```
```<code><Doughnut data={data} />
</code>```

Body:
I want to create this:

Aspiration

So far, I have managed to create this:

crap

I want to move the color label descriptions that are appearing above the chart to the left side.

Here's my code:

const data = {
    datasets: [
      {
        data: [20, 30, 50],
        backgroundColor: ["#EB6262", "#39BDE7", "#0B8878"],
        borderWidth: 8,
        borderColor: theme.palette.white,
        hoverBorderColor: theme.palette.white,
      },
    ],
    labels: ["Pending", "In Process", "Completed"],
  };

<Doughnut data={data} />


问:
oAuth2 with Google Authentication on Swagger C#
i am using swagger to authenticate the user via google authentication. My goal is that when I press the authorize button and enter the ClientID . It redirected me to the google login page and after a successful login I went back to swagger. however, in my case, when I enter the ClientID, it redirects me to the google login page, but it does not work for me to return to the swagger and it does not show me the logout button in this swagger. (I don't use identity server or maybe I should?)

Program

```<code>builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = builder.Configuration["Jwt:Issuer"],
        ValidAudience = builder.Configuration["Jwt:Audience"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
    };
})
    .AddGoogle(googleOptions =>
{

    googleOptions.ClientId = builder.Configuration["Google:ClientId"];
    googleOptions.ClientSecret = builder.Configuration["Google:ClientSecret"];

});

builder.Services.AddSwaggerGen(c =>
{

    c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
    {
        Title = "Google Auth",
        Version = "v1"
    });
    c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
    {
        Description = "ouath",
        Name = "oauth2.0",
        Type = SecuritySchemeType.OAuth2,
        Flows = new OpenApiOAuthFlows
        {
           Implicit =  new OpenApiOAuthFlow
            {

               AuthorizationUrl = new Uri($"https://accounts.google.com/o/oauth2/v2/auth"),
                TokenUrl = new Uri($"https://oauth2.googleapis.com/token"),

                Scopes = new Dictionary<string, string>
                    {
                        {
                            $"https://www.googleapis.com/auth/cloud-platform.read-only",
                            "User"
                        }

                    }
            }
        }

    });

    c.AddSecurityRequirement(new OpenApiSecurityRequirement{
                    {
                        new OpenApiSecurityScheme{
                            Reference = new OpenApiReference { Id = "oauth2",
                                Type = ReferenceType.SecurityScheme},
                            Scheme="oauth2",
                            Name = "authorization",

                        },new List<string>()
                    }
                });

});

builder.Services.AddAuthorization();
app.UseAuthentication();
app.UseAuthorization();

app.UseSwaggerUI(options =>
{
    options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
    options.RoutePrefix = string.Empty;
    options.OAuth2RedirectUrl("https://localhost:7189/Auth/LoginSuccess"); // i must used that       //because i got redirect_error but i dont wan't to redirect me to the page
    options.OAuthUsePkce();
    options.OAuthUseBasicAuthenticationWithAccessCodeGrant();
});

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

Body:
i am using swagger to authenticate the user via google authentication. My goal is that when I press the authorize button and enter the ClientID . It redirected me to the google login page and after a successful login I went back to swagger. however, in my case, when I enter the ClientID, it redirects me to the google login page, but it does not work for me to return to the swagger and it does not show me the logout button in this swagger. (I don't use identity server or maybe I should?)

Program

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = builder.Configuration["Jwt:Issuer"],
        ValidAudience = builder.Configuration["Jwt:Audience"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
    };
})
    .AddGoogle(googleOptions =>
{

    googleOptions.ClientId = builder.Configuration["Google:ClientId"];
    googleOptions.ClientSecret = builder.Configuration["Google:ClientSecret"];

});

builder.Services.AddSwaggerGen(c =>
{

    c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
    {
        Title = "Google Auth",
        Version = "v1"
    });
    c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
    {
        Description = "ouath",
        Name = "oauth2.0",
        Type = SecuritySchemeType.OAuth2,
        Flows = new OpenApiOAuthFlows
        {
           Implicit =  new OpenApiOAuthFlow
            {

               AuthorizationUrl = new Uri($"https://accounts.google.com/o/oauth2/v2/auth"),
                TokenUrl = new Uri($"https://oauth2.googleapis.com/token"),

                Scopes = new Dictionary<string, string>
                    {
                        {
                            $"https://www.googleapis.com/auth/cloud-platform.read-only",
                            "User"
                        }

                    }
            }
        }

    });

    c.AddSecurityRequirement(new OpenApiSecurityRequirement{
                    {
                        new OpenApiSecurityScheme{
                            Reference = new OpenApiReference { Id = "oauth2",
                                Type = ReferenceType.SecurityScheme},
                            Scheme="oauth2",
                            Name = "authorization",

                        },new List<string>()
                    }
                });

});

builder.Services.AddAuthorization();
app.UseAuthentication();
app.UseAuthorization();

app.UseSwaggerUI(options =>
{
    options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
    options.RoutePrefix = string.Empty;
    options.OAuth2RedirectUrl("https://localhost:7189/Auth/LoginSuccess"); // i must used that       //because i got redirect_error but i dont wan't to redirect me to the page
    options.OAuthUsePkce();
    options.OAuthUseBasicAuthenticationWithAccessCodeGrant();
});


问:
Kotlin/Java how to format localized time duration like "1 minute 30 seconds"?
Is there a way to format a localized time duration in Kotlin or Java? I have a Duration, and I want to display it in a localized, human readable string like "1 minute 30 seconds" or "1m 30s".

I did find RelativeDateTimeFormatter, but it only appears to generate time parts that are in the future or past tense like "1 minute ago" or "in 1 minute". Is there a way to configure it to generate the present tense?


问:
Django allauth render login fields manually user or email not displayed
I'm trying to display the login fields manually, instead of using:

```<code>{{form.as_p}}
</code>```

I'm setting allauth as follows in order to login with email:

```<code>ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False
ACCOUNT_SESSION_REMEMBER = True
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_UNIQUE_EMAIL = True
</code>```

In HTML I have the following:

```<code><form class="login" method="POST" action="{% url 'account_login' %}">
    {% csrf_token %}
    <!-- Email input -->
  <div class="form-outline mb-4">
    {{form.email}}
    <label class="form-label" for="form2Example1">Email address</label>
  </div>

  <!-- Password input -->
  <div class="form-outline mb-4">
    {{form.password}}
    <label class="form-label" for="form2Example2">Password</label>
  </div>
    {% if redirect_field_value %}
    <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
    {% endif %}
    <a class="button secondaryAction" href="{% url 'account_reset_password' %}">{% trans "Forgot Password?" %}</a>
    <button class="btn btn-lg btn-block btn-primary" type="submit">{% trans "Sign In" %}</button>
  </form>
</code>```

The email field is not being displayed, I have also tried with:

```<code>{{form.user}}
</code>```

and the field is not displayed

Body:
I'm trying to display the login fields manually, instead of using:

{{form.as_p}}

I'm setting allauth as follows in order to login with email:

ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False
ACCOUNT_SESSION_REMEMBER = True
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_UNIQUE_EMAIL = True

In HTML I have the following:

<form class="login" method="POST" action="{% url 'account_login' %}">
    {% csrf_token %}

    {{form.email}}
    Email address

    {{form.password}}
    Password

    {% if redirect_field_value %}
    <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
    {% endif %}
    {% trans "Forgot Password?" %}
    <button class="btn btn-lg btn-block btn-primary" type="submit">{% trans "Sign In" %}</button>
  </form>

The email field is not being displayed, I have also tried with:

{{form.user}}

and the field is not displayed


问:
How do I adapt my import statements to my folder structure in Django?
I just set up a basic folder structure for a new project, however I am doing it a bit different than the standard file structure, since my front-end is in React and will be in a separate git repository. The problem is, my virtual environment is installed in the "backend-django" project and when I try to access my package imports (that I installed in my virtual env) in backend/settings.py it does not recognize them.

As an example: I pip installed django-environ into my venv but when I go to settings.py (like I normally do) and import environ, I get a 'no module named environ' error.

This is my first foray into Django (clearly). For reference, I have previously only used Flask for Python projects. Any help is appreciated!

A mockup of my basic folder structure is here:
folder structure

I have already tried from backend-django import environ and from . import environ. I am still getting the same error.


问:
Utilizing 3 detached slicers with "or" logic for data filtering in Power BI
I have a dataset sampled below in which I'm trying to create a report with a custom Year-Year comparison, as detailed below:

Date
Complete

11/11/2021
Complete

1/1/2022
Not Complete

4/11/2021
Complete

9/1/2021
Not Complete

10/11/2022
Complete

3/1/2022
Not Complete

The dataset consists of many hundreds of entries per month between 2020-2022. I'm looking to create a custom year to year comparison tab where the user can select 2 years and a month to compare them between for a graph. For example, selecting 2021, selecting 2022, and selecting November betweeen the 3 slicers would  generate a graph that looks like this:

I've already created tables separate from the main dataset with just the years and months listed for the slicer selections, I'm stuck instead on the DAX logic that would be used to connect them all. Prior attempts to do so have not been successful, or have only been able to connect the slicers with "AND" logic (Data would only show up when Year 1 = Year 2). The closest I've come is a snippet I gathered from a Power BI Discussion Forum, but I'm not sure how to integrate the Month slicer into it:

```<code>OR #4 =
VAR Y1 = VALUES('Detatched Slicers'[Year 1])
VAR Y2 = VALUES('Detatched Slicers'[Year 2])
Return
    CALCULATE(
        'Dataset'[Account Complete Count],
        FILTER(
            CROSSJOIN(
                ALL( 'Detatched Slicers'[Year 2]),
                ALL('Detatched Slicers'[Year 1])
            ),
            OR (
                    'Detatched Slicers'[Year 2] IN Y2,
                    'Detatched Slicers'[Year 1] IN Y1
            )
        )
    )
</code>```

Thanks in advance!

Body:
I have a dataset sampled below in which I'm trying to create a report with a custom Year-Year comparison, as detailed below:

Date
Complete

11/11/2021
Complete

1/1/2022
Not Complete

4/11/2021
Complete

9/1/2021
Not Complete

10/11/2022
Complete

3/1/2022
Not Complete

The dataset consists of many hundreds of entries per month between 2020-2022. I'm looking to create a custom year to year comparison tab where the user can select 2 years and a month to compare them between for a graph. For example, selecting 2021, selecting 2022, and selecting November betweeen the 3 slicers would  generate a graph that looks like this:

I've already created tables separate from the main dataset with just the years and months listed for the slicer selections, I'm stuck instead on the DAX logic that would be used to connect them all. Prior attempts to do so have not been successful, or have only been able to connect the slicers with "AND" logic (Data would only show up when Year 1 = Year 2). The closest I've come is a snippet I gathered from a Power BI Discussion Forum, but I'm not sure how to integrate the Month slicer into it:

OR #4 =
VAR Y1 = VALUES('Detatched Slicers'[Year 1])
VAR Y2 = VALUES('Detatched Slicers'[Year 2])
Return
    CALCULATE(
        'Dataset'[Account Complete Count],
        FILTER(
            CROSSJOIN(
                ALL( 'Detatched Slicers'[Year 2]),
                ALL('Detatched Slicers'[Year 1])
            ),
            OR (
                    'Detatched Slicers'[Year 2] IN Y2,
                    'Detatched Slicers'[Year 1] IN Y1
            )
        )
    )

Thanks in advance!


问:
Spring auto configuration for @ControllerAdvice
I'm writting custom starter for global exception handler class annotated with @ControllerAdvice. I can't put this class into configuration class without need of abstract class, but I've seen example where you leave exception handler in it's own class and put it into spring.factories file, but I don't understand how does spring picks it up since in spring docs it is mentioned that spring.factories should contain classes annotated with @Configuration?

Example here:

```<code>@ControllerAdvice
@ConditionalOnMissingBean(annotation = [ControllerAdvice::class])
class ExceptionHandler {
  ...
}
</code>```
```<code>org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  test.configuration.controller.ExceptionHandler
</code>```

Does it actually work because of this: @ConditionalOnMissingBean(annotation = [ControllerAdvice::class]) and adding it to factories is redundant?

Body:
I'm writting custom starter for global exception handler class annotated with @ControllerAdvice. I can't put this class into configuration class without need of abstract class, but I've seen example where you leave exception handler in it's own class and put it into spring.factories file, but I don't understand how does spring picks it up since in spring docs it is mentioned that spring.factories should contain classes annotated with @Configuration?

Example here:

@ControllerAdvice
@ConditionalOnMissingBean(annotation = [ControllerAdvice::class])
class ExceptionHandler {
  ...
}

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  test.configuration.controller.ExceptionHandler

Does it actually work because of this: @ConditionalOnMissingBean(annotation = [ControllerAdvice::class]) and adding it to factories is redundant?


问:
My bash script isn't sending messages to my slack channel
I have a bash script that's supposed to send a message to a Slack channel when a GCP VM is running outside of appropriate time.

I found a script on Github that does a similar job but I modified it to fit my need but for some reason it's not sending the message needed.

My script:

```<code>#!/usr/bin/env bash

hour=$(date +%H)
script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
if [[ $hour -gt 17 || $hour -lt 9 ]] ; then
    HOST=$(hostname)
    message="${HOST} is still running. Please make sure to shut it down"
    # Read the webhook URL from the slack-hook file.
    hook=$(cat "${script_dir}/slack-hook")

    # Send a POST HTTP request to the Slack webhook.
    curl -X POST --data-urlencode "payload={\"text\": \"${message}\"}" "${hook}"
fi
</code>```

The slack-hook file contains the url for the slack webhook that receives incoming messages.

Body:
I have a bash script that's supposed to send a message to a Slack channel when a GCP VM is running outside of appropriate time.

I found a script on Github that does a similar job but I modified it to fit my need but for some reason it's not sending the message needed.

My script:

#!/usr/bin/env bash

hour=$(date +%H)
script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
if [[ $hour -gt 17 || $hour -lt 9 ]] ; then
    HOST=$(hostname)
    message="${HOST} is still running. Please make sure to shut it down"
    # Read the webhook URL from the slack-hook file.
    hook=$(cat "${script_dir}/slack-hook")

    # Send a POST HTTP request to the Slack webhook.
    curl -X POST --data-urlencode "payload={\"text\": \"${message}\"}" "${hook}"
fi

The slack-hook file contains the url for the slack webhook that receives incoming messages.


问:
Javassist ClassPool instantiation fails silently
I'm currently trying to write a Java agent for monitoring purposes. I use maven as build system.

I have a Agent.java file:

import java.lang.instrument.Instrumentation;

public class Agent {

    public static void premain(String args, Instrumentation inst) {
        System.out.println("Running premain");

        MonitorTransformer transformer = new MonitorTransformer();
        inst.addTransformer( transformer );
    }

}
```
<p>And a MonitorTransformer.java file implementing the ClassFileTransformer interface by simply overriding the <code>transform</code> method.
This is how the implementation looks like:</p>
<pre class="lang-java prettyprint-override"><code>@Override
    public byte[] transform(
        ClassLoader loader,
        String className,
        Class<?> classBeingRedefined,
        ProtectionDomain protectionDomain,
        byte[] classfileBuffer
    ) throws IllegalClassFormatException {

        System.out.println("Before ClassPool Instantiation");
        ClassPool classPool = new ClassPool();
        System.out.println("After ClassPool Instantiation");

        return classfileBuffer;
    }
</code>```

When i run the agent statically by typing the following command

```<code>java -javaagent:target/agent.jar -jar example-app.jar
</code>```

I get the following output:

```<code>Running premain
Before ClassPool Instantiation
Before ClassPool Instantiation
Before ClassPool Instantiation
Hello World!
Before ClassPool Instantiation
Before ClassPool Instantiation
Before ClassPool Instantiation
Before ClassPool Instantiation
</code>```

It seems the print statement after the ClassPool object is instantiatet is not executed.
** Example class is just printing "Hello World" onto the console

I have tried other examples provided in the internet, with the same result. Wrapping it into try/catch block doesn't throw an error either.

Body:
I'm currently trying to write a Java agent for monitoring purposes. I use maven as build system.

I have a Agent.java file:

import java.lang.instrument.Instrumentation;

public class Agent {

    public static void premain(String args, Instrumentation inst) {
        System.out.println("Running premain");

        MonitorTransformer transformer = new MonitorTransformer();
        inst.addTransformer( transformer );
    }

}

And a MonitorTransformer.java file implementing the ClassFileTransformer interface by simply overriding the transform method.
This is how the implementation looks like:

@Override
    public byte[] transform(
        ClassLoader loader,
        String className,
        Class<?> classBeingRedefined,
        ProtectionDomain protectionDomain,
        byte[] classfileBuffer
    ) throws IllegalClassFormatException {

        System.out.println("Before ClassPool Instantiation");
        ClassPool classPool = new ClassPool();
        System.out.println("After ClassPool Instantiation");

        return classfileBuffer;
    }

When i run the agent statically by typing the following command

java -javaagent:target/agent.jar -jar example-app.jar

I get the following output:

Running premain
Before ClassPool Instantiation
Before ClassPool Instantiation
Before ClassPool Instantiation
Hello World!
Before ClassPool Instantiation
Before ClassPool Instantiation
Before ClassPool Instantiation
Before ClassPool Instantiation

It seems the print statement after the ClassPool object is instantiatet is not executed.
** Example class is just printing "Hello World" onto the console

I have tried other examples provided in the internet, with the same result. Wrapping it into try/catch block doesn't throw an error either.


问:
GoAWS creates queue without host
I'm using a service with GoAws with docker image: pafortin/goaws.

This is my docker-compose

```<code>version: '2'
services:
  goaws:
    container_name: goaws
    image: pafortin/goaws
    ports:
     - 4100:4100
    volumes:
     - ./app/conf:/conf
</code>```

The problem is that when I create the queue using this command
aws --endpoint-url http://localhost:4100 sqs create-queue --queue-name test,

I am getting this answer:

```<code>{
    "QueueUrl": "http://://test"
}
</code>```

a queue created without host and with double ://

Is this a correct behavior?

Am I doing something wrong?

Title: GoAWS creates queue without host

Body:
I'm using a service with GoAws with docker image: pafortin/goaws.

This is my docker-compose

version: '2'
services:
  goaws:
    container_name: goaws
    image: pafortin/goaws
    ports:
     - 4100:4100
    volumes:
     - ./app/conf:/conf

The problem is that when I create the queue using this command
aws --endpoint-url http://localhost:4100 sqs create-queue --queue-name test,

I am getting this answer:

{
    "QueueUrl": "http://://test"
}

a queue created without host and with double ://

Is this a correct behavior?

Am I doing something wrong?


问:
how can I send a complete XML node to a function as text?
I have the following function call which I extract the full node to XML:

```<code>mvarXmlSalida = Util.Salida("0", "", xmldoc.SelectSingleNode("//file/"))
</code>```

This is the function that obtains the elements:

```<code>Public Function Salida(ByVal est As String, ByVal err As String, Optional node As XmlNode = Nothing) As String

    Dim m_xmld = New XmlDocument
    Try
        m_xmld.LoadXml("<tx><estado></estado><info></info></tx>")
        m_xmld.SelectSingleNode("tx/estado").InnerText = est
        m_xmld.SelectSingleNode("tx/info").InnerText = err

        If Not node Is Nothing Then
            m_xmld.SelectSingleNode("//").AppendChild(node)
        End If

    Catch ex As Exception
        m_xmld.InnerText = "Error al cargar nodos de error"

    End Try
    Return m_xmld.InnerXml

End Function
</code>```

When I run the function, it returns the following error:

The expression must be evaluated as a set of nodes.

I know that it sends several nodes when I call it from there, the function can receive only one node or several nodes.

example of the node to be obtained

```<code><Transport>
 <file>
    <name>test.txt</name>
    <size>1,52 Kb</size>
    <type>.txt</type>
    <data>test data</data>
    <option>ExactName</option>
  </file>
<Transport>
</code>```

Body:
I have the following function call which I extract the full node to XML:

mvarXmlSalida = Util.Salida("0", "", xmldoc.SelectSingleNode("//file/"))

This is the function that obtains the elements:

Public Function Salida(ByVal est As String, ByVal err As String, Optional node As XmlNode = Nothing) As String

    Dim m_xmld = New XmlDocument
    Try
        m_xmld.LoadXml("<tx><estado></estado><info></info></tx>")
        m_xmld.SelectSingleNode("tx/estado").InnerText = est
        m_xmld.SelectSingleNode("tx/info").InnerText = err

        If Not node Is Nothing Then
            m_xmld.SelectSingleNode("//").AppendChild(node)
        End If

    Catch ex As Exception
        m_xmld.InnerText = "Error al cargar nodos de error"

    End Try
    Return m_xmld.InnerXml

End Function

When I run the function, it returns the following error:

The expression must be evaluated as a set of nodes.

I know that it sends several nodes when I call it from there, the function can receive only one node or several nodes.

example of the node to be obtained

<Transport>
 <file>
    <name>test.txt</name>
    <size>1,52 Kb</size>
    <type>.txt</type>
    <data>test data</data>
    <option>ExactName</option>
  </file>
<Transport>


问:
Is there a way to call a function within a package and then use it within another package in Python
I have a file structure that goes like this:

```<code>project
├── package1
│  └── useModule.py
└── package2
   └── module.py
</code>```

Basically, in package2 there are a bunch of files that do specific things such as Gets/Sets. I want to use one of the Gets from package2 in useModule.py in package1.

I have created an init.py file which allows me to use the module.py in the project directory but it does not seem to be working in the package1 directory.

I have used sys.path.append to add it to my python path and it works, but my IDE believes it to be an error as it just lights up red, it still does work. I would like to know if there were any other ways to do this without doing sys.path.append. Any ideas?

Thanks

Body:
I have a file structure that goes like this:

project
├── package1
│  └── useModule.py
└── package2
   └── module.py

Basically, in package2 there are a bunch of files that do specific things such as Gets/Sets. I want to use one of the Gets from package2 in useModule.py in package1.

I have created an init.py file which allows me to use the module.py in the project directory but it does not seem to be working in the package1 directory.

I have used sys.path.append to add it to my python path and it works, but my IDE believes it to be an error as it just lights up red, it still does work. I would like to know if there were any other ways to do this without doing sys.path.append. Any ideas?

Thanks


问:
I am trying to use lightbox for a popup window that has youtube url but it is not working
All that it displays when I click on it is black background.
Here is my code:

```<code><div class="cbp-item art illustration">
  <a class="cbp-caption cbp-lightbox" data-title="Abstract Art Museum" href="https://www.youtube.com/embed/watch?v=LnwPD69Fbh4">                                             <div class="cbp-caption-defaultWrap">
       <img src="assets/images/portfolio/masonry/art.jpg" class="portfolio-thumbnail" alt="" >
     </div>
     <div class="cbp-caption-activeWrap">
       <div class="cbp-l-caption-alignCenter">
          <div class="cbp-l-caption-body">
            <div class="cbp-l-caption-title">3D Abstract Museum</div>
               <div class="cbp-l-caption-desc">Video</div>
             </div>
           </div>
       </div>
     </a>
   </div>
</code>```

I tried to change URL and use embed code. I also tried to research more on it but it kept on showing lightbox for images with code that had modal involved in it. I have seen this code work before without the use of modal but I feel like something else is missing.

Body:
All that it displays when I click on it is black background.
Here is my code:

3D Abstract Museum

Video

I tried to change URL and use embed code. I also tried to research more on it but it kept on showing lightbox for images with code that had modal involved in it. I have seen this code work before without the use of modal but I feel like something else is missing.


问:
dynamic object keyname inside map function
I am formatting my data using the map function inside a method I am calling with a parameter named "period".

I need to get the keynames to be dynamic (generated by the base name + the period I am passing along to the outter function but it wont let me no matter how I try.

Can anyone guide me towards how to do it?

Here is my code

export async function EMA(candles: Candle[], period: number) {  //period should be used to generate key name below
  const input = candles.map((candle) => candle.close);
  const ema = await ta.indicators.ema.indicator([input], [period]);
  const diffLen = input.length - ema[0].length;
  const emptyArray = [...new Array(diffLen)].map((entry) => 0); //set 0  value for entriers before period
  const emaValues = [...emptyArray, ...ema[0]]; //get rsi values including 0 values

  candles = candles.map((candle, i) => ({
    ...candle,
    ema + period: { value: emaValues[i], period: period },  //Here I want the keyname to be ema200 ie.
  }));

  return candles;
}```

Is this even possible to use the outter functions parameter inside the .map function and build a dynamic object key name?

Body:
I am formatting my data using the map function inside a method I am calling with a parameter named "period".

I need to get the keynames to be dynamic (generated by the base name + the period I am passing along to the outter function but it wont let me no matter how I try.

Can anyone guide me towards how to do it?

Here is my code

export async function EMA(candles: Candle[], period: number) {  //period should be used to generate key name below
  const input = candles.map((candle) => candle.close);
  const ema = await ta.indicators.ema.indicator([input], [period]);
  const diffLen = input.length - ema[0].length;
  const emptyArray = [...new Array(diffLen)].map((entry) => 0); //set 0  value for entriers before period
  const emaValues = [...emptyArray, ...ema[0]]; //get rsi values including 0 values

  candles = candles.map((candle, i) => ({
    ...candle,
    ema + period: { value: emaValues[i], period: period },  //Here I want the keyname to be ema200 ie.
  }));

  return candles;
}

Is this even possible to use the outter functions parameter inside the .map function and build a dynamic object key name?


问:
Launching the SPA proxy... This page will automatically redirect to https://localhost:44426 when the SPA proxy is ready. .net6 and react
rigth now i´m creating a little crud in react and .net6 to learn new skill, i getting little issues, the principal is this Launching the SPA proxy...
This page will automatically redirect to https://localhost:44426 when the SPA proxy is ready. when i start the project tha page automatticaly show that then a console open and show this

crud2@0.1.0 prestart
node aspnetcore-https && node aspnetcore-react

crud2@0.1.0 start
rimraf ./build && react-scripts start

then the console close and open again and again and i dont know how solved please help :)

i try to solve restart de pc if some of the ports was in using while the application was running but doesnt work


问:
Files not uploading to OneDrive
The files caught on the input isn't being uploaded to my OneDrive for some reason. The error message keeps saying that the authorization key is blank but it's in the header. I'm not sure how to fix this.

I tried changing the file being fetched on the API and expecting different error messages or maybe the file being uploaded to the OneDrive but it kept showing me the same error message.

HTML code:

```<code><form id="upload-form">
                <ul>
                    <li>
                        <label class="title-label">Download File:</label>
                        <input type="file" name="download-file" id="download-file" class="upload-box" accept=".exe, .zip" required/>
                    </li>
                    <li>
                        <label class="title-label">Thumbnail:</label>
                        <input type="file" name="thumbnail" id="thumbnail" class="upload-box" accept=".png, .jpg"/>
                    </li>
                    <li>
                        <label class="title-label">Caption:</label>
                        <input type="text" name="caption" class="upload-caption" placeholder="Keep it short." maxlength="80"/>
                    </li>
                    <li>
                        <label class="title-label">Price:</label>
                        <input type="text" name="price" class="upload-caption" placeholder="$0.00" value="$1.00"/>
                    </li>
                </ul>
                <button class="upload-button" id="upload-button"><font size="5">Upload</font></button>
            </form>
</code>```

JavaScript code:

```<code>    <script>
        const form = document.getElementById("upload-form");

        form.addEventListener("submit", e => {
            e.preventDefault();

            const formData = new FormData();
            const downloadFile = document.getElementById("download-file");

            console.log(downloadFile.files[0]);

            formData.append("download-file", downloadFile.files[0]);

            //TO DO//
            fetch("https://graph.microsoft.com/drive/root/Econsole/children", {
                method: 'POST',
                body: JSON.stringify(formData),
                headers: {
                    "Authorization": "Bearer my-token",
                },
                })
                .then((response) => response.json())
                .then((result) => {
                    console.log("Success:", result)
                    alert("File uploaded successfully.")
                })
                .catch((error) => {
                    console.error("Error:", error)
                    alert("Error uploading file")
                })
            });
    </script>
</code>```

Title: Files not uploading to OneDrive

Body:
The files caught on the input isn't being uploaded to my OneDrive for some reason. The error message keeps saying that the authorization key is blank but it's in the header. I'm not sure how to fix this.

I tried changing the file being fetched on the API and expecting different error messages or maybe the file being uploaded to the OneDrive but it kept showing me the same error message.

HTML code:

<form id="upload-form">

                        Download File:
                        <input type="file" name="download-file" id="download-file" class="upload-box" accept=".exe, .zip" required/>

                        Thumbnail:
                        <input type="file" name="thumbnail" id="thumbnail" class="upload-box" accept=".png, .jpg"/>

                        Caption:
                        <input type="text" name="caption" class="upload-caption" placeholder="Keep it short." maxlength="80"/>

                        Price:
                        <input type="text" name="price" class="upload-caption" placeholder="$0.00" value="$1.00"/>

                <button class="upload-button" id="upload-button">Upload</button>
            </form>

JavaScript code:


问:
write file in android studio
when creating a file from android studio it does not show me in my gallery, it shows when restarting the computer?</p>

Title: write file in android studio


问:
is it possible to use qt container such as QSet classes in python
Qt has container classes such as QList and QSet: https://doc.qt.io/qt-5/containers.html

Is it possible to use these qt container classes in python through PyQt5?

I can't find a way to import these classes and create instances.
I would like to create a set of QTreeWidgetItem to be able to quickly check for members of the set


问:
How to do OAuth dance with Deezer API on iOS?
I'm currently trying to complete the OAuth dance with the Deezer API.
I have created a Deezer app on their site and full fill required fields.
I'm not using the Deezer SDK as it's deprecated since a long time ago.
I'm loading the request with a WKWebView and the request looks like :
https://connect.deezer.com/oauth/auth.php?app_id=MY_APP_ID&redirect_uri=MY_REDIRECT_URL&response_type=token&perms=basic_access

This open a webview displaying an auth form.
After i login with my deezer account credentials, i'm supposed to be redirected to the previous specified url MY_REDIRECT_URL.
But i intercept the redirection like this :

```<code>    public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Swift.Void) {
        if !isLoading {
            isLoading = true
        }
        if let redirectedUrl = navigationAction.request.url, redirectedUrl.host == AppConfig.redirectHost {
            // extracting token from url
            let deezerToken = DeezerURLBuilder.deezerToken(fromUrl: redirectedUrl)
            // saving token
            PrefUtils.shared.deezerToken = deezerToken
            didLogin = true
            decisionHandler(.cancel)
            return
        }
        decisionHandler(.allow)
    }
</code>```

I don't want to go to the redirect url because i'm in a iOS app and i hope i could prevent the server step.

I have noticed that the redirectedUrl looks like : https://MY_REDIRECT_URL/#access_token=frazeeFRT188maXzvPiCeTDEjCCbrIGGaCwlkGQra4whmp7rtJ&expires=1468

I don't understand why because from the Deezer API, i should see a code query parameter which i should put in the next request for App Authentication like this :
https://connect.deezer.com/oauth/access_token.php?app_id=MY_APP_ID&secret=MY_APP_SECRET&code=THE_MISSING_CODE
That request was sent with URLSession.shared.data.

So i was assuming that i got the final access_token and continue to request the user info with :
https://api.deezer.com/user/me?access_token=frazeeFRT188maXzvPiCeTDEjCCbrIGGaCwlkGQra4whmp7rtJ

Finally i got an error stating : "An active token must be used to query information about the current user"

I try the first request inside Safari in macOS then i was redirected to MY_REDIRECT_URL. After this i tried the request to get user info and it succeeded, i saw the json response in the Safari.

As i understand, Deezer has set cookies during the redirection in Safari. My guess is requests are completed because of the cookies and when i'm in the iOS App WKWebView is dismiss and subsequent requests are made without these.

To sum up,
<s>why am i getting access_token without providing 'my app secret request' ?</s>
(because i ask for it with the response_type param set to token)

How to properly do OAuth dance with Deezer API in SwiftUI/Swift App without Deezer SDK ?

PS: I didn't try OAuthSwift library as i want to keep it simple.

Thx for any help

EDIT: SOLVED

it was a typo in my url parameter... but it is fully working without a server redirect.

Body:
I'm currently trying to complete the OAuth dance with the Deezer API.
I have created a Deezer app on their site and full fill required fields.
I'm not using the Deezer SDK as it's deprecated since a long time ago.
I'm loading the request with a WKWebView and the request looks like :
https://connect.deezer.com/oauth/auth.php?app_id=MY_APP_ID&redirect_uri=MY_REDIRECT_URL&response_type=token&perms=basic_access

This open a webview displaying an auth form.
After i login with my deezer account credentials, i'm supposed to be redirected to the previous specified url MY_REDIRECT_URL.
But i intercept the redirection like this :

    public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Swift.Void) {
        if !isLoading {
            isLoading = true
        }
        if let redirectedUrl = navigationAction.request.url, redirectedUrl.host == AppConfig.redirectHost {
            // extracting token from url
            let deezerToken = DeezerURLBuilder.deezerToken(fromUrl: redirectedUrl)
            // saving token
            PrefUtils.shared.deezerToken = deezerToken
            didLogin = true
            decisionHandler(.cancel)
            return
        }
        decisionHandler(.allow)
    }

I don't want to go to the redirect url because i'm in a iOS app and i hope i could prevent the server step.

I have noticed that the redirectedUrl looks like : https://MY_REDIRECT_URL/#access_token=frazeeFRT188maXzvPiCeTDEjCCbrIGGaCwlkGQra4whmp7rtJ&expires=1468

I don't understand why because from the Deezer API, i should see a code query parameter which i should put in the next request for App Authentication like this :
https://connect.deezer.com/oauth/access_token.php?app_id=MY_APP_ID&secret=MY_APP_SECRET&code=THE_MISSING_CODE
That request was sent with URLSession.shared.data.

So i was assuming that i got the final access_token and continue to request the user info with :
https://api.deezer.com/user/me?access_token=frazeeFRT188maXzvPiCeTDEjCCbrIGGaCwlkGQra4whmp7rtJ

Finally i got an error stating : "An active token must be used to query information about the current user"

I try the first request inside Safari in macOS then i was redirected to MY_REDIRECT_URL. After this i tried the request to get user info and it succeeded, i saw the json response in the Safari.

As i understand, Deezer has set cookies during the redirection in Safari. My guess is requests are completed because of the cookies and when i'm in the iOS App WKWebView is dismiss and subsequent requests are made without these.

To sum up,
<s>why am i getting access_token without providing 'my app secret request' ?</s>
(because i ask for it with the response_type param set to token)

How to properly do OAuth dance with Deezer API in SwiftUI/Swift App without Deezer SDK ?

PS: I didn't try OAuthSwift library as i want to keep it simple.

Thx for any help

EDIT: SOLVED

it was a typo in my url parameter... but it is fully working without a server redirect.