摘星┃星的人

文章 评论 浏览 31

摘星┃星的人 2025-02-20 15:15:23

您只需要确保在创建/打开输出文件时指定相关编码。

import json

ls_dict = [
    { 'a': 'میلاد'},
    { 'b': 'علی'},
    { 'c': 'رضا'}
]

with open('j.json', 'w', encoding='utf-8') as j:
    j.write(json.dumps(ls_dict))

随后...

with open('j.json', encoding='utf-8') as j:
    j = json.load(j)
    print(j)

输出:

[{'a': 'میلاد'}, {'b': 'علی'}, {'c': 'رضا'}]

You just need to make sure you specify the relevant encoding when you create/open the output file.

import json

ls_dict = [
    { 'a': 'میلاد'},
    { 'b': 'علی'},
    { 'c': 'رضا'}
]

with open('j.json', 'w', encoding='utf-8') as j:
    j.write(json.dumps(ls_dict))

Subsequently...

with open('j.json', encoding='utf-8') as j:
    j = json.load(j)
    print(j)

Output:

[{'a': 'میلاد'}, {'b': 'علی'}, {'c': 'رضا'}]

如何制作dict Python列表的文本文件

摘星┃星的人 2025-02-20 13:13:27

我发现。

这是因为Maxfdlimit。

谢谢

I find about it.

It is because of MaxFDLimit.

Thanks

我的博客的软限制和硬限度相同

摘星┃星的人 2025-02-20 05:59:34

在以下方法中, UserId和rolename存储在角色表中

,我们检查表角色中给定角色的名称是否适用于所需人员,它将发送true:

private bool UserCheckInRole(int userId , string roleName)
{
   if(RoleTable.Where(role => role.roleName == roleName , role.UserId ==   
       userId).Any()) return true;
  return false;
}

[HttpGet]
public IActionResult DomSomething(string roleName = "")
{
    if(UserCheckInRole(userId , roleName){
        //true
    }
    // How can I know that user has a role here?
    return Ok();
}

UserId and RoleName are stored in the Role table

In the following method, we check if the name of the given role in Table Role is for the desired person, it will send true :

private bool UserCheckInRole(int userId , string roleName)
{
   if(RoleTable.Where(role => role.roleName == roleName , role.UserId ==   
       userId).Any()) return true;
  return false;
}

[HttpGet]
public IActionResult DomSomething(string roleName = "")
{
    if(UserCheckInRole(userId , roleName){
        //true
    }
    // How can I know that user has a role here?
    return Ok();
}

如何在ASP.NET Core中以编程方式检查该用户在角色中处于角色?

摘星┃星的人 2025-02-19 23:10:16

事件驱动的功能可能由于功能代码本身丢弃的错误而无法成功完成。可能发生的一些原因如下:

  • 该函数包含一个错误,并且运行时会引发异常。
  • 该函数无法达到服务端点,或者在
    试图到达端点。
  • 该功能有意抛出异常(例如,当
    参数失败验证)。
  • 当用node.js编写功能时,返回拒绝的承诺或通过
    呼叫的非零值。

在上述任何情况下,默认情况下该函数停止执行,并且事件被丢弃。如果要在发生错误时重试函数,则可以通过属性。这会导致该事件重复进行多达多天,直到该功能成功完成为止。

在此问题中,服务端点'api-football-v1.p.rapidapi.com/v3'本身花了很多时间来加载(不可到达),这就是问题所在。将API端点更改为 v3.football.api-sports.io ,然后调用Firebase功能中的外部API为我们的用户解决了问题@TATE_XY

An event-driven function may fail to successfully complete due to errors thrown in the function code itself. Some of the reasons this might happen are as follows:

  • The function contains a bug and the runtime throws an exception.
  • The function cannot reach a service endpoint, or times out while
    trying to reach the endpoint.
  • The function intentionally throws an exception (for example, when a
    parameter fails validation).
  • When functions written in Node.js return a rejected promise or pass a
    non-null value to a callback.

In any of the above cases, the function stops executing by default and the event is discarded. If you want to retry the function when an error occurs, you can change the default retry policy by setting the "retry on failure" property. This causes the event to be retried repeatedly for up to multiple days until the function successfully completes.

In this question, the service endpointi ‘api-football-v1.p.rapidapi.com/v3’ itself took so much time to load ( not reachable ), that was the issue. Changing the API endpoint to v3.football.api-sports.io and then calling the external API in Firebase Functions solved the issue for our user @tate_xy

调用外部API时的firebase函数超时

摘星┃星的人 2025-02-19 19:51:04

这看起来像剃须刀页面,在这种情况下,评论是错误的:简单地调用返回将将页面发送到浏览器。

相反,您应该返回 iActionResult ,如下:

public IActionResult OnGet()
{
    string id = Request.Query["id"];
    if (!int.TryParse(id, out int value) || value == 0)
    {
        return new RedirectResult("/Clients/Index");        
    }
    try                                         
    {
        using (SqlConnection connection = new(connectionString))
        {
            connection.Open();
            string sql = "SELECT * FROM clients WHERE id = @id";

            using (SqlCommand command = new(sql, connection))

     //etc........ 
    return Page();
}

现在您可以重定向并结束响应或返回页面。

This looks like a Razor page, in which case the comments are wrong: Simply calling return will send the page to the browser.

Instead you should return an IActionResult, like this:

public IActionResult OnGet()
{
    string id = Request.Query["id"];
    if (!int.TryParse(id, out int value) || value == 0)
    {
        return new RedirectResult("/Clients/Index");        
    }
    try                                         
    {
        using (SqlConnection connection = new(connectionString))
        {
            connection.Open();
            string sql = "SELECT * FROM clients WHERE id = @id";

            using (SqlCommand command = new(sql, connection))

     //etc........ 
    return Page();
}

Now you can redirect and end response or return the page.

响应后。redirect(),代码继续执行

摘星┃星的人 2025-02-19 04:14:50

您可以简单地使用:

 WHERE amount > 0 

You can simply use:

 WHERE amount > 0 

SQL如何表达“不等于和不少于”

摘星┃星的人 2025-02-18 14:03:28

正如@brujobenavides在评论中所建议的那样,您可以链接 。如果其中一个链接过程终止,则ERLANG VM将自动终止所有其他链接过程。参见参考手册“从“学习一些erlang for for for Great Good” 以获取更多详细信息。

在您的示例中,更改 spawner/2 使用 spawn_link/3 而不是 spawn/3

spawner(N, Nring) ->
    Pid = spawn_link(r, processes, [Nring]),
    spawner(N - 1, Pid).

此方式 loop/loop/1 不需要再传播 {停止,PID}

loop(Nring) ->
    receive
        { stop, From } ->
            io:format("~w received stop from ~w\n", [self(), From]),
            %% All linked processes will be terminated
            %% once we break out the loop/1
            ok;

请注意,在您的示例中,中央进程产卵其他过程也是戒指的一部分。这意味着a)每当另一个环中的一个过程中的一个和b)当中央进程死亡时,它也将被终止。

您可以通过不链接 self()来避免这种情况:

spawner(N, Nring) ->
    if Nring == self() ->
        Pid = spawn(r, processes, [Nring]);
    true ->
        Pid = spawn_link(r, processes, [Nring])
    end,
    spawner(N - 1, Pid).

As was suggested by @BrujoBenavides in a comment, you can link all processes in the ring. If one of the linked processes terminates, Erlang VM will automatically terminate all other linked processes. See the reference manual and a chapter from "Learn You Some Erlang for great good" for more details.

In your example change spawner/2 to use spawn_link/3 instead of spawn/3:

spawner(N, Nring) ->
    Pid = spawn_link(r, processes, [Nring]),
    spawner(N - 1, Pid).

This way loop/1 does not need to propagate { stop, Pid } anymore:

loop(Nring) ->
    receive
        { stop, From } ->
            io:format("~w received stop from ~w\n", [self(), From]),
            %% All linked processes will be terminated
            %% once we break out the loop/1
            ok;

Note that in your example the Central Process spawning other processes is also part of the ring. This means that a) it will also be terminated whenever one of the other ring processes dies and b) the whole process ring will be terminated when the Central Process dies.

You can avoid this by not linking self():

spawner(N, Nring) ->
    if Nring == self() ->
        Pid = spawn(r, processes, [Nring]);
    true ->
        Pid = spawn_link(r, processes, [Nring])
    end,
    spawner(N - 1, Pid).

当将杀戮消息发送到任何其他过程必须死亡的过程时,有没有办法修改?

摘星┃星的人 2025-02-18 13:25:14

使用基础r

mydata["last_date"] <- apply(mydata[,-1],1,max, na.rm=T)
  ID      Date1 Date2      Date3      Date4  last_date
1  1       <NA>    NA 2022-02-08       <NA> 2022-02-08
2  2       <NA>    NA       <NA>       <NA>       <NA>
3  3 2022-06-10    NA       <NA> 2022-06-24 2022-06-24
4  4       <NA>    NA       <NA>       <NA>       <NA>
5  5       <NA>    NA       <NA> 2022-05-13 2022-05-13

Using base R

mydata["last_date"] <- apply(mydata[,-1],1,max, na.rm=T)
  ID      Date1 Date2      Date3      Date4  last_date
1  1       <NA>    NA 2022-02-08       <NA> 2022-02-08
2  2       <NA>    NA       <NA>       <NA>       <NA>
3  3 2022-06-10    NA       <NA> 2022-06-24 2022-06-24
4  4       <NA>    NA       <NA>       <NA>       <NA>
5  5       <NA>    NA       <NA> 2022-05-13 2022-05-13

如何使用可用的最后日期创建变量

摘星┃星的人 2025-02-18 08:27:31

如果这种格式可以适合您,则代码为PowerQuery。否则请说明为什么需要Code3,以及一行使用code3而不是示例中的Code2

let  Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"ID", Int64.Type}, {"Name", type text}, {"Proportion", Int64.Type}, {"%", type number}}),
#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Changed Type", {"ID", "Name"}, "Attribute", "Value"),
#"Grouped Rows" = Table.Group(#"Unpivoted Other Columns", {"ID"}, {{"data", each 
    Table.AddColumn(
        Table.TransformColumns(
            Table.AddIndexColumn(_, "Index", 2, 1, Int64.Type)
        ,{{"Index", each Number.IntegerDivide(_, 2), Int64.Type}})
    , "Header", each if [Attribute]="Proportion" then "Code " &Text.From([Index]) else "Code " &Text.From([Index]) & "%"
    ), type table}}),
#"Expanded data" = Table.ExpandTableColumn(#"Grouped Rows", "data", {"Name", "Value",  "Header"}, {"Name", "Value", "Header"}),
#"Pivoted Column" = Table.Pivot(#"Expanded data", List.Distinct(#"Expanded data"[Header]), "Header", "Value")
in  #"Pivoted Column"

If this format it ok for you, code is below for Powerquery. Otherwise explain why Code3 is needed, and when a row would use Code3 as opposed to Code2 in your sample

enter image description here

let  Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"ID", Int64.Type}, {"Name", type text}, {"Proportion", Int64.Type}, {"%", type number}}),
#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Changed Type", {"ID", "Name"}, "Attribute", "Value"),
#"Grouped Rows" = Table.Group(#"Unpivoted Other Columns", {"ID"}, {{"data", each 
    Table.AddColumn(
        Table.TransformColumns(
            Table.AddIndexColumn(_, "Index", 2, 1, Int64.Type)
        ,{{"Index", each Number.IntegerDivide(_, 2), Int64.Type}})
    , "Header", each if [Attribute]="Proportion" then "Code " &Text.From([Index]) else "Code " &Text.From([Index]) & "%"
    ), type table}}),
#"Expanded data" = Table.ExpandTableColumn(#"Grouped Rows", "data", {"Name", "Value",  "Header"}, {"Name", "Value", "Header"}),
#"Pivoted Column" = Table.Pivot(#"Expanded data", List.Distinct(#"Expanded data"[Header]), "Header", "Value")
in  #"Pivoted Column"

转换数据 - excel

摘星┃星的人 2025-02-17 22:10:17

您可以编写一个汇总查询来做到这一点。

  1. 使用 $ group 带有 $ sum 来计算总和
  2. 的ID密钥
db.collection.aggregate({
  $group: {
    _id: "",
    num: {
      $sum: "$num"
    },
    count: {
      $sum: "$count"
    }
  }
},
{
  $project: {
    _id: 0,
    num: "$num",
    count: "$count"
  }
})

投影的 $ project 操作员删除$ group oterator Playground链接

You can write an aggregate query to do that.

  1. Use $group with $sum to calculate the sum
  2. Use projection's $project operator to remove the id key required by the $group operator
db.collection.aggregate({
  $group: {
    _id: "",
    num: {
      $sum: "$num"
    },
    count: {
      $sum: "$count"
    }
  }
},
{
  $project: {
    _id: 0,
    num: "$num",
    count: "$count"
  }
})

Playground link

如何将多个文档添加到MongoDB中的一个文档中?

摘星┃星的人 2025-02-17 20:25:19

这是一个示例,说明如何使用Python标准库 difflib 模块,它提供了用于计算三角洲的帮助者。

给定以下玩具数据框和搜索句子:

import pandas as pd

df = pd.DataFrame(
    {
        "document": ["doc 1", "doc 2"],
        "sentences": [
            ["lore ipsum", "magna carta", "upside down"],
            ["tempus fugit", "memento mori", "lora ipsom"],
        ],
    }
)
search_sentence = "lor ipsum"

定义一个辅助功能以比较句子的相似性:

from difflib import SequenceMatcher

def ratio(a, b):
    return round(SequenceMatcher(None, a, b).ratio(), 2)

然后:

# Use Python instead of Pandas
df = df.to_dict(orient="list")

# Init empty dictionary
results = {"Matching sentence": [], "similarity score": [], "document name": []}

# Iterate to compare
for (doc, sentences) in zip(df["document"], df["sentences"]):
    for i, sentence in enumerate(sentences):
        results["Matching sentence"].append(f"Sentence {i+1}")
        results["similarity score"].append(ratio(search_sentence, sentence))
        results["document name"].append(doc)

最后:

new_df = (
    pd.DataFrame(results)
    .sort_values(by="similarity score", ascending=False)
    .reset_index(drop=True)
)

print(new_df)
# Ouptut
  Matching sentence  similarity score document name
0        Sentence 1              0.95         doc 1
1        Sentence 3              0.84         doc 2
2        Sentence 2              0.29         doc 2
3        Sentence 3              0.20         doc 1
4        Sentence 1              0.19         doc 2
5        Sentence 2              0.10         doc 1

Here is an example of how you can do it using Python standard library difflib module, which provides helpers for computing deltas.

Given the following toy dataframe and search sentence:

import pandas as pd

df = pd.DataFrame(
    {
        "document": ["doc 1", "doc 2"],
        "sentences": [
            ["lore ipsum", "magna carta", "upside down"],
            ["tempus fugit", "memento mori", "lora ipsom"],
        ],
    }
)
search_sentence = "lor ipsum"

Define a helper function to compare sentences similarity:

from difflib import SequenceMatcher

def ratio(a, b):
    return round(SequenceMatcher(None, a, b).ratio(), 2)

And then:

# Use Python instead of Pandas
df = df.to_dict(orient="list")

# Init empty dictionary
results = {"Matching sentence": [], "similarity score": [], "document name": []}

# Iterate to compare
for (doc, sentences) in zip(df["document"], df["sentences"]):
    for i, sentence in enumerate(sentences):
        results["Matching sentence"].append(f"Sentence {i+1}")
        results["similarity score"].append(ratio(search_sentence, sentence))
        results["document name"].append(doc)

Finally:

new_df = (
    pd.DataFrame(results)
    .sort_values(by="similarity score", ascending=False)
    .reset_index(drop=True)
)

print(new_df)
# Ouptut
  Matching sentence  similarity score document name
0        Sentence 1              0.95         doc 1
1        Sentence 3              0.84         doc 2
2        Sentence 2              0.29         doc 2
3        Sentence 3              0.20         doc 1
4        Sentence 1              0.19         doc 2
5        Sentence 2              0.10         doc 1

如何在数据框中找到大多数类似的字符串值?

摘星┃星的人 2025-02-17 19:26:16

替换第4行

&lt;%包括partials/head.ejs%&gt; with&lt;% - 包括('partials/head.ejs'); %&gt;

和83

&lt;%包括partials/footer.ejs%&gt; with&lt;% - 包括('partials/footer.ejs'); %&gt;

Replace line 4

<% include partials/head.ejs %> with <%- include('partials/head.ejs'); %>

and line 83

<% include partials/footer.ejs %> with <%- include('partials/footer.ejs'); %>

运行.EJS文件时,我会一直遇到错误,是我的代码中的错误还是程序中的其他位置?我该如何解决?

摘星┃星的人 2025-02-17 19:06:39

Luxon的工具是间隔,它具有重叠()

const fromISOs = (start, end) => {
  const startDt = luxon.DateTime.fromISO(start);
  const endDt = luxon.DateTime.fromISO(end);
  return luxon.Interval.fromDateTimes(startDt, endDt);
};

const assignment = fromISOs('2022-06-26T12:00:00.000Z', '2022-06-26T12:30:00.000Z');

const ranges = [
 ['2022-06-26T10:00:00.000Z', '2022-06-26T10:30:00.000Z'],
 ['2022-06-26T10:35:00.000Z', '2022-06-26T11:00:00.000Z'],
 ['2022-06-26T11:45:00.000Z', '2022-06-26T12:15:00.000Z'],
 ['2022-06-26T12:10:00.000Z', '2022-06-26T12:25:00.000Z'],
 ['2022-06-26T12:20:00.000Z', '2022-06-26T12:45:00.000Z'],
 ['2022-06-26T12:40:00.000Z', '2022-06-26T13:00:00.000Z']
];

 ranges
   .map(([start, end]) => fromISOs(start, end)) // create intervals
   .filter(i => !i.overlaps(assignment)) // filter out the overlaps
   .forEach(i => console.log(i.toISO())) // print the interval ISO (you don't have to do this)
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.4.0/luxon.min.js"></script>

Luxon's tool for this is the Interval, which has overlaps()

const fromISOs = (start, end) => {
  const startDt = luxon.DateTime.fromISO(start);
  const endDt = luxon.DateTime.fromISO(end);
  return luxon.Interval.fromDateTimes(startDt, endDt);
};

const assignment = fromISOs('2022-06-26T12:00:00.000Z', '2022-06-26T12:30:00.000Z');

const ranges = [
 ['2022-06-26T10:00:00.000Z', '2022-06-26T10:30:00.000Z'],
 ['2022-06-26T10:35:00.000Z', '2022-06-26T11:00:00.000Z'],
 ['2022-06-26T11:45:00.000Z', '2022-06-26T12:15:00.000Z'],
 ['2022-06-26T12:10:00.000Z', '2022-06-26T12:25:00.000Z'],
 ['2022-06-26T12:20:00.000Z', '2022-06-26T12:45:00.000Z'],
 ['2022-06-26T12:40:00.000Z', '2022-06-26T13:00:00.000Z']
];

 ranges
   .map(([start, end]) => fromISOs(start, end)) // create intervals
   .filter(i => !i.overlaps(assignment)) // filter out the overlaps
   .forEach(i => console.log(i.toISO())) // print the interval ISO (you don't have to do this)
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.4.0/luxon.min.js"></script>

如何在特定时间间隔范围之外过滤ISO DateTime对象

摘星┃星的人 2025-02-17 11:21:49
let attributeService = widgetContext.$injector.get(widgetContext.servicesMap.get('attributeService'));

let attributes = [{
    "key": YOUR_ATTRIBUTE_KEY,
    "value": YOUR_ATTRIBUTE_VALUE
}];
attributeService.saveEntityAttributes(entityId, 'SERVER_SCOPE', attributes).
    subscribe(
        () => {
            console.log('Saved!');
        },
        error => {
            console.log('Error');
        }
    );
let attributeService = widgetContext.$injector.get(widgetContext.servicesMap.get('attributeService'));

let attributes = [{
    "key": YOUR_ATTRIBUTE_KEY,
    "value": YOUR_ATTRIBUTE_VALUE
}];
attributeService.saveEntityAttributes(entityId, 'SERVER_SCOPE', attributes).
    subscribe(
        () => {
            console.log('Saved!');
        },
        error => {
            console.log('Error');
        }
    );

物品板如何使用窗口小部件中的自定义&#xa0; Action选项更改服务器属性

摘星┃星的人 2025-02-17 04:13:29

使用 dense_rank()按列订购

SELECT Column,
       DENSE_RANK() OVER (ORDER BY Column) AS 'Desire'
FROM mytable;

return

aaaaaaa desires drees
1 aaaaaaa
1 aaaaaa 1
aaaaaa 1
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb bbbbbb 2
bbbbbbb bbbbb
cccccc 2
3 cccccc 3
ccccc 3

使用 row_number(row_number(Row_number)( )按列分区

SELECT Column,
       ROW_NUMBER() OVER (PARTITION BY Column) AS 'Desire'
FROM mytable;

返回:

欲望
AAAAAA 1
AAAAAA 2
AAAAAA 2 AAAAAA 3
BBBBBBB 1
BBBBBBB 2
BBBBBB 2 BBBBBBB 3
BBBBBBB BBBBBB 4
CCCCCC 1
CCCCCC 2 CCCCCC 2

Using DENSE_RANK() function with ORDER BY Column:

SELECT Column,
       DENSE_RANK() OVER (ORDER BY Column) AS 'Desire'
FROM mytable;

returns:

Column Desire
AAAAAA 1
AAAAAA 1
AAAAAA 1
BBBBBB 2
BBBBBB 2
BBBBBB 2
CCCCCC 3
CCCCCC 3

Using ROW_NUMBER() function with PARTITION BY Column:

SELECT Column,
       ROW_NUMBER() OVER (PARTITION BY Column) AS 'Desire'
FROM mytable;

returns:

Column Desire
AAAAAA 1
AAAAAA 2
AAAAAA 3
BBBBBB 1
BBBBBB 2
BBBBBB 3
BBBBBB 4
CCCCCC 1
CCCCCC 2

mySQL更新序列重复值

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

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