怪我太投入

文章 评论 浏览 31

怪我太投入 2025-02-20 18:08:26

如果您不需要在field weft_links_10g上进行DB查询,我可以使用@property:

@property
def leave_links_10g(self):
    try:
        return int(self.by_projects_10g) - int(elf.on_facts_10g)
    except ValueError:
        return 0

您可以像普通字段一样

kt_object.leave_links_10g

将其加速,例如:但是,如果您想执行一些DB操作(例如filter或order_by) :

def save(self, *args, **kwargs):
    try:
        self.leave_links_10g =  int(self.by_projects_10g) - int(elf.on_facts_10g)
    except ValueError:
       self.leave_links_10g = 0
    super().save(*args, **kwargs)  # Call the "real" save() method.

if you don't need to do db query on field leave_links_10g i sugest use @property:

@property
def leave_links_10g(self):
    try:
        return int(self.by_projects_10g) - int(elf.on_facts_10g)
    except ValueError:
        return 0

you can acces it like normal field e.g.:

kt_object.leave_links_10g

but if you want to do some db operations like filter or order_by you need to override save method of model KT:

def save(self, *args, **kwargs):
    try:
        self.leave_links_10g =  int(self.by_projects_10g) - int(elf.on_facts_10g)
    except ValueError:
       self.leave_links_10g = 0
    super().save(*args, **kwargs)  # Call the "real" save() method.

Django模型错误,现在我想从一个鸡蛋中的另一个鸡皮中减去,但始终等于0,例如默认值。我是与Django合作的初学者

怪我太投入 2025-02-20 15:33:33

您在线上索引了一个范围的数组

arr [i] = arr [i + 1];

i = 2 右侧评估ARR [3]的右侧,该范围不超出范围。

这会产生不确定的越野车行为。人们在这个问题。

You're indexing an out of bounds array on line

arr[i] = arr[i + 1];

when i=2 the right hand side evaluates to arr[3], which is out of bounds.

This generates undefined, buggy behavior. This has already been answered much better by people at this question.

为什么我得到1'移动元素后,作为索引ARR [2]的阵列的最后一个元素

怪我太投入 2025-02-20 11:02:41

仍然没有找到正确的方法,而是想出了适合我需求的工作(黑客)。

使用 oneDitformPreloadtext 代码> malakhere '),编辑了'标题'变更标题的参数,然后使用新页名重定向。在挂钩函数中,如果找到(仅是重定向的原因),则需要检查“ malakhere ”参数,然后它将退出该函数,以免创建循环。

    public static function onEditFormPreloadText(string &$text, Title &$title ) {
        global $wgOut;

        if ( isset( $_GET["MalakHere"] ) ) {
            return true;
        }

        $pos = strpos($text, "[[Category:Malak]]");
        if ($pos) {
            $url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
            $urlTitle = urlencode($_GET["title"]);

            $newURL = str_replace("title=" . $urlTitle,"MalakHere=yes",$url);
            $newTitle = self::newTitlePre() . $title->prefixedText;
            $url = $newURL . "&title=" . $newTitle;

            return $wgOut->redirect($url);
        }

        return true;
    }

Still have not found the proper way to do this, but came up with a work around (hackery) which works for my needs.

Using the onEditFormPreloadText hook, change the url and added a new parameter ('MalakHere'), edited the 'title' parameter to the altered title, then do a redirect with the new page name. In the hook function there is a check for the 'MalakHere' parameter, if found (only cause of redirect) then it will exit the function so not to create a loop.

    public static function onEditFormPreloadText(string &$text, Title &$title ) {
        global $wgOut;

        if ( isset( $_GET["MalakHere"] ) ) {
            return true;
        }

        $pos = strpos($text, "[[Category:Malak]]");
        if ($pos) {
            $url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
            $urlTitle = urlencode($_GET["title"]);

            $newURL = str_replace("title=" . $urlTitle,"MalakHere=yes",$url);
            $newTitle = self::newTitlePre() . $title->prefixedText;
            $url = $newURL . "&title=" . $newTitle;

            return $wgOut->redirect($url);
        }

        return true;
    }

MediaWiki-挂钩编辑/更改页面标题创建

怪我太投入 2025-02-20 08:50:22

如果我正确理解了您的问题,您需要在第一名中创建该字符向量,您只需要列表柱子,然后在每个列表上应用diff并计算每个 a_dat


library(dplyr)
library(tibble)


fall_hc <- tibble::tribble(
  ~a_dat,  ~AZeit, ~snzeit,
  "2019-01-02", "24180",      31,
  "2019-01-02", "24360",      27,
  "2019-01-02", "24480",      16,
  "2019-01-02", "24780",      64,
  "2019-01-02", "30420",       9,
  "2019-01-02", "30840",      10,
  "2019-01-02", "35280",      31,
  "2019-01-03", "24120",      40,
  "2019-01-03", "24120",      27,
  "2019-01-03", "24480",       6,
  "2019-01-03", "24480",       4,
  "2019-01-03", "24780",       9,
  "2019-01-03", "25380",      25,
  "2019-01-03", "26460",      33,
  "2019-01-04", "24000",       5,
  "2019-01-04", "24360",       2,
  "2019-01-04", "24900",       1,
  "2019-01-04", "27180",      29,
  "2019-01-04", "30600",       8,
  "2019-01-07", "24780",      25,
  "2019-01-07", "24840",       4,
  "2019-01-07", "28920",       3,
  "2019-01-07", "31620",      11,
  "2019-01-08", "24060",      46,
  "2019-01-08", "24480",       7,
  "2019-01-08", "25260",       4,
  "2019-01-08", "27900",       5,
  "2019-01-08", "29820",       5,
  "2019-01-08", "30060",      74,
  "2019-01-08", "33360",       5,
  "2019-01-08", "33600",      28,
  "2019-01-08", "34200",      15,
  "2019-01-08", "35520",      13,
  "2019-01-08", "36000",      19,
  "2019-01-08", "44100",      24
)


fall_hc %>%
    arrange(a_dat, AZeit) %>%
    group_by(a_dat) %>%
    summarise(
        time_vec = list(snzeit)
    ) %>%
    group_by(a_dat) %>%
    summarise(
        time_vec = diff(unlist(time_vec)) # caluculate diffs for each list
    ) %>%
    group_by(a_dat) %>%
    summarise(
        time_vec_neg = sum(time_vec < 0) # count number of negative values
    )

#> `summarise()` has grouped output by 'a_dat'. You can override using the
#> `.groups` argument.
#> # A tibble: 5 × 2
#>   a_dat      time_vec_neg
#>   <chr>             <int>
#> 1 2019-01-02            3
#> 2 2019-01-03            3
#> 3 2019-01-04            3
#> 4 2019-01-07            2
#> 5 2019-01-08            5

reprex软件包(v2.0.1)

If I have understood your problem correctly, you donot need to create that character vector in the 1st place, you just need list-column and then applying diff on each list and calculate the number of negative values for each a_dat


library(dplyr)
library(tibble)


fall_hc <- tibble::tribble(
  ~a_dat,  ~AZeit, ~snzeit,
  "2019-01-02", "24180",      31,
  "2019-01-02", "24360",      27,
  "2019-01-02", "24480",      16,
  "2019-01-02", "24780",      64,
  "2019-01-02", "30420",       9,
  "2019-01-02", "30840",      10,
  "2019-01-02", "35280",      31,
  "2019-01-03", "24120",      40,
  "2019-01-03", "24120",      27,
  "2019-01-03", "24480",       6,
  "2019-01-03", "24480",       4,
  "2019-01-03", "24780",       9,
  "2019-01-03", "25380",      25,
  "2019-01-03", "26460",      33,
  "2019-01-04", "24000",       5,
  "2019-01-04", "24360",       2,
  "2019-01-04", "24900",       1,
  "2019-01-04", "27180",      29,
  "2019-01-04", "30600",       8,
  "2019-01-07", "24780",      25,
  "2019-01-07", "24840",       4,
  "2019-01-07", "28920",       3,
  "2019-01-07", "31620",      11,
  "2019-01-08", "24060",      46,
  "2019-01-08", "24480",       7,
  "2019-01-08", "25260",       4,
  "2019-01-08", "27900",       5,
  "2019-01-08", "29820",       5,
  "2019-01-08", "30060",      74,
  "2019-01-08", "33360",       5,
  "2019-01-08", "33600",      28,
  "2019-01-08", "34200",      15,
  "2019-01-08", "35520",      13,
  "2019-01-08", "36000",      19,
  "2019-01-08", "44100",      24
)


fall_hc %>%
    arrange(a_dat, AZeit) %>%
    group_by(a_dat) %>%
    summarise(
        time_vec = list(snzeit)
    ) %>%
    group_by(a_dat) %>%
    summarise(
        time_vec = diff(unlist(time_vec)) # caluculate diffs for each list
    ) %>%
    group_by(a_dat) %>%
    summarise(
        time_vec_neg = sum(time_vec < 0) # count number of negative values
    )

#> `summarise()` has grouped output by 'a_dat'. You can override using the
#> `.groups` argument.
#> # A tibble: 5 × 2
#>   a_dat      time_vec_neg
#>   <chr>             <int>
#> 1 2019-01-02            3
#> 2 2019-01-03            3
#> 3 2019-01-04            3
#> 4 2019-01-07            2
#> 5 2019-01-08            5

Created on 2022-07-07 by the reprex package (v2.0.1)

数据框中的数字向量的字符值

怪我太投入 2025-02-19 17:19:34

杰克逊显然扫描您通过的班级
然后使用这些方法进行序列化和挑选化。

“获取”,“ set”,“ is”被消除,这些方法中仍然存在的内容将用作JSON字段。

因此,您的“ is_something”将其更改为“ _something”等等。

Jackson apparently scans the class that you pass in for getters and setters
and then use those methods for serialization and deserialization.

"Get", "Set", "is" are eliminated and what remains in those methods will be used as Json field.

Hence your "is_something" is changed into "_something" and so on.

杰克逊(Jackson)的objectmapper()。writeValueasString()忽略以“ is_ is_”开头的变量

怪我太投入 2025-02-18 16:47:59

主题标签是uris的保留字符(表示片段)。

根据 rfc 3986 第2.2节,保留的字符为:

 保留= gen-delims / sub-delims

gen-delims =“:” /“ /” /“?” /“#” /“ [“ /”]“ /”@”

sub-delims =“!” /“ $” /“&amp;” /“'” /“(“ /”)”
            /“*” /“+” /“,” /“;” /“ =”
 

而且,重要的是:

如果URI组件的数据将与保留角色作为定界符的目的相抵触,则在形成URI之前,必须对矛盾的数据进行分配


Hastag的百分比编码为%23 ,因此而不是
背景:url('./ Assets/test#1234.png')

您将寻找目标:
背景:url('./ Assets/test%231234.png ')

The hashtag is a reserved character for URIs (which denotes the fragment).

According to RFC 3986 section 2.2, the reserved characters are:

reserved    = gen-delims / sub-delims

gen-delims  = ":" / "/" / "?" / "#" / "[" / "]" / "@"

sub-delims  = "!" / "
quot; / "&" / "'" / "(" / ")"
            / "*" / "+" / "," / ";" / "="

And, importantly:

If data for a URI component would conflict with a reserved character's purpose as a delimiter, then the conflicting data must be percent-encoded before the URI is formed.

The percentage-encoding of the hastag comes out to %23, so instead of
background: url('./assets/test#1234.png')

You would be looking to target:
background: url('./assets/test%231234.png')

在SCSS/CSS中使用#(主题标签)中的#(主题标签)

怪我太投入 2025-02-17 10:39:06

在这里使用 str_replace

library(stringr)

str_replace(text, ' sat
, '')

[1] "good morning amer"    
[2] "this morning saturday"

Here with str_replace:

library(stringr)

str_replace(text, ' sat
, '')

[1] "good morning amer"    
[2] "this morning saturday"

删除特定的字符串和之后的任何内容

怪我太投入 2025-02-17 10:27:11

您在承载后包含的那个字符串 evaz ... 看起来不像是正确格式化的JWT,它的3个片段分别为时期。

您需要使用一个领域SDK或Admin API获取客户端访问令牌。

这里是有关如何使用Web SDK获取访问令牌的文档 -

我认为所有其他领域客户端SDK都应该具有 user.accesstoken conscotor方法。

以及有关如何使用Admin API获取访问令牌的更多一般文档 - https://www.mongodb.com/docs/atlas/atlas/app-services/reference/reference/reference/authenticate/authenticate-http-client-reqlient-request-requests/#std -label-authenticate-http-client-requests

另外,如果您使用的是自定义JWT auth,请求标题不同。从文档中:

http.post({
  "url": "https://realm.mongodb.com/api/client/v2.0/app/<yourappid-abcde>/graphql",
  "headers": {
    "jwtTokenString": "<User's JWT Token>"
  },
  "body": '{"query":"query AllMovies {\n  movies {\n    title\n    year\n  }\n}"}'
})

在自定义JWT请求标头上进行进一步阅读 - https://www.mongodb.com/docs/atlas/app-services/graphql/authenticate/#custom-jwt

That string which you've included after Bearer eVaz... doesn't look like a properly formatted JWT, which has 3 segments separated by periods.

You need to get the client access token using one of the Realm SDKs or the Admin API.

Here's docs on how to get the access token with the Web SDK - https://www.mongodb.com/docs/realm/web/graphql-apollo-react/

I think all the other Realm client SDKs should also have a User.accessToken accessor method.

And more general documentation on how to use the Admin API to get an access token - https://www.mongodb.com/docs/atlas/app-services/reference/authenticate-http-client-requests/#std-label-authenticate-http-client-requests

Alternatively, if you're using Custom JWT auth, the request header is different. From the docs:

http.post({
  "url": "https://realm.mongodb.com/api/client/v2.0/app/<yourappid-abcde>/graphql",
  "headers": {
    "jwtTokenString": "<User's JWT Token>"
  },
  "body": '{"query":"query AllMovies {\n  movies {\n    title\n    year\n  }\n}"}'
})

Further reading on custom JWT request headers - https://www.mongodb.com/docs/atlas/app-services/graphql/authenticate/#custom-jwt

如何在Mongoatlas GraphQl API中使用JWT标准

怪我太投入 2025-02-17 06:48:20

您正在运行原始查询,因此将转换为 date 实例而不是Postgres驱动程序的不是Typeorm。

我不确定是否可以配置驱动程序不执行转换,但是相对简单的解决方法可能是将与时间相关的字段强加于字符串:

SELECT date::text AS dateString, dueDate::text AS dueDateString, * FROM invoice

You're running a raw query, so it's not TypeORM that's doing the conversion to a Date instance, but rather the Postgres driver.

I'm not sure if it's possible to configure the driver not to perform the conversion, but a relatively simple workaround could be to force your time-related fields to a string:

SELECT date::text AS dateString, dueDate::text AS dueDateString, * FROM invoice

typeorm-实体管理器日期

怪我太投入 2025-02-16 04:01:30

文档

>>> import datetime
>>> from django.db.models import Q, Avg
>>> from django.db.models import F
>>> apr21 = Avg('aqi', filter=Q(date__range=(datetime.date(2021, 4, 1), datetime.date(2021, 4, 30)))
>>> apr22 = Avg('aqi', filter=Q(date__range=(datetime.date(2022, 4, 1), datetime.date(2022, 4, 30)))
>>> aqi_calc = Airquality.objects.annotate(apr21=apr21)
                         .annotate(apr22=apr22)
                         .annotate(diff=F('apr22') - F('apr21'))

如果我没记错的话,应该在1查询中完成所有操作。

Inspiring from the documentation, the following should work:

>>> import datetime
>>> from django.db.models import Q, Avg
>>> from django.db.models import F
>>> apr21 = Avg('aqi', filter=Q(date__range=(datetime.date(2021, 4, 1), datetime.date(2021, 4, 30)))
>>> apr22 = Avg('aqi', filter=Q(date__range=(datetime.date(2022, 4, 1), datetime.date(2022, 4, 30)))
>>> aqi_calc = Airquality.objects.annotate(apr21=apr21)
                         .annotate(apr22=apr22)
                         .annotate(diff=F('apr22') - F('apr21'))

It should do everything in 1 query, if I'm not mistaken.

Django Orm:仅在数据质量查询内进行计算?

怪我太投入 2025-02-15 23:04:26

如果要将其概括为更长或更多的列表/数组,则可以查看numpy:

a1 = np.array([True, True, False])
a2 = np.array([False, False, True, False])
out = np.r_[a1, ~a2]

output: array([真,true,true,false,true,true,true,true,false,true])>

If you want to generalize this to longer or more lists/arrays, you could have a look at numpy:

a1 = np.array([True, True, False])
a2 = np.array([False, False, True, False])
out = np.r_[a1, ~a2]

output: array([ True, True, False, True, True, False, True])

通过其他布尔人列表的补充来扩展布尔值列表

怪我太投入 2025-02-15 21:17:59

我转换了 blindman67的响应对可重复使用的功能。

它是高度可配置的。

const TAU = 2 * Math.PI;

const main = () => {
  const ctx = document.querySelector('#drawing').getContext('2d');
  drawGrid(ctx, 1, 1, 15, 13, {
    radius: 20,
    inset: 2,
    randomColors: generateColors(30, 1.0, 0.667)
  });
};

const defaultGridOptions = {
  radius: 10,
  sides: 6,
  inset: 0,
  // Context
  lineWidth: 1,
  fillStyle: '',
  strokeStyle: 'black',
  // Other
  randomColors: null
};

const drawGrid = (ctx, x, y, w, h, options = {}) => {
  const opts = { ...defaultGridOptions, ...options };
  const points = createPoly(opts);
  opts.diameter = opts.radius * 2;
  for (let gy = y; gy < y + h; gy++) {
    for (let gx = x; gx < x + w; gx++) {
      ctx.fillStyle = opts.randomColors ? pickRandom(opts.randomColors) : opts.fillStyle;
      drawPoly(ctx, gridToPixel(gx, gy, opts), points, opts);
    }
  }
};

const gridToPixel = (gridX, gridY, opts) => {
  const m = gridMeasurements(opts);
  return toPoint(
    Math.floor(gridX * m.gridSpaceX),
    Math.floor(gridY * m.gridSpaceY + (gridX % 2 ? m.gridOffsetY : 0))
  );
};

const drawPoly = (ctx, origin, points, opts) => {
  ctx.strokeStyle = opts.strokeStyle;
  ctx.save();
  ctx.translate(origin.x, origin.y);
  polyPath3(ctx, points);
  ctx.restore();
  if (opts.lineWidth) ctx.lineWidth = opts.lineWidth;
  if (opts.fillStyle || opts.randomColors) ctx.fill();
  if (opts.strokeStyle) ctx.stroke();
};

const createPoly = (opts, points = []) => {
  const
    { inset, radius, sides } = opts,
    size = radius - inset,
    step = TAU / sides;
  for (let i = 0; i < sides; i++) {
    points.push(toPolarCoordinate(0, 0, size, step * i));
  }
  return points;
};

const gridMeasurements = (opts) => {
  const
    { diameter, inset, radius, sides } = opts,
    edgeLength = Math.sin(Math.PI / sides) * diameter,
    gridSpaceX = diameter - edgeLength / 2,
    gridSpaceY = Math.cos(Math.PI / sides) * diameter,
    gridOffsetY = gridSpaceY / 2;
  return {
    diameter,
    edgeLength,
    gridSpaceX,
    gridSpaceY,
    gridOffsetY
  };
};

/** @unused */
const polyPath = (ctx, x, y, radius, sides = 3) => {
  ctx.beginPath();
  ctx.moveTo(...fromPoint(toPolarCoordinate2(x, y, radius)));
  for (let i = 1; i <= sides; i += 1) {
    ctx.lineTo(...fromPoint(toPolarCoordinate2(x, y, radius, sides, i)));
  }
  ctx.closePath();
};

/** @unused */
const polyPath2 = (ctx, points = []) => {
  ctx.beginPath();
  ctx.moveTo(points[0], points[1]);
  for (let i = 2; i < points.length - 1; i += 2) {
    ctx.lineTo(points[i], points[i + 1]);
  }
  ctx.closePath();
};

const polyPath3 = (ctx, points = []) => {
  const [{ x: startX, y: startY }] = points;
  ctx.beginPath();
  ctx.moveTo(startX, startY);
  points.forEach(({ x, y }) => { ctx.lineTo(x, y); });
  ctx.closePath();
};

const pickRandom = (arr) => arr[Math.floor(Math.random() * arr.length)];

const toPoint = (x, y) => ({ x, y });

const fromPoint = ({ x, y }) => [ x, y ];

const toPolarCoordinate = (centerX, centerY, radius, angle) => ({
  x: centerX + radius * Math.cos(angle),
  y: centerY + radius * Math.sin(angle)
});

const toPolarCoordinate2 = (centerX, centerY, radius, sides, i) =>
  toPolarCoordinate(centerX, centerY, radius, i === 0 ? 0 : (i * TAU / sides));

const generateColors = (count, saturation = 1.0, lightness = 0.5, alpha = 1.0) =>
  Array.from({ length: count }, (_, i) =>
    `hsla(${[
      Math.floor(i / count * 360),
      `${Math.floor(saturation * 100)}%`,
      `${Math.floor(lightness * 100)}%`,
      alpha
    ].join(', ')})`);

main();
#drawing { border: 1px dashed red; }
<canvas id="drawing" width="500" height="500"></canvas>

I converted Blindman67's response to a reusable function.

It is highly configurable.

const TAU = 2 * Math.PI;

const main = () => {
  const ctx = document.querySelector('#drawing').getContext('2d');
  drawGrid(ctx, 1, 1, 15, 13, {
    radius: 20,
    inset: 2,
    randomColors: generateColors(30, 1.0, 0.667)
  });
};

const defaultGridOptions = {
  radius: 10,
  sides: 6,
  inset: 0,
  // Context
  lineWidth: 1,
  fillStyle: '',
  strokeStyle: 'black',
  // Other
  randomColors: null
};

const drawGrid = (ctx, x, y, w, h, options = {}) => {
  const opts = { ...defaultGridOptions, ...options };
  const points = createPoly(opts);
  opts.diameter = opts.radius * 2;
  for (let gy = y; gy < y + h; gy++) {
    for (let gx = x; gx < x + w; gx++) {
      ctx.fillStyle = opts.randomColors ? pickRandom(opts.randomColors) : opts.fillStyle;
      drawPoly(ctx, gridToPixel(gx, gy, opts), points, opts);
    }
  }
};

const gridToPixel = (gridX, gridY, opts) => {
  const m = gridMeasurements(opts);
  return toPoint(
    Math.floor(gridX * m.gridSpaceX),
    Math.floor(gridY * m.gridSpaceY + (gridX % 2 ? m.gridOffsetY : 0))
  );
};

const drawPoly = (ctx, origin, points, opts) => {
  ctx.strokeStyle = opts.strokeStyle;
  ctx.save();
  ctx.translate(origin.x, origin.y);
  polyPath3(ctx, points);
  ctx.restore();
  if (opts.lineWidth) ctx.lineWidth = opts.lineWidth;
  if (opts.fillStyle || opts.randomColors) ctx.fill();
  if (opts.strokeStyle) ctx.stroke();
};

const createPoly = (opts, points = []) => {
  const
    { inset, radius, sides } = opts,
    size = radius - inset,
    step = TAU / sides;
  for (let i = 0; i < sides; i++) {
    points.push(toPolarCoordinate(0, 0, size, step * i));
  }
  return points;
};

const gridMeasurements = (opts) => {
  const
    { diameter, inset, radius, sides } = opts,
    edgeLength = Math.sin(Math.PI / sides) * diameter,
    gridSpaceX = diameter - edgeLength / 2,
    gridSpaceY = Math.cos(Math.PI / sides) * diameter,
    gridOffsetY = gridSpaceY / 2;
  return {
    diameter,
    edgeLength,
    gridSpaceX,
    gridSpaceY,
    gridOffsetY
  };
};

/** @unused */
const polyPath = (ctx, x, y, radius, sides = 3) => {
  ctx.beginPath();
  ctx.moveTo(...fromPoint(toPolarCoordinate2(x, y, radius)));
  for (let i = 1; i <= sides; i += 1) {
    ctx.lineTo(...fromPoint(toPolarCoordinate2(x, y, radius, sides, i)));
  }
  ctx.closePath();
};

/** @unused */
const polyPath2 = (ctx, points = []) => {
  ctx.beginPath();
  ctx.moveTo(points[0], points[1]);
  for (let i = 2; i < points.length - 1; i += 2) {
    ctx.lineTo(points[i], points[i + 1]);
  }
  ctx.closePath();
};

const polyPath3 = (ctx, points = []) => {
  const [{ x: startX, y: startY }] = points;
  ctx.beginPath();
  ctx.moveTo(startX, startY);
  points.forEach(({ x, y }) => { ctx.lineTo(x, y); });
  ctx.closePath();
};

const pickRandom = (arr) => arr[Math.floor(Math.random() * arr.length)];

const toPoint = (x, y) => ({ x, y });

const fromPoint = ({ x, y }) => [ x, y ];

const toPolarCoordinate = (centerX, centerY, radius, angle) => ({
  x: centerX + radius * Math.cos(angle),
  y: centerY + radius * Math.sin(angle)
});

const toPolarCoordinate2 = (centerX, centerY, radius, sides, i) =>
  toPolarCoordinate(centerX, centerY, radius, i === 0 ? 0 : (i * TAU / sides));

const generateColors = (count, saturation = 1.0, lightness = 0.5, alpha = 1.0) =>
  Array.from({ length: count }, (_, i) =>
    `hsla(${[
      Math.floor(i / count * 360),
      `${Math.floor(saturation * 100)}%`,
      `${Math.floor(lightness * 100)}%`,
      alpha
    ].join(', ')})`);

main();
#drawing { border: 1px dashed red; }
<canvas id="drawing" width="500" height="500"></canvas>

使用帆布html&amp;用六角形绘制网格JavaScript

怪我太投入 2025-02-15 20:41:52

这应该给您一些想法。假设我们使用的是一个名为 testdb 的测试数据库,并且您的原始表被命名为 test ,它具有3列IE a b ,<代码> c 。桌子上的三行就像您之前提供的一样。接下来,我们可以继续创建一个存储过程。注意:使用准备好的语句以获取每列的总和值的背后原因是由于必须进行硬编码的规则,该规则无法用变量替换。例如从test; 中选择“ sum(a)”,无法将其写入从test; 中选择sum(@column_name)。通过使用准备好的语句,我们可以动态编码列名。

delimiter //
drop procedure if exists table_sum//
create procedure table_sum (db_name varchar(20),tb_name varchar(20))
begin
declare col_name varchar(10);
declare fin bool default false;
declare c cursor for select column_name from information_schema.columns where table_schema=db_name and table_name=tb_name;
declare continue handler for not found set fin=true;
drop temporary table if exists result_tb;
create temporary table result_tb (`Columns` varchar(10),`Values` varchar(25));
open c;
lp:loop

    fetch c into col_name;
    if fin=true then
        leave lp;
    end if;
    set @stmt=concat('select sum(',col_name,') into @sum from test ;'); 
    prepare stmt from @stmt;
    execute stmt;
    deallocate prepare stmt;
    
    set @val=concat('sum(',col_name,') = ',@sum);
    insert result_tb values(col_name,@val);

end loop lp;

close c;
select * from result_tb;
end//

delimiter ;

最后,我们调用该过程以获取所需的输出:

call table_sum('testdb','test'); 

This should fairly give you some ideas. Supposing we are using a test database named testdb and your original table is named test which has 3 columns i.e a,b,c . The three rows in the table are just like what you provided before. Next we can proceed to create a stored procedure. Note: The reason behind using a prepared statement to get the sum value for each column is due to the rules that column names have to be hardcoded , which can not be replaced with variables. e.g select sum(a) from test; can not be written as select sum(@column_name) from test;. By using a prepared statement, we can hardcode the column name dynamically.

delimiter //
drop procedure if exists table_sum//
create procedure table_sum (db_name varchar(20),tb_name varchar(20))
begin
declare col_name varchar(10);
declare fin bool default false;
declare c cursor for select column_name from information_schema.columns where table_schema=db_name and table_name=tb_name;
declare continue handler for not found set fin=true;
drop temporary table if exists result_tb;
create temporary table result_tb (`Columns` varchar(10),`Values` varchar(25));
open c;
lp:loop

    fetch c into col_name;
    if fin=true then
        leave lp;
    end if;
    set @stmt=concat('select sum(',col_name,') into @sum from test ;'); 
    prepare stmt from @stmt;
    execute stmt;
    deallocate prepare stmt;
    
    set @val=concat('sum(',col_name,') = ',@sum);
    insert result_tb values(col_name,@val);

end loop lp;

close c;
select * from result_tb;
end//

delimiter ;

Finally we call the procedure to get the desired output:

call table_sum('testdb','test'); 

sql /mysql /transpose表 /列成排成排作为列的行和新标头的列

怪我太投入 2025-02-15 20:35:56

标签解决问题后添加一个空格:

Window {
width: 640;
height: 480;
visible: true;
title: qsTr("Code from @Meliodas on StackOverflow");

    TextArea {
        id: textArea;
        textFormat: Qt.RichText;
        focus: true;
        selectByMouse: true;
        selectByKeyboard: true;

        Keys.onPressed: (event) => {
            if (event.text === "@") {
                // HERE
                insert(cursorPosition, "<a href='mentioned://user'>@User</a> ");
                event.accepted = true;
            }
        }
    }
}

请注意,我享有修改其他代码的自由:

  • ​警告告诉我隐式事件参数已弃用

Adding a whitespace after the tag solves the problem :

Window {
width: 640;
height: 480;
visible: true;
title: qsTr("Code from @Meliodas on StackOverflow");

    TextArea {
        id: textArea;
        textFormat: Qt.RichText;
        focus: true;
        selectByMouse: true;
        selectByKeyboard: true;

        Keys.onPressed: (event) => {
            if (event.text === "@") {
                // HERE
                insert(cursorPosition, "<a href='mentioned://user'>@User</a> ");
                event.accepted = true;
            }
        }
    }
}

Note that I took the freedom of modifying other pieces of your code :

  • insert() instead of text += to avoid automatic newlines
  • explicitly defining event to silence a warning telling me implicit event parameters are deprecated

如何重置QML Textarea中丰富文本的样式

怪我太投入 2025-02-15 17:55:35
  1. 只需将应用程序类的静态实例存储在您想要的地方 - &gt;不是理想的解决方案,但它起作用* source> source

打开class myapplication:application:application( ){

override fun onCreate() {
    super.onCreate()
    instance = this
}

companion object {
    lateinit var instance: MyApplication
        private set
    fun getApplicationContext(): Context? {
        return instance.applicationContext
    }
}

}

这样使用:

MyApplication.instance.cacheDir()

*您将在组件之间引入直接依赖性
您项目的应用程序类,使得无法使用这些
具有另一个应用程序类的组件,无法声明
例如,这些组件在单独的Gradle模块中。 - link

  1. 使用di,例如使用hilt-&gt;到小型项目的开销?
  2. 自定义Kotlin Singleton实施 - &gt;可读性和复杂性缺点。
  1. Simply store a static instance of your application class in it an access it where you want -> not ideal solution but it works* Source

open class MyApplication : Application() {

override fun onCreate() {
    super.onCreate()
    instance = this
}

companion object {
    lateinit var instance: MyApplication
        private set
    fun getApplicationContext(): Context? {
        return instance.applicationContext
    }
}

}

Use it like this:

MyApplication.instance.cacheDir()

*you would introduce a direct dependency between your components and
your project's Application class, making it impossible to use these
components with another Application class and impossible to declare
these components inside a separate gradle module for example. - LINK

  1. Using DI for example with Hilt -> to much overhead for small projects?
  2. Custom Kotlin singleton implementation -> readability and complexity drawback.

如何在翻新单元对象中使用Android上下文

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

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