鸵鸟症

文章 评论 浏览 30

鸵鸟症 2025-02-21 01:33:11

这里有多个问题。 要点

将尝试突出 1的 进行了反应性API的重构?

。从第一个外观看,您的应用程序是IO绑定的,并且反应性应用程序通常更有效地 反应性应用程序不会更快,但是您需要更少的资源来解决唯一的警告是,为了从反应性API中获得所有收益,您的应用程序应该是反应性的端到端(DB的反应驱动程序,反应性网络电机,…) 。所有反应性逻辑均在schedulers.parallel()上执行,并且您需要少量线程(默认情况下,CPU内核数)才能执行非阻滞逻辑。通过将它们“卸载”到schedulas.boundedelastic()中,仍然可能使用阻止API,但是应该是一个例外(不是规则),以提高您的应用程序效率。有关更多详细信息,请检查磁通3的飞行 - 跳线和调度程序

2。

看起来像是对阻止API有些误解。这不是关于响应时间,而是关于强调API。默认情况下,Spring WebFlux使用反应堆Netty作为基础HTTP客户端库,它本身就是Netty客户端的反应性实现,该实现使用事件循环而不是每个请求模型。即使请求需要30-60秒才能获得响应,也不会阻止线程,因为所有IO操作都是异步。对于此类API,反应性应用程序的行为会好得多,因为对于非反应性(每个请求线程),您将需要大量线程,并且结果更多的内存才能处理相同的工作负载。

为了量化效率,我们可以应用 Little's Ward 来计算A“传统”中所需的线程数量线程每个请求模型

工人> = totup x延迟,其中工人 - 线程

数量例如,要处理具有30秒延迟的100 QP,我们需要100 x 30 = 3000个线程。在反应性应用程序中,相同的工作负载只能由几个线程处理,因此,内存更少。为了伸缩性,这意味着对于IO绑定的反应应用程序,通常您通常会通过CPU使用和“传统”进行扩展。

有时候,什么代码在阻止哪些代码并不明显。测试反应代码时的一个非常有用的工具是 blockhound 您可以将其集成到单元测试中。

3。如何重构?

我会逐层迁移,但只阻止一次。将远程调用转移到网络电机可能是重构应用程序的第一步,以进行反应性API。我将使用反应性API创建所有请求/响应逻辑,然后在最高级别(例如,在控制器中)阻止(如果需要)。做和不做:避免避免首次反应性程序员矿山是一个很好的概述。常见的陷阱和可能的迁移策略。

4。通量与单声道。

flux不会帮助您提高性能。更多的是下游逻辑。如果您处理记录录制 - 使用flux< t>,但是如果您分批处理数据 - 使用mono< list< t>>>

您当前的代码并不是真正的反应性,并且很难理解混合反应性API,流动API并多次阻止。作为第一步,尝试使用反应性API将其重写为单个流,并且仅阻止一次。

不太确定您的内部类型,但这里有一些骨架可以使您了解该流程。

// Service method
public Flux<Task> getTasks() {
    return getTasksMono()
            .flatMapMany(response -> {
                List<Mono<Response<Task>>> taskRequests = new ArrayList<>();
                taskRequests.add(Mono.just(response));

                if (response.getCount() > TASK_QUERY_LIMIT) {
                    retrieveAdditionalTasks(key, response.getCount(), taskRequests);
                }

                return Flux.mergeSequential(taskRequests);
            })
            .flatMapIterable(Response::getData)
            .map(this::transform); // use flatMap in case transform is async
}

如前所述,尝试将内部API保持反应式返回单声道flux,并且在上层中仅阻止一次。

There are multiple questions here. Will try to highlight main points

1. Does it make sense refactoring to Reactive API?

From the first look your application is IO bound and typically reactive applications are much more efficient because all IO operations are async and non-blocking. Reactive application will not be faster but you will need less resources to The only caveat is that in order to get all benefits from the reactive API, your app should be reactive end-to-end (reactive drivers for DB, reactive WebClient, …). All reactive logic is executed on Schedulers.parallel() and you need small number of threads (by default, number of CPU cores) to execute non-blocking logic. It’s still possible use blocking API by “offloading” them to Schedulers.boundedElastic() but it should be an exception (not the rule) to make your app efficient. For more details, check Flight of the Flux 3 - Hopping Threads and Schedulers.

2. Blocking vs non-blocking.

It looks like there is some misunderstanding of the blocking API. It’s not about response time but about underlining API. By default, Spring WebFlux uses Reactor Netty as underlying Http Client library which itself is a reactive implementation of Netty client that uses Event Loop instead of Thread Per Request model. Even if request takes 30-60 sec to get response, thread will not be blocked because all IO operations are async. For such API reactive applications will behave much better because for non-reactive (thread per request) you would need large number of threads and as result much more memory to handle the same workload.

To quantify efficiency we could apply Little's Law to calculate required number of threads in a ”traditional” thread per request model

workers >= throughput x latency, where workers - number of threads

For example, to handle 100 QPS with 30 sec latency we would need 100 x 30 = 3000 threads. In reactive app the same workload could be handled by several threads only and, as result, much less memory. For scalability it means that for IO bound reactive apps you would typically scale by CPU usage and for “traditional” most probably by memory.

Sometimes it's not obvious what code is blocking. One very useful tool while testing reactive code is BlockHound that you could integrate into unit tests.

3. How to refactor?

I would migrate layer by layer but block only once. Moving remote calls to WebClient could be a first step to refactor app to reactive API. I would create all request/response logic using reactive API and then block (if required) at the very top level (e.g. in controller). Do’s and Don’ts: Avoiding First-Time Reactive Programmer Mines is a great overview of the common pitfalls and possible migration strategy.

4. Flux vs Mono.

Flux will not help you to improve performance. It’s more about downstream logic. If you process record-by-record - use Flux<T> but if you process data in batches - use Mono<List<T>>.

Your current code is not really reactive and very hard to understand mixing reactive API, stream API and blocking multiple times. As a first step try to rewrite it as a single flow using reactive API and block only once.

Not really sure about your internal types but here is some skeleton that could give you an idea about the flow.

// Service method
public Flux<Task> getTasks() {
    return getTasksMono()
            .flatMapMany(response -> {
                List<Mono<Response<Task>>> taskRequests = new ArrayList<>();
                taskRequests.add(Mono.just(response));

                if (response.getCount() > TASK_QUERY_LIMIT) {
                    retrieveAdditionalTasks(key, response.getCount(), taskRequests);
                }

                return Flux.mergeSequential(taskRequests);
            })
            .flatMapIterable(Response::getData)
            .map(this::transform); // use flatMap in case transform is async
}

As I mentioned before, try to keep internal API reactive returning Mono or Flux and block only once in the upper layer.

Spring WebFlux:用反应性API重构阻止API,还是我应该?

鸵鸟症 2025-02-20 12:43:43

在Python 3.9.10替补中测试:

>>> currency = 'د.إ'
>>> price = '9.99'
>>> print(currency)
د.إ
>>> print(price)
9.99
>>> print(currency, price)
د.إ 9.99

Tested in Python 3.9.10 REPL:

>>> currency = 'د.إ'
>>> price = '9.99'
>>> print(currency)
د.إ
>>> print(price)
9.99
>>> print(currency, price)
د.إ 9.99

python中串联串联订购字符串

鸵鸟症 2025-02-20 07:38:19

我发现了另一个引起此问题并已经解决的问题。我不小心将脚本保存在utf-16编码中。 PHP5似乎无法识别&lt;?php在16位中默认编码的标签。

I found another problem causing this issue and already solved it. I accidentally saved my script in UTF-16 encoding. It seems that PHP5 can't recognize <?php tag in 16 bit encoding by default.

PHP代码尚未执行,但代码在浏览器源代码中显示

鸵鸟症 2025-02-20 02:43:46

之所以失败的原因是您使用的Mac使用的flutter版本3具有更改窗口小部件绑定的更改,即不需要使用不使用的限制?在小部件绑定中。包装百分比指示器不摇动3兼容。请将版本更改为percenter_indicator: ^4.2.2 flutter 3兼容。进行清洁和POD安装,它应该可以工作

编辑

清洁酒吧缓存您可以运行flutter Pub Cache Clean

请注意,这将清除所有您的酒吧缓存,然后您可能必须经营Flutter Pub参加所有项目

The reason why it failed is that your Mac used flutter version 3 which has a change that widget binding cannot be null which required not to use? In Widget binding. The package percentage indicator is not flutter 3 compatible. Please change the version to percent_indicator: ^4.2.2 which is flutter 3 compatible. Do a flutter clean and pod install and it should work

Edit

To clean your pub cache you can run flutter pub cache clean

Please note that this will clear all your pub cache which after that you may have to run flutter pub get on all projects

由于Flutter_IOS_BUILD_TEMP_DIRZZL8EG/QUERTARY_XCRESULT_BUNDLE,可以在我的iPhone上启动Flutter应用程序吗?

鸵鸟症 2025-02-19 11:00:00

我解决了这个问题。 页面上工作代码

在此处在app.route函数的

 if turbo.can_stream():
        return turbo.stream(
            turbo.replace(render_template('doc_cards.html', data=data), target='load_cards'))
    else:
        return render_template('home.html', form=search_form, data=data)

将在其中更新内容

 <div class="container">
    {% with data=data %}
        {% include "doc_cards.html"%}
    {% endwith %}
</div>

和动态内容

<div id="load_cards" class="container">
    {% if data is defined %}
        {% for item in data %}
          .......
        {% endfor %}
    {% endif %}
</div>

I solved this. Here working code

in app.route function

 if turbo.can_stream():
        return turbo.stream(
            turbo.replace(render_template('doc_cards.html', data=data), target='load_cards'))
    else:
        return render_template('home.html', form=search_form, data=data)

On page where content will be updated

 <div class="container">
    {% with data=data %}
        {% include "doc_cards.html"%}
    {% endwith %}
</div>

and dynamic content

<div id="load_cards" class="container">
    {% if data is defined %}
        {% for item in data %}
          .......
        {% endfor %}
    {% endif %}
</div>

提交按钮时涡轮式涡轮增压涡轮增压

鸵鸟症 2025-02-19 05:51:14

pynput没有is_presse() - 我不知道您在哪里找到它。

您应该使用pynput.keyboard.listener在按下q时运行代码结束程序。


您不能有两个具有相同名称控制器的对象。

一个控制器替换其他控制器,然后您使用相同的Controller来创建鼠标键盘代码> - 这使问题问题。

您必须使用pynput.mouse.controllerpynput.keyboard.pynput.controller

import pynput
from pynput.mouse import Button
from pynput.keyboard import Key
import time

keyboard = pynput.keyboard.Controller()
mouse    = pynput.mouse.Controller()

while True:
    time.sleep(10)
    mouse.click(Button.left)
    #if keyboard.is_pressed('q'):  # <-- this will need Listener()
    #    break

编辑:

q 您必须使用侦听器

例如:

import pynput
from pynput.mouse import Button
import time

mouse_controller = pynput.mouse.Controller()

def on_press(key):
    print('pressed:', key)
    if str(key) == "'q'":  # it has to be with `' '` inside `" "`
        # Stop listener
        print("exit listener")
        return False  # `False` ends listener

with pynput.keyboard.Listener(on_press=on_press) as keyboard_listener:
    
    while keyboard_listener.is_alive():
        time.sleep(10)
        mouse_controller.click(Button.left)
        print('clicked')

pynput doesn't have is_pressed() - I don't know where you find it.

You should rather use pynput.keyboard.Listener to run code when q is pressed and set some variable - q_is_pressed = True - or run code which ends program.


You can't have two objects with the same name Controller.

One Controller replaces other Controller and later you use the same Controller to create mouse and keyboard - and this makes problem.

You have to use pynput.mouse.Controller and pynput.keyboard.pynput.Controller

import pynput
from pynput.mouse import Button
from pynput.keyboard import Key
import time

keyboard = pynput.keyboard.Controller()
mouse    = pynput.mouse.Controller()

while True:
    time.sleep(10)
    mouse.click(Button.left)
    #if keyboard.is_pressed('q'):  # <-- this will need Listener()
    #    break

EDIT:

To end code when q was pressed you have to use Listener

For example:

import pynput
from pynput.mouse import Button
import time

mouse_controller = pynput.mouse.Controller()

def on_press(key):
    print('pressed:', key)
    if str(key) == "'q'":  # it has to be with `' '` inside `" "`
        # Stop listener
        print("exit listener")
        return False  # `False` ends listener

with pynput.keyboard.Listener(on_press=on_press) as keyboard_listener:
    
    while keyboard_listener.is_alive():
        time.sleep(10)
        mouse_controller.click(Button.left)
        print('clicked')

为什么我总是让错误消息控制器没有属性is_pressed?

鸵鸟症 2025-02-18 23:13:16

您可以尝试在非全局模式下使用替换()进行正则替换,因此,这将仅针对输入字符串中的第一匹匹配。

var input = "XX XXXX XX XXX";
var output = input.replace(/ \w+/, " YYYY");
console.log(output);

You could try doing a regex replacement with replace(), in non global mode, which would therefore target just the first match in the input string.

var input = "XX XXXX XX XXX";
var output = input.replace(/ \w+/, " YYYY");
console.log(output);

在两个空间之间替换一部分字符串

鸵鸟症 2025-02-18 08:05:34

基本上,如果您的测试框架进行了测试,则需要将SureFire插件添加到POM中。

请查看 this 并相应地更新您的POM。

Basically, if your test framework is TestNg then you need to add the surefire plugin to your pom.

Please have a look at this and update your POM accordingly.

詹金斯(Jenkins)构建成功后,它将显示未运行的测试。&#x27;用于黄瓜自动化

鸵鸟症 2025-02-18 06:06:13

您应该将浮动按钮放在协调器布局中。

You should place the floating button inside the Coordinator Layout.

如何包括浮动动作按钮以绘制java android studio

鸵鸟症 2025-02-18 05:38:34

尝试使用dyplr :: rename()或在if_else()的最终消除na中替换为“”无空间。

Try with dyplr::rename() or eliminate NA at final of if_else() replace it with "" without space.

处理R中的整数变量时的IFELSE错误

鸵鸟症 2025-02-18 04:09:02

您的问题并没有真正连接到TKINTER和GUI编程。您需要多线程或多处理。有效的解决方案取决于您想做什么。您可以看到有关选择多线程/多处理的以下页面: this

=“ nofollow noreferrer 对我来说并不清楚水晶,但我试图在答案中尽力而为。

您可以在下面看到一个测试代码,而无需任何并行性,因此它不是您的解决方案。

代码:

"""
Example script for data processing
"""


def call_main_script(ip_adr_str, processes_dict):
    """
    Print the data structure for testing.

    Args:
        ip_adr_str: The IP address as string to define the dict key.
        processes_dict: The dict data structure

    Returns: None

    """

    # Get the key-values based on the given IP address
    for key, value in processes_dict[ip_adr_str].items():
        print("{} -> {}".format(key, value))
    print("\n\n")


class DummyCheckBox:
    """
    A Dummy class for simulate the CheckBox widget of TK.
    """

    def __init__(self, number_of_box):
        """
        The constructor of DummyCheckBox

        Args:
            number_of_box: Input parameter of "widget"
        """

        self.number_of_box = number_of_box

    def get(self):
        """
        Provides some dummy value (Class name and the input value...).

        Returns: Dummy str.
        """

        return "{}_{}".format(self.__class__.__name__, self.number_of_box)


class DummyName:
    """
    A Dummy class for simulate the Input widget of TK.
    """

    def __init__(self, name_input):
        """
        The constructor of DummyName

        Args:
            name_input: Input parameter of "widget"
        """
        self.name = name_input

    def get(self):
        """
        Provides some dummy value (Class name and the input value...).

        Returns: Dummy str.
        """

        return "{}_{}".format(self.__class__.__name__, self.name)


# Creating the instances from the Check Box class.
dummy_check_box_1 = DummyCheckBox(1)
dummy_check_box_2 = DummyCheckBox(2)
dummy_check_box_3 = DummyCheckBox(3)

# Creating the instances from the Name widget class.
dummy_name_1 = DummyName("FOO")
dummy_name_2 = DummyName("BAR")
dummy_name_3 = DummyName("BAZ")

processes = {}

# Put the instances to lists.
check_boxes = [dummy_check_box_1, dummy_check_box_2, dummy_check_box_3]
names = [dummy_name_1, dummy_name_2, dummy_name_3]

# You can process the lists in ony for loop with the "zip" function.
for check_box, name in zip(check_boxes, names):
    if check_box.get():
        processes["192.168.x.xx"] = {
            "name": name.get(),
            "ip": "dummy_ip",
            "enable_disable": check_box.get(),
            "email": "dummy_mail",
            "email_address": "dummy_adress",
        }
        call_main_script("192.168.x.xx", processes)

输出:

>>> python3 test.py

name -> DummyName_FOO
ip -> dummy_ip
enable_disable -> DummyCheckBox_1
email -> dummy_mail
email_address -> dummy_adress

name -> DummyName_BAR
ip -> dummy_ip
enable_disable -> DummyCheckBox_2
email -> dummy_mail
email_address -> dummy_adress

name -> DummyName_BAZ
ip -> dummy_ip
enable_disable -> DummyCheckBox_3
email -> dummy_mail
email_address -> dummy_adress

以下示例包含多线程解决方案。我已经评论了代码中所有更改的位置。

代码:

"""
Example script for data processing
"""

import threading
import random
import time


def call_main_script(processes_dict):
    """
    Print the data structure for testing.

    Args:
        processes_dict: The dict data structure

    Returns: None

    """

    # Get a random integer between 1-5 and sleep it in secs.
    random_sleep = random.randint(1, 5)
    time.sleep(random_sleep)
    print(
        "[{}] ({} secs slept) name -> {}".format(
            threading.current_thread().name, random_sleep, processes_dict["name"]
        )
    )


class DummyCheckBox:
    """
    A Dummy class for simulate the CheckBox widget of TK.
    """

    def __init__(self, number_of_box):
        """
        The constructor of DummyCheckBox

        Args:
            number_of_box: Input parameter of "widget"
        """

        self.number_of_box = number_of_box

    def get(self):
        """
        Provides some dummy value (Class name and the input value...).

        Returns: Dummy str.
        """

        return "{}_{}".format(self.__class__.__name__, self.number_of_box)


class DummyName:
    """
    A Dummy class for simulate the Input widget of TK.
    """

    def __init__(self, name_input):
        """
        The constructor of DummyName

        Args:
            name_input: Input parameter of "widget"
        """
        self.name = name_input

    def get(self):
        """
        Provides some dummy value (Class name and the input value...).

        Returns: Dummy str.
        """

        return "{}_{}".format(self.__class__.__name__, self.name)


# Creating the instances from the Check Box class.
dummy_check_box_1 = DummyCheckBox(1)
dummy_check_box_2 = DummyCheckBox(2)
dummy_check_box_3 = DummyCheckBox(3)

# Creating the instances from the Name widget class.
dummy_name_1 = DummyName("FOO")
dummy_name_2 = DummyName("BAR")
dummy_name_3 = DummyName("BAZ")

# This list will contain the dict structures.
processes = []

# Put the instances to lists.
check_boxes = [dummy_check_box_1, dummy_check_box_2, dummy_check_box_3]
names = [dummy_name_1, dummy_name_2, dummy_name_3]

# You can process the lists in ony for loop with the "zip" function.
for check_box, name in zip(check_boxes, names):
    if check_box.get():
        # Creating the dict data structure.
        data_structure = {
            "name": name.get(),
            "ip": "dummy_ip",
            "enable_disable": check_box.get(),
            "email": "dummy_mail",
            "email_address": "dummy_adress",
        }

        # Append the actual dict data structure to the process list.
        processes.append(data_structure)

# Creating the list for the started threads. We will wait the threads based on this list.
threads = []

# Creating threads for the dict data structures.
for single_dict in processes:
    # Creating the thread which calls the "call_main_script" function with "single_dict" argument.
    t = threading.Thread(target=call_main_script, args=(single_dict,))
    # Start the actual thread.
    t.start()
    # Append the Thread object to the list.
    threads.append(t)

# Join (Stop) the Threads one-by-one.
for t in threads:
    # Wait until thread is completely executed
    t.join()

print("Done!")

输出:

>>> python3 test.py

[Thread-3] (1 secs slept) name -> DummyName_BAZ
[Thread-1] (2 secs slept) name -> DummyName_FOO
[Thread-2] (5 secs slept) name -> DummyName_BAR
Done!

您可以在上面的输出部分中看到3个不同的DICE数据结构在3个线程上启动。我添加了一个随机的(1-5秒)睡眠以更好地表示。

You question is not really connected to Tkinter and GUI programming. You need multithreading or multiprocessing. The efficient solution depends on what you want to do. You can see the following pages about select the multithreading/multiprocessing: This and This

Honestly based on your question your problem is not crystal clear for me but I tried to do my best in my answer.

You can see a test code below, without any parallelism, so it's not the solution for you.

Code:

"""
Example script for data processing
"""


def call_main_script(ip_adr_str, processes_dict):
    """
    Print the data structure for testing.

    Args:
        ip_adr_str: The IP address as string to define the dict key.
        processes_dict: The dict data structure

    Returns: None

    """

    # Get the key-values based on the given IP address
    for key, value in processes_dict[ip_adr_str].items():
        print("{} -> {}".format(key, value))
    print("\n\n")


class DummyCheckBox:
    """
    A Dummy class for simulate the CheckBox widget of TK.
    """

    def __init__(self, number_of_box):
        """
        The constructor of DummyCheckBox

        Args:
            number_of_box: Input parameter of "widget"
        """

        self.number_of_box = number_of_box

    def get(self):
        """
        Provides some dummy value (Class name and the input value...).

        Returns: Dummy str.
        """

        return "{}_{}".format(self.__class__.__name__, self.number_of_box)


class DummyName:
    """
    A Dummy class for simulate the Input widget of TK.
    """

    def __init__(self, name_input):
        """
        The constructor of DummyName

        Args:
            name_input: Input parameter of "widget"
        """
        self.name = name_input

    def get(self):
        """
        Provides some dummy value (Class name and the input value...).

        Returns: Dummy str.
        """

        return "{}_{}".format(self.__class__.__name__, self.name)


# Creating the instances from the Check Box class.
dummy_check_box_1 = DummyCheckBox(1)
dummy_check_box_2 = DummyCheckBox(2)
dummy_check_box_3 = DummyCheckBox(3)

# Creating the instances from the Name widget class.
dummy_name_1 = DummyName("FOO")
dummy_name_2 = DummyName("BAR")
dummy_name_3 = DummyName("BAZ")

processes = {}

# Put the instances to lists.
check_boxes = [dummy_check_box_1, dummy_check_box_2, dummy_check_box_3]
names = [dummy_name_1, dummy_name_2, dummy_name_3]

# You can process the lists in ony for loop with the "zip" function.
for check_box, name in zip(check_boxes, names):
    if check_box.get():
        processes["192.168.x.xx"] = {
            "name": name.get(),
            "ip": "dummy_ip",
            "enable_disable": check_box.get(),
            "email": "dummy_mail",
            "email_address": "dummy_adress",
        }
        call_main_script("192.168.x.xx", processes)

Output:

>>> python3 test.py

name -> DummyName_FOO
ip -> dummy_ip
enable_disable -> DummyCheckBox_1
email -> dummy_mail
email_address -> dummy_adress

name -> DummyName_BAR
ip -> dummy_ip
enable_disable -> DummyCheckBox_2
email -> dummy_mail
email_address -> dummy_adress

name -> DummyName_BAZ
ip -> dummy_ip
enable_disable -> DummyCheckBox_3
email -> dummy_mail
email_address -> dummy_adress

The following example contains a multithreading solution. I have commented all changed place in the code.

Code:

"""
Example script for data processing
"""

import threading
import random
import time


def call_main_script(processes_dict):
    """
    Print the data structure for testing.

    Args:
        processes_dict: The dict data structure

    Returns: None

    """

    # Get a random integer between 1-5 and sleep it in secs.
    random_sleep = random.randint(1, 5)
    time.sleep(random_sleep)
    print(
        "[{}] ({} secs slept) name -> {}".format(
            threading.current_thread().name, random_sleep, processes_dict["name"]
        )
    )


class DummyCheckBox:
    """
    A Dummy class for simulate the CheckBox widget of TK.
    """

    def __init__(self, number_of_box):
        """
        The constructor of DummyCheckBox

        Args:
            number_of_box: Input parameter of "widget"
        """

        self.number_of_box = number_of_box

    def get(self):
        """
        Provides some dummy value (Class name and the input value...).

        Returns: Dummy str.
        """

        return "{}_{}".format(self.__class__.__name__, self.number_of_box)


class DummyName:
    """
    A Dummy class for simulate the Input widget of TK.
    """

    def __init__(self, name_input):
        """
        The constructor of DummyName

        Args:
            name_input: Input parameter of "widget"
        """
        self.name = name_input

    def get(self):
        """
        Provides some dummy value (Class name and the input value...).

        Returns: Dummy str.
        """

        return "{}_{}".format(self.__class__.__name__, self.name)


# Creating the instances from the Check Box class.
dummy_check_box_1 = DummyCheckBox(1)
dummy_check_box_2 = DummyCheckBox(2)
dummy_check_box_3 = DummyCheckBox(3)

# Creating the instances from the Name widget class.
dummy_name_1 = DummyName("FOO")
dummy_name_2 = DummyName("BAR")
dummy_name_3 = DummyName("BAZ")

# This list will contain the dict structures.
processes = []

# Put the instances to lists.
check_boxes = [dummy_check_box_1, dummy_check_box_2, dummy_check_box_3]
names = [dummy_name_1, dummy_name_2, dummy_name_3]

# You can process the lists in ony for loop with the "zip" function.
for check_box, name in zip(check_boxes, names):
    if check_box.get():
        # Creating the dict data structure.
        data_structure = {
            "name": name.get(),
            "ip": "dummy_ip",
            "enable_disable": check_box.get(),
            "email": "dummy_mail",
            "email_address": "dummy_adress",
        }

        # Append the actual dict data structure to the process list.
        processes.append(data_structure)

# Creating the list for the started threads. We will wait the threads based on this list.
threads = []

# Creating threads for the dict data structures.
for single_dict in processes:
    # Creating the thread which calls the "call_main_script" function with "single_dict" argument.
    t = threading.Thread(target=call_main_script, args=(single_dict,))
    # Start the actual thread.
    t.start()
    # Append the Thread object to the list.
    threads.append(t)

# Join (Stop) the Threads one-by-one.
for t in threads:
    # Wait until thread is completely executed
    t.join()

print("Done!")

Output:

>>> python3 test.py

[Thread-3] (1 secs slept) name -> DummyName_BAZ
[Thread-1] (2 secs slept) name -> DummyName_FOO
[Thread-2] (5 secs slept) name -> DummyName_BAR
Done!

As you can see on above output section the 3 different dict data structures started on 3 threads. I have added a random (1-5 secs) sleep for better representation.

使用GUI运行具有不同变量的脚本的多个实例

鸵鸟症 2025-02-18 02:59:00

尝试Vanilla JavaScript:

.setAttribute('required', true/false);
.removeAttribute('required');
.toggleAttribute('required');

如果您在jQuery对象上使用Vanilla JavaScript方法,它将无法识别它。因此,您要么使用JavaScript方法引用元素(推荐)或退参考jQuery对象:

// Two ways to de-referencing a jQuery object
$('input')[0]
//OR
$('input').get(0)

零表示您仅针对第一个目标,因此,如果您已经知道这是第二个输入使用索引1。

// Using no ids, classes, or tagnames just indexes
document.forms[0].elements[1].onclick = e => 
  e.target.previousElementSibling.toggleAttribute('required');
  
// De-referencing the second .data 
$('.data')[1].setAttribute('required', true);
[required] {
  outline: 3px dashed red
}
<form>
  <input name='data' class='data'><input type='button' value='Toggle'><br>
  <input name='data' class='data'><br>
  <button>Submit</button>
</form>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

只是一些建议,您要删除的属性通常不会因为其性质而被删除。 占位符永远不需要删除,因为当用户专注于表单控件时,它会消失。 必需的不应删除,因为它有助于验证。您为什么需要删除它们?

Try vanilla JavaScript:

.setAttribute('required', true/false);
.removeAttribute('required');
.toggleAttribute('required');

If you use vanilla JavaScript methods on a jQuery object, it will not recognize it. So you either use JavaScript methods to reference an element (recommended) or de-reference the jQuery object:

// Two ways to de-referencing a jQuery object
$('input')[0]
//OR
$('input').get(0)

The zero indicates that you are targeting the first one only so if you already know that it's the second input use index 1.

// Using no ids, classes, or tagnames just indexes
document.forms[0].elements[1].onclick = e => 
  e.target.previousElementSibling.toggleAttribute('required');
  
// De-referencing the second .data 
$('.data')[1].setAttribute('required', true);
[required] {
  outline: 3px dashed red
}
<form>
  <input name='data' class='data'><input type='button' value='Toggle'><br>
  <input name='data' class='data'><br>
  <button>Submit</button>
</form>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Just some advice, the attributes you are removing are not commonly removed because of their nature. A placeholder never needs to be removed because it disappears when the user focuses on a form control. required shouldn't be removed because it facilitates validation. Why would you need to remove them?

jQuery removeAttr,prop,attr不适用于必需&#x27;财产

鸵鸟症 2025-02-18 02:02:53

当查询在SQL Shell外面不需要半隆时,这很常见。通常它们需要,但不是强制性的。例如,在python脚本中启动SQL查询时,没有必要以;结束查询,因为Shell不需要知道何时结束。取而代之的是,在SQL外壳中,您可以按件编写查询。

That's pretty common for queries to not need a semicolon when outside the SQL Shell. Generally they're needed, but not mandatory. For example, when launching a SQL query inside a Python script, it's unnecessary to end the query with ;, because the shell doesn't need to know when it ends. Instead, in the SQL Shell, you are able to write the query piece by piece.

无法理解SQL语句终止

鸵鸟症 2025-02-17 18:49:28

您的数据

CREATE TABLE test(
   ID    INTEGER  NOT NULL 
  ,Month VARCHAR(40) NOT NULL
);
INSERT INTO test
(ID,Month) VALUES 
(0,'Mar'),
(1,'July'),
(2,'Jun'),
(3,'Aug');

由于列类型未明确表示为

Select name, alias, months, shortmonths
from   sys.syslanguages
where name='us_english'
姓名别名月份1月,2月,3月,4月,五月,五月,六月,七月,八月,九月,10月
us_english英语,10月,11月,12月,12月,1月1月, ,4月,5月,6月,7月,8月,10月,11月,12月,12月,1月1月1

5
6,3月
1月1月2月2月3月3月4月4月4
5月7月7月8月8月8月
81
1月8月10月10月10
1月10月
10月10
月12月12
12月12
12月12月

通过使用string_splitrow_number

SELECT shortmonth,
       fullname
FROM   (SELECT NAME,
               alias,
               months,
               shortmonths,
               a.value                     AS shortmonth,
               Row_number()
                 OVER (
                   ORDER BY (SELECT NULL)) rn
        FROM   (SELECT NAME,
                       alias,
                       months,
                       shortmonths
                FROM   sys.syslanguages
                WHERE  NAME = 'us_english') b
               CROSS apply String_split(shortmonths, ',') a) t1
       JOIN (SELECT NAME,
                    alias,
                    months,
                    shortmonths,
                    c.value                     fullName,
                    Row_number()
                      OVER (
                        ORDER BY (SELECT NULL)) rn
             FROM   (SELECT NAME,
                            alias,
                            months,
                            shortmonths
                     FROM   sys.syslanguages
                     WHERE  NAME = 'us_english') b
                    CROSS apply String_split(months, ',') c) t2
         ON t1.rn = t2.rn  

cte中使用上述查询,并与您的表一起使用前三个 wargin和然后使用eomonth正确的函数如下所示,

SELECT t.*,
       m.fullname,
       RIGHT(Eomonth(( '01-' + m.fullname + '-2010' )), 5)
FROM   test t
       JOIN monthname1 m
         ON LEFT(t.month, 3) = m.shortmonth  

但是使用适当的年份不应忽略leap年的适当年份。

your data

CREATE TABLE test(
   ID    INTEGER  NOT NULL 
  ,Month VARCHAR(40) NOT NULL
);
INSERT INTO test
(ID,Month) VALUES 
(0,'Mar'),
(1,'July'),
(2,'Jun'),
(3,'Aug');

since month column type is not clearly indicated as

Select name, alias, months, shortmonths
from   sys.syslanguages
where name='us_english'
namealiasmonthsshortmonths
us_englishEnglishJanuary,February,March,April,May,June,July,August,September,October,November,DecemberJan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec

and change it into

shortmonthfullName
JanJanuary
FebFebruary
MarMarch
AprApril
MayMay
JunJune
JulJuly
AugAugust
SepSeptember
OctOctober
NovNovember
DecDecember

by using string_split, row_number

SELECT shortmonth,
       fullname
FROM   (SELECT NAME,
               alias,
               months,
               shortmonths,
               a.value                     AS shortmonth,
               Row_number()
                 OVER (
                   ORDER BY (SELECT NULL)) rn
        FROM   (SELECT NAME,
                       alias,
                       months,
                       shortmonths
                FROM   sys.syslanguages
                WHERE  NAME = 'us_english') b
               CROSS apply String_split(shortmonths, ',') a) t1
       JOIN (SELECT NAME,
                    alias,
                    months,
                    shortmonths,
                    c.value                     fullName,
                    Row_number()
                      OVER (
                        ORDER BY (SELECT NULL)) rn
             FROM   (SELECT NAME,
                            alias,
                            months,
                            shortmonths
                     FROM   sys.syslanguages
                     WHERE  NAME = 'us_english') b
                    CROSS apply String_split(months, ',') c) t2
         ON t1.rn = t2.rn  

use above query in CTE and join it with your table with first three left character and then use EOMONTH and Right function as follows

SELECT t.*,
       m.fullname,
       RIGHT(Eomonth(( '01-' + m.fullname + '-2010' )), 5)
FROM   test t
       JOIN monthname1 m
         ON LEFT(t.month, 3) = m.shortmonth  

however using a proper year considering leap year should not be neglected.

dbfiddle

从SQL的另一列中得出1列的值

鸵鸟症 2025-02-17 08:43:01

对于具有简单值的简单,平坦的键/值对,请使用普通表。如果值只是true/false boolean值列可节省一些空间。

如果值可以是类型的混合(日期,数字,字符串,列表,嵌套键/值对) 。它可以被索引和搜索。

如果它们是正确索引,则一年数百万的条目并不多。 SQL数据库擅长处理大量数据。

For simple, flat key/value pairs with simple values, use a normal table. If the values are just true/false use boolean for the value column to save a little space.

If the values can be a mix of types (dates, numbers, strings, lists, nested key/value pairs) use the JSON type. It can be indexed and searched.

Millions of entries a year is not a lot if they are properly indexed. Handling large amounts of data is what SQL databases are good at.

正确存储许多键值对吗?

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文