拔了角的鹿

文章 评论 浏览 29

拔了角的鹿 2025-02-20 22:20:09

实际上问题是类型列表< map< string,object>>您正在访问类型对象的问题[index] [“答案”],因此不能用作列表< map< string,objecct>>

actually questions is a type List<Map<String,Object>> and you are accessing questions[index]["Answers"] which is of type Object so it can not be used as List<Map<String,Objecct>>

type; list&lt; object&gt;&#x27;不是类型的子类型&#x27; list&lt; string,object&gt;&gt;&gt;&#x27;在类型中

拔了角的鹿 2025-02-20 18:53:12

使函数通用

func multiplier<T: Numeric>(_ a:T, _ b:T) -> T {
 if a == 0 || b == 0 {
  return 0
 }
 return a+multiplier(a,b-1)
}

相同的实现

Make the function generic

func multiplier<T: Numeric>(_ a:T, _ b:T) -> T {
 if a == 0 || b == 0 {
  return 0
 }
 return a+multiplier(a,b-1)
}

Same implementation

如何使用通用类执行递归方法

拔了角的鹿 2025-02-20 18:02:42

您可以使用split(“ _”),并以[-1]作为列的新名称获取最后一个元素

>>>string="MAC0999_STD_F_ColumnName"
>>>string.split("_") 
['MAC0999', 'STD','F', 'ColumnName'] 
>>>NewColumnName=string.split("_")[-1] 
>>>NewColumnName
'ColumnName'´

You can use split("_") and get the last element with [-1] as the new name of your column

>>>string="MAC0999_STD_F_ColumnName"
>>>string.split("_") 
['MAC0999', 'STD','F', 'ColumnName'] 
>>>NewColumnName=string.split("_")[-1] 
>>>NewColumnName
'ColumnName'´

如果包含特定文本,如何更改列的名称

拔了角的鹿 2025-02-20 11:37:35

利用Linq! .sum()将添加您集合中的所有内容。您可以运行两次,每个切片一次,每个小计的一次。

var input = new [] { 1, 2, 2, 3, 6 };
var totalSum = Enumerable.Range(1, input.Length).Sum(len => input[0..len].Sum());
// totalSum is 31

enumerable.range 为您提供(以及)1和5之间的数字集合 - 子阵列的每个切片的可能长度。然后,您使用范围运算符 [0 ..#] 获得越来越大的切片。

是的,这不像Aminrd的解决方案那么聪明 - 它正在手动进行所有计算,并且您正在执行许多切片。

Take advantage of Linq! .Sum() will add up everything in your collection. You run that twice, once per each slice, and once per each subtotal.

var input = new [] { 1, 2, 2, 3, 6 };
var totalSum = Enumerable.Range(1, input.Length).Sum(len => input[0..len].Sum());
// totalSum is 31

Enumerable.Range gets you a collection of numbers between (and including) 1 and 5 - the possible lengths of each slice of your sub arrays. You then use the range operator [0..#] to get increasingly larger slices.

Yes, this is not as clever as aminrd's solution - it's doing all the computations manually and you're performing many slices.

c#数组中的总和

拔了角的鹿 2025-02-20 05:02:57

您正在遇到 innerhtml 查找元素的麻烦。您正在传递狮子,但是交换语句期望狮子。这将永远不会评估 audio.play 案例。

建议的解决方案是在 InnerHtml 字符串上调用 tolowercase(),以便它们匹配。当前使用您的堆栈片段 querySelector 因此,因此没有返回任何元素。

var buttonInnerHTML = this.innerHTML.toLowerCase();

You are getting into trouble with the innerHTML lookup of the elements. You are passing in Lion but the switch statement is expecting lion. This will never evaluate to the audio.play cases.

Suggested solution would be to call toLowerCase() on the innerHTML strings so that they will match. Currently with your stack snippet the querySelector isn't returning any elements because of this.

var buttonInnerHTML = this.innerHTML.toLowerCase();

JavaScript声音和对按钮不起作用的效果单击

拔了角的鹿 2025-02-20 02:02:38

像解决方案一样,您需要为计数本机查询指定返回类型。

可以通过

JPA版本1.0和2.0

<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings version="2.0" xmlns="http://java.sun.com/xml/ns/persistence/orm"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm
        http://java.sun.com/xml/ns/persistence/orm_2_0.xsd ">

    <named-native-query name="Person.findPeople.count" result-set-mapping="cntColumnResult">
        <query>select count(*) cnt from person</query>
    </named-native-query>

    <named-native-query name="Person.findPeople">
        <query>select first_name, last_name from person</query>
    </named-native-query>

    <sql-result-set-mapping name="cntColumnResult">
        <column-result name="cnt"/>
    </sql-result-set-mapping>

</entity-mappings>

JPA版本2.1

将您的映射配置推向 entity-mappings版本=“ 2.1”

<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence/orm"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence/orm
    http://xmlns.jcp.org/xml/ns/persistence/orm_2_1.xsd">

    <named-native-query name="Person.findPeople.count" result-set-mapping="cntColumnResult">
        <query>select count(*) cnt from person</query>
    </named-native-query>

    <named-native-query name="Person.findPeople">
        <query>select first_name, last_name from person</query>
    </named-native-query>

    <sql-result-set-mapping name="cntColumnResult">
        <column-result name="cnt" class="java.lang.Long"/>
    </sql-result-set-mapping>

</entity-mappings>

,或者

<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence/orm"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence/orm
    http://xmlns.jcp.org/xml/ns/persistence/orm_2_1.xsd">

    <named-native-query name="Person.findPeople.count" result-set-mapping="cntConstructorResult">
        <query>select count(*) cnt from person</query>
    </named-native-query>

    <named-native-query name="Person.findPeople">
        <query>select first_name, last_name from person</query>
    </named-native-query>

    <sql-result-set-mapping name="cntConstructorResult">
        <constructor-result target-class="java.lang.Long">
            <column name="cnt" class="java.lang.Long"/>
        </constructor-result>
    </sql-result-set-mapping>

</entity-mappings>

我认为这是一个缺陷或可能是 spring-data-jpa 有问题的源代码行

countQuery = em.createNamedQuery(countQueryName, Long.class);

如果在查询创建期间不会传递 long.class 类型,则无需在映射配置中指定计数查询的精确类型。在这种情况下,Hibernate运作良好。

可能的解决方案的示例为本机创建原始查询,而不是键入:

        Query query = getQueryMethod().isNativeQuery()
                ? em.createNativeQuery(queryString)
                : em.createQuery(queryString, Long.class);

因此,如果您有时间,请为Spring-Data-JPA项目发布新问题,因此,这种小的查询校正将显着简化映射配置。

Like solution you need to specify the return type for your count native query.

It can be done via sql-result-set-mapping.

JPA version 1.0 and 2.0

<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings version="2.0" xmlns="http://java.sun.com/xml/ns/persistence/orm"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm
        http://java.sun.com/xml/ns/persistence/orm_2_0.xsd ">

    <named-native-query name="Person.findPeople.count" result-set-mapping="cntColumnResult">
        <query>select count(*) cnt from person</query>
    </named-native-query>

    <named-native-query name="Person.findPeople">
        <query>select first_name, last_name from person</query>
    </named-native-query>

    <sql-result-set-mapping name="cntColumnResult">
        <column-result name="cnt"/>
    </sql-result-set-mapping>

</entity-mappings>

JPA version 2.1

Move forward your mapping config to entity-mappings version="2.1"

<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence/orm"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence/orm
    http://xmlns.jcp.org/xml/ns/persistence/orm_2_1.xsd">

    <named-native-query name="Person.findPeople.count" result-set-mapping="cntColumnResult">
        <query>select count(*) cnt from person</query>
    </named-native-query>

    <named-native-query name="Person.findPeople">
        <query>select first_name, last_name from person</query>
    </named-native-query>

    <sql-result-set-mapping name="cntColumnResult">
        <column-result name="cnt" class="java.lang.Long"/>
    </sql-result-set-mapping>

</entity-mappings>

OR

<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence/orm"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence/orm
    http://xmlns.jcp.org/xml/ns/persistence/orm_2_1.xsd">

    <named-native-query name="Person.findPeople.count" result-set-mapping="cntConstructorResult">
        <query>select count(*) cnt from person</query>
    </named-native-query>

    <named-native-query name="Person.findPeople">
        <query>select first_name, last_name from person</query>
    </named-native-query>

    <sql-result-set-mapping name="cntConstructorResult">
        <constructor-result target-class="java.lang.Long">
            <column name="cnt" class="java.lang.Long"/>
        </constructor-result>
    </sql-result-set-mapping>

</entity-mappings>

I think this is a defect or possibly a new feature in spring-data-jpa. Problematic source code line.

countQuery = em.createNamedQuery(countQueryName, Long.class);

If Long.class type will not be passed during query creation we will not need to specify an exact type for the count query in the mapping config. Hibernate is working well in this case.

Example of possible solution create raw query for native instead of typed:

        Query query = getQueryMethod().isNativeQuery()
                ? em.createNativeQuery(queryString)
                : em.createQuery(queryString, Long.class);

So if you have time please post a new issue for spring-data-jpa project, such a small query correction will significantly simplify the mapping config.

使用本机查询时的Hibernate分页不起作用(存在命名查询,但其结果类型不兼容)

拔了角的鹿 2025-02-19 23:25:56

通过更改 a 中的类属性,每次对象都会在本地进行 a 的更改,就有一种非常丑陋的方法来完成您想要的事情:

class A:
    additional_amount = 0

    def __init__(self, amount):
        self.amount = amount
        self.local_additional_amount = A.additional_amount  # Remember the "context" at creation time

    def __add__(self, other):
        return self.amount + other.amount + self.local_additional_amount


class B:
    def __init__(self, added_amount):
        self.added_amount = added_amount
        self.old_additional_amount = A.additional_amount  # Could be in `__enter__`, for a slightly different behaviour

    def __enter__(self):
        # Change the additional amount for A's created inside this context
        A.additional_amount = self.added_amount
        return self

    def __exit__(self, exc_type, exc_value, exc_traceback):
        # Restore As original amount, so we can nest it:
        A.additional_amount = self.old_additional_amount

此方法使您的示例通过,甚至可以使用嵌套上下文:

if __name__ == '__main__':
    # Test default behaviour:
    assert (A(2) + A(3)) == 5

    # Simple context (example requested by OP):
    with B(1000):
        assert (A(1) + A(5)) == 1006

    # Test default behaviour is restored:
    assert (A(1) + A(5)) == 6

    # Nested contexts work
    with B(1000):
        with B(2000):
            assert (A(1) + A(5)) == 2006
        # Out of the '2000' context
        assert (A(1) + A(5)) == 1006
    assert (A(1) + A(5)) == 6

请注意,在此实施中,上下文是在创建时记录的,因此您可能会得到令人惊讶的行为:

    with B(1000):
        a = A(1)
    with B(2000):
        b = A(1)
    assert (a + b) == 1002  # `a` adds 1000
    assert (b + a) == 2002  # but `b` adds 2000

可以使每个实例 a 获取当前上下文是在 __添加__ 方法中,通过直接使用 a.additional_amount

无论如何,请,不要将其用作语言难题。这是非常令人惊讶的行为,并且违背了“显式胜于隐式”的python哲学。由于它基本上使用了一个全局变量,因此它将在任何类型的并发或上下文切换案例中破裂(例如,在 yarts s内部的函数中。

顺便说一句,某些语言实现了与您想要的非常相似的功能。例如,看看上下文参数例如,在Scala中。

There is a very ugly way to do what you want, by changing a class attribute in A that is copied locally every time an object is instantiated:

class A:
    additional_amount = 0

    def __init__(self, amount):
        self.amount = amount
        self.local_additional_amount = A.additional_amount  # Remember the "context" at creation time

    def __add__(self, other):
        return self.amount + other.amount + self.local_additional_amount


class B:
    def __init__(self, added_amount):
        self.added_amount = added_amount
        self.old_additional_amount = A.additional_amount  # Could be in `__enter__`, for a slightly different behaviour

    def __enter__(self):
        # Change the additional amount for A's created inside this context
        A.additional_amount = self.added_amount
        return self

    def __exit__(self, exc_type, exc_value, exc_traceback):
        # Restore As original amount, so we can nest it:
        A.additional_amount = self.old_additional_amount

This method makes your example pass, and can even use nested contexts:

if __name__ == '__main__':
    # Test default behaviour:
    assert (A(2) + A(3)) == 5

    # Simple context (example requested by OP):
    with B(1000):
        assert (A(1) + A(5)) == 1006

    # Test default behaviour is restored:
    assert (A(1) + A(5)) == 6

    # Nested contexts work
    with B(1000):
        with B(2000):
            assert (A(1) + A(5)) == 2006
        # Out of the '2000' context
        assert (A(1) + A(5)) == 1006
    assert (A(1) + A(5)) == 6

Note that, in this implementation, the context is recorded at the time of creation, so you may get surprising behaviour:

    with B(1000):
        a = A(1)
    with B(2000):
        b = A(1)
    assert (a + b) == 1002  # `a` adds 1000
    assert (b + a) == 2002  # but `b` adds 2000

It is possible to make every instance of A fetch the current context it is in, by using directly A.additional_amount in the __add__ method.

In any case, please, never use it as anything more than a language puzzle. It is very surprising behaviour and goes against the Python philosophy of "Explicit is better than Implicit". As it uses essentially a global variable, it will break badly in any kind of concurrency or context switching cases (such as in a function that yields from inside a B context).

As an aside, some languages implement a feature very similar to what you want. Have a look at context parameters in Scala, for example.

通过上下文管理器调整第二类的行为

拔了角的鹿 2025-02-19 20:26:59

您可以合并一个文件中的所有4个文件。我建议使用两条空行的分离,因为这样,您可以通过 index 轻松地解决(sub)Datablocks,请检查 help Index

对于标签,您可以制作双循环,一个用于(子)数据锁,一个用于列。您必须总结列(检查 help sum )才能计算标签的y位(即直方图元素的中心)。标签的X位置对于第一个数据集很特别(因为只有列列),因此可以考虑(i*3+$ 0-(i == 0)), IE i == 0 如果我等于0,则返回1,否则将返回1。

您可能想在终端设置大型字体大小,而不是多次设置它,例如:设置术语pngcairo字体“,17”

在下面找到最小化的示例,作为进一步优化的起点。

脚本:

### rowstacked histogram with numbers in corresponding boxes
reset session

$Data <<EOD
# base_vs_FHA_1core.dat
col1 col2 col3 col4 col5
Base 5 50 40.5 4.5
FHA  5 16 38 5 1.54x


# base_vs_FHA_2core.dat
Base 9.3 47 37.3 6.3
FHA  9.3 15 34.3 6.3 1.54x


# base_vs_FHA_4core.dat
Base 18   41    33.9 7.06
FHA  16.6 13.07 30.7 7.4  1.47x


# base_vs_FHA_8core.dat
Base 27.7 34.3  28.3 9.6
FHA  28.3 11.45 25.3 9.6 1.34x
EOD

set xlabel "Number of Cores"
set ylabel "Time (%)"
set yrange [0:130]
set ytics 0, 10, 100
set grid

set style data histogram
set style histogram rowstacked title
set style fill solid 0.5 border lt -1
set boxwidth 0.9
set key top left noautotitle horizontal

N = 5   # number of last data column

plot newhistogram '1-Core' at 0, \
        for [i=2:N] $Data index 0 u i:xtic(1) ti columnheader, \
     newhistogram '2-Cores' lt 1 at 3, \
        for [i=2:N] '' index 1 u i:xtic(1), \
     newhistogram '4-Cores' lt 1 at 6, \
        for [i=2:N] '' index 2 u i:xtic(1), \
     newhistogram '8-Cores' lt 1 at 9, \
        for [i=2:N] '' index 3 u i:xtic(1), \
    for [i=0:3] for [j=2:N] '' index i u (i*3+$0-(i==0)): \
        ((sum [k=2:j] column(k))-column(j)*0.5):j w labels
### end of script

结果:

“在此处输入图像说明”

You can merge all 4 files in one file. I would recommend a separation with two empty lines, because with this, you can easily address the (sub)datablocks via index, check help index.

For the labels you can make a double loop, one for the (sub)datablocks and one for the columns. You have to sum up the columns (check help sum) to calculate the y-position of the label (i.e. center of the histogram element). The x-position of the labels is special for the first dataset (since only this has a columnheader), this is taken into account with (i*3+$0-(i==0)), i.e. i==0 will return 1 if i equals 0, and 0 otherwise.

Instead of setting a large fontsize many times you might want to set it in the terminal, e.g. something like: set term pngcairo font ",17".

Find below a minimized example as a starting point for further optimization.

Script:

### rowstacked histogram with numbers in corresponding boxes
reset session

$Data <<EOD
# base_vs_FHA_1core.dat
col1 col2 col3 col4 col5
Base 5 50 40.5 4.5
FHA  5 16 38 5 1.54x


# base_vs_FHA_2core.dat
Base 9.3 47 37.3 6.3
FHA  9.3 15 34.3 6.3 1.54x


# base_vs_FHA_4core.dat
Base 18   41    33.9 7.06
FHA  16.6 13.07 30.7 7.4  1.47x


# base_vs_FHA_8core.dat
Base 27.7 34.3  28.3 9.6
FHA  28.3 11.45 25.3 9.6 1.34x
EOD

set xlabel "Number of Cores"
set ylabel "Time (%)"
set yrange [0:130]
set ytics 0, 10, 100
set grid

set style data histogram
set style histogram rowstacked title
set style fill solid 0.5 border lt -1
set boxwidth 0.9
set key top left noautotitle horizontal

N = 5   # number of last data column

plot newhistogram '1-Core' at 0, \
        for [i=2:N] $Data index 0 u i:xtic(1) ti columnheader, \
     newhistogram '2-Cores' lt 1 at 3, \
        for [i=2:N] '' index 1 u i:xtic(1), \
     newhistogram '4-Cores' lt 1 at 6, \
        for [i=2:N] '' index 2 u i:xtic(1), \
     newhistogram '8-Cores' lt 1 at 9, \
        for [i=2:N] '' index 3 u i:xtic(1), \
    for [i=0:3] for [j=2:N] '' index i u (i*3+$0-(i==0)): \
        ((sum [k=2:j] column(k))-column(j)*0.5):j w labels
### end of script

Result:

enter image description here

如何在每个栏中使用值标签的GNUPLOT中绘制划船堆的直方图

拔了角的鹿 2025-02-19 16:25:22

看起来像是弹力弹力的SDK中的一个问题,我已经创建了一个问题: https:https:https:https:https: //github.com/getsentry/sentry-dart/issues/942

同时,解决方法可能正在设置操作系统在当前范围的上下文中手动: https://pub.dev/documentation/sentry/latest/sentry_io/contexts/operatingsystem.html

这样的事情可以起作用(不进行测试):

import 'dart:io' show Platform;

if (Platform.isIOS) {
  Sentry.configureScope((scope) => scope.setContexts('os', {
    'name': Platform.operatingSystem
  }));
}

Looks like an issue in the Sentry SDK for flutter, I've created an issue: https://github.com/getsentry/sentry-dart/issues/942

In the meantime, the workaround could be setting the operating system manually in the current scope's context: https://pub.dev/documentation/sentry/latest/sentry_io/Contexts/operatingSystem.html

Something like this could work (not tested):

import 'dart:io' show Platform;

if (Platform.isIOS) {
  Sentry.configureScope((scope) => scope.setContexts('os', {
    'name': Platform.operatingSystem
  }));
}

Sentry不会在事件上提供操作系统

拔了角的鹿 2025-02-19 09:46:56

我终于设法找到了一种适合我的解决方案。
我收到的 access_token 授权代码我可以用来消费 google apis
我唯一要做的就是将访问权限发送到我的个人 asp.net core webapi
然后,我只需要编写一个简单的功能,我的控制器可以执行它:

 public class GoogleUserInfos
    {
        public string Id { get; set; }
        public string Email { get; set; }
        public string Verified_Email { get; set; }
        public string Name { get; set; }
        public string Given_Name { get; set; }
        public string Family_Name { get; set; }
        public string Picture { get; set; }
        public string Locale { get; set; }
    }

public async Task<GoogleUserInfos?> GetGoogleUserInfos(string authCode)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    var uri = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + authCode;
                    using (var response = await client.GetAsync(uri))
                    {
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            string responseString = await response.Content.ReadAsStringAsync();
                            var obj = JsonConvert.DeserializeObject<GoogleUserInfos>(responseString);
                            return obj;
                        }
                    }
                }
            }
            catch
            {
                return null;
            }
            return null;
        }

函数 getgoogleuserinfos access_token 为参数(名为 authcode )。 br>
然后,它将使用以下端点 https://www.googleapis.com /oauth2/v1/userInfo
它还将 AccessToken 作为GetRequest中的参数。
一旦得到响应,该函数就可以在自定义对象中 googleuserinfos 中启用对象。
响应的 id 字段是Google用户唯一 Open ID ,这将使我能够将用户与数据库中存储的用户联系起来。

I finally managed to find a solution that works for me.
The Access_Token I received was an Authorization Code I could use to consume google apis.
The only thing I had to do was to send the AccessToken to my personal ASP.NET CORE WebApi.
Then I just had to write a simple function that my controller could execute :

 public class GoogleUserInfos
    {
        public string Id { get; set; }
        public string Email { get; set; }
        public string Verified_Email { get; set; }
        public string Name { get; set; }
        public string Given_Name { get; set; }
        public string Family_Name { get; set; }
        public string Picture { get; set; }
        public string Locale { get; set; }
    }

public async Task<GoogleUserInfos?> GetGoogleUserInfos(string authCode)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    var uri = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + authCode;
                    using (var response = await client.GetAsync(uri))
                    {
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            string responseString = await response.Content.ReadAsStringAsync();
                            var obj = JsonConvert.DeserializeObject<GoogleUserInfos>(responseString);
                            return obj;
                        }
                    }
                }
            }
            catch
            {
                return null;
            }
            return null;
        }

The function GetGoogleUserInfos take the Access_Token as parameter (named authCode).
Then it consume the googleApi oauth2 with the following endpoint https://www.googleapis.com/oauth2/v1/userinfo.
It also send the accessToken as argument in the getRequest.
Once it get the response, the function deserialize the object in a custom object GoogleUserInfos.
The Id field of the response is the google user unique OPEN ID which will allow me to link the user with the users I store in my database.

如何通过授权令牌获得Google用户OpenID?

拔了角的鹿 2025-02-19 09:40:14

我用 npm i ran跑了您的代码,然后 npm start ,您在这里看不到Navbar吗?

I ran your code with npm i and then npm start, you don't see the navbar right here?

enter image description here

与React React的Crud不要显示Navbar

拔了角的鹿 2025-02-19 09:28:51

这是我到目前为止最好的解决方案,包括 student_id topic_id 以及老师的分数输入。

是的,很好。您只需要分析分数_ $ {student_id} _ $ {topic_id} 在服务器上的格式回到您期望的数据结构中。

不过,更习惯的编码是使用括号符号而不是下划线。许多用于应用程序/X-WWW-Form-urlencoded 的解析器可以自动将其转换为嵌套对象,请参阅Eg 无法将嵌套对象json张贴到节点Express Body Parser 如何在express.js?中获取嵌套表单数据。

 <input type="text" class="score-input" name="scores[<%= student.id %>][<%= topic.id %>]">

我还需要一个关于如何将所有这些数据转换为更新语句的提示。

使用多个 update 语句简单:

const { scores } = req.body;
for (const studentId in scores) {
    const studentScores = scores[studentId];
    for (const topicId in studentScores) {
        const points = studentScores[topicId];
        // TODO: check for permission (current user is a teacher who teaches the topic to the student)
        await pgClient.query(
            'UPDATE scores SET points = $3 WHERE student_id = $1 AND topic_id = $2',
            [studentId, topicId, points]
        );
    }
}

您可能需要在 parseInt 或两个或两个中使用 student> studentId 的适当输入验证, topic> topic> 如果您需要它们是整数而不是字符串;否则,Postgres将抛出例外。

This is my best solution so far to include a student_id and topic_id along with the teacher's score input.

Yes, it's fine. You just have to parse the scores_${student_id}_${topic_id} format on the server back into the data structure you expect.

A more customary encoding is to use bracket notation instead of underscores though. Many parsers for application/x-www-form-urlencoded POST bodies can automatically transform this into a nested object, see e.g. Can not post the nested object json to node express body parser and How to get nested form data in express.js?.

 <input type="text" class="score-input" name="scores[<%= student.id %>][<%= topic.id %>]">

I also need a hint about how to convert all of this data into an update statement.

Use multiple UPDATE statements for simplicity:

const { scores } = req.body;
for (const studentId in scores) {
    const studentScores = scores[studentId];
    for (const topicId in studentScores) {
        const points = studentScores[topicId];
        // TODO: check for permission (current user is a teacher who teaches the topic to the student)
        await pgClient.query(
            'UPDATE scores SET points = $3 WHERE student_id = $1 AND topic_id = $2',
            [studentId, topicId, points]
        );
    }
}

You might want to throw in a parseInt or two with proper input validation for the studentId, topicId and points if you need them to be integers instead of strings; otherwise postgres will throw an exception.

EJS表单,发送可以转换为PostgreSQL更新查询的数据阵列

拔了角的鹿 2025-02-19 08:19:39

您可以使用 switch 如下:

$regPath  = 'HKLM:\SOFTWARE\Bentley\BentleyDesktopClient\Install'
$oldValue = (Get-ItemPropertyValue -Path $regPath -Name 'UpdateClient') -ne ''
$newValue = switch -Wildcard ($oldValue) {
    'KeyName_CheckUpdateOption=*'    { 'KeyName_CheckUpdateOption=3' }
    'KeyName_CheckUpdateIsEnabled=*' { 'KeyName_CheckUpdateIsEnabled=0' }
    default { $_ }  # return this item unchanged
}
Set-ItemProperty -Path $regPath -Name 'UpdateClient' -Value $newValue

注册表值的新内容是:

KeyName_CheckUpdateOption=3
KeyName_CheckUpdateOptionModTime=<number-varies>
KeyName_UpdateClientInstallTime=<number-varies>
KeyName_CheckUpdateIsEnabled=0

You could use switch for this like below:

$regPath  = 'HKLM:\SOFTWARE\Bentley\BentleyDesktopClient\Install'
$oldValue = (Get-ItemPropertyValue -Path $regPath -Name 'UpdateClient') -ne ''
$newValue = switch -Wildcard ($oldValue) {
    'KeyName_CheckUpdateOption=*'    { 'KeyName_CheckUpdateOption=3' }
    'KeyName_CheckUpdateIsEnabled=*' { 'KeyName_CheckUpdateIsEnabled=0' }
    default { $_ }  # return this item unchanged
}
Set-ItemProperty -Path $regPath -Name 'UpdateClient' -Value $newValue

The new content of the registry value will be:

KeyName_CheckUpdateOption=3
KeyName_CheckUpdateOptionModTime=<number-varies>
KeyName_UpdateClientInstallTime=<number-varies>
KeyName_CheckUpdateIsEnabled=0

Windows 10注册表subkey reg_multi_sz如何编辑一些值

拔了角的鹿 2025-02-19 05:50:32

我相信您的计时器正在收集垃圾。声明函数之外的计时器变量,因此它永远不会超出范围。

I beleive your timer is getting garbage collected. Declare the timer variable outside of the function so it never goes out of scope.

Windows Service一天后停止

拔了角的鹿 2025-02-19 04:27:48

您可以首先将BLOB数据转换为CLOB类型,然后提取所需的标签。希望以下两个功能可以解决您的问题:

FUNCTION BLOB2CLOB(mBLOB IN BLOB) 
    RETURN CLOB IS
BEGIN
    Declare
        mCLOB   CLOB;
        mDestOffSet     INTEGER;
        mSrcOffSet      INTEGER;
        mBLOBCSID       INTEGER;
        mLangCntx       INTEGER;
        mWarn           INTEGER;
    Begin
        mDestOffSet := 1;
        mSrcOffSet := 1;
        mBLOBCSID := 0;
        mLangCntx := 0;
        mWarn := 0;
        DBMS_LOB.CreateTemporary(mCLOB, TRUE);
        DBMS_LOB.ConvertToClob(mCLOB, mBLOB, DBMS_LOB.GetLength(mBLOB), mDestOffSet, mSrcOffSet, mBLOBCSID, mLangCntx, mWarn);
        RETURN(mCLOB);
    End;
END BLOB2CLOB;
--
FUNCTION Get_SOAP_PartCLOB(mCLOB IN CLOB, mTag IN VARCHAR2) RETURN CLOB 
  IS
BEGIN
    Declare
        wrkCLOB         CLOB;
    myStart       NUMBER(10) := 0;
    myEnd         NUMBER(10) := 0;
    myLength      NUMBER(10) := 0;
    toErase       NUMBER(10) := 0;
    Begin
    DBMS_LOB.CreateTemporary(wrkCLOB, True);
    DBMS_LOB.COPY(wrkCLOB, mCLOB, DBMS_LOB.GETLENGTH(mCLOB));
    --
    myStart := DBMS_LOB.InStr(wrkCLOB, mTag, 1, 1) + Length(mTag) - 1;
    myEnd := DBMS_LOB.InStr(wrkCLOB, SubStr(mTag, 1, 1) || '/' || SubStr(mTag, 2));
    myLength := DBMS_LOB.GetLength(wrkCLOB);
    
    DBMS_LOB.ERASE(wrkCLOB, myStart, 1);
    toErase := myLength - myEnd + 1;

    DBMS_LOB.ERASE(wrkCLOB, toErase, myEnd);
    
    wrkCLOB := REPLACE(wrkCLOB, ' ', '');

        RETURN(wrkCLOB);
    End;
END Get_SOAP_PartCLOB;

您可以这样使用它:

SELECT 
    Get_SOAP_PartCLOB(BLOB2CLOB(YOUR_BLOB_COL), 'your_tag_in_clob') as "TAG_COL_ALIAS"
FROM
    YOUR_TABLE

我使用第二个功能get_soap_partclob()从某些Web服务的SOAP信封响应中获取一些很大的B64数据。这就是为什么返回类型是clob的原因。您可以将返回的值投放到其他方面,也可以对功能进行自己的调整。

You can first convert your BLOB data into CLOB type, and then extract the tags you need. Here are two functions that will, hopefully, solve your problem:

FUNCTION BLOB2CLOB(mBLOB IN BLOB) 
    RETURN CLOB IS
BEGIN
    Declare
        mCLOB   CLOB;
        mDestOffSet     INTEGER;
        mSrcOffSet      INTEGER;
        mBLOBCSID       INTEGER;
        mLangCntx       INTEGER;
        mWarn           INTEGER;
    Begin
        mDestOffSet := 1;
        mSrcOffSet := 1;
        mBLOBCSID := 0;
        mLangCntx := 0;
        mWarn := 0;
        DBMS_LOB.CreateTemporary(mCLOB, TRUE);
        DBMS_LOB.ConvertToClob(mCLOB, mBLOB, DBMS_LOB.GetLength(mBLOB), mDestOffSet, mSrcOffSet, mBLOBCSID, mLangCntx, mWarn);
        RETURN(mCLOB);
    End;
END BLOB2CLOB;
--
FUNCTION Get_SOAP_PartCLOB(mCLOB IN CLOB, mTag IN VARCHAR2) RETURN CLOB 
  IS
BEGIN
    Declare
        wrkCLOB         CLOB;
    myStart       NUMBER(10) := 0;
    myEnd         NUMBER(10) := 0;
    myLength      NUMBER(10) := 0;
    toErase       NUMBER(10) := 0;
    Begin
    DBMS_LOB.CreateTemporary(wrkCLOB, True);
    DBMS_LOB.COPY(wrkCLOB, mCLOB, DBMS_LOB.GETLENGTH(mCLOB));
    --
    myStart := DBMS_LOB.InStr(wrkCLOB, mTag, 1, 1) + Length(mTag) - 1;
    myEnd := DBMS_LOB.InStr(wrkCLOB, SubStr(mTag, 1, 1) || '/' || SubStr(mTag, 2));
    myLength := DBMS_LOB.GetLength(wrkCLOB);
    
    DBMS_LOB.ERASE(wrkCLOB, myStart, 1);
    toErase := myLength - myEnd + 1;

    DBMS_LOB.ERASE(wrkCLOB, toErase, myEnd);
    
    wrkCLOB := REPLACE(wrkCLOB, ' ', '');

        RETURN(wrkCLOB);
    End;
END Get_SOAP_PartCLOB;

You can use it like this:

SELECT 
    Get_SOAP_PartCLOB(BLOB2CLOB(YOUR_BLOB_COL), 'your_tag_in_clob') as "TAG_COL_ALIAS"
FROM
    YOUR_TABLE

I use the second function Get_SOAP_PartCLOB() to get some pretty big B64 data out of the soap envelope response from certain web services. That's why the return type is CLOB. You can cast the returned value to something else or make your own adjustments to the function.

SQL Oracle如何在Blob列中提取XML标签内容

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

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