请爱~陌生人

文章 评论 浏览 26

请爱~陌生人 2025-02-21 01:28:16

在VSCODE中,我试图禁用我之前安装的所有扩展程序,我一个一个接一个地禁用它们,在每次禁用后,我通过更改代码然后保存的代码测试,但问题仍然存在,直到所有扩展名关闭为止。

然后我想起还有其他一些内置扩展。我打开了扩展名,然后按在左侧栏右上方的三个点上,然后我选择显示运行扩展运行扩展将打开,您将找到其中的git。我注意到git在无响应中,除了 4000+MS 之外,它的数量大于所有其他扩展。

请注意,我正在使用git版本 2.34.1 。在生锈开发过程中,GIT扩展也可以响应。

因此,我将git更新为最新版本,该版本是 2.37.1 使用以下命令:

sudo addo add-apt-repository ppa:git-core/ppa

sudo apt apt Update

sudo apt install git

现在我重新启动了VSCODE,git扩展程序响应且正常工作。另外,节省很快,一切都很好。

问题归因于我所知,仅在C ++开发中扩展了无反应的GIT。因此,将git更新到最新版本。

更新:

我认为即使将GIT更新为最新版本后,问题仍然存在。延迟仍然仅在C ++开发中发生。一旦我使用 git Init 在工作目录中初始化了git,就可以解决该问题。当我重新启动VSCODE时,一切正常。这是问题存在时运行扩展的屏幕截图(请注意第一个GIT扩展程序):

更新:

我想我知道问题所在。我的C ++项目的目录是/home/user/user/projects/cpp/testing_1 ,在 cpp/目录中,我放置了所有我的C ++项目,例如 testing_1/< /code>, testing_2/等等。我在 cpp/ dir中初始化的git在此之前是我所有项目的父级。当我删除 .git cpp/ dir时,即使我在工作项目中不初始化git,例如 testing_1 /。我认为您的项目的父母dir中不初始化git解决了问题。我会看到那走的地方。

In vscode, i tried to disable all the extensions that i installed previously, i disabled them one by one, after each disable, i test by changing the code then saving, yet the problem persists, until all the extensions are off.

Then i remembered there are some other built-in extensions. I opened the extensions, then pressed on the three dots at the top right of the left side bar, then i chose Show running extensions, the Running extensions will open and you will find among them git. I noticed that git in unresponsive and had a huge number beside it like 4000+ms which is substantially greater than all the other extensions.

Notice that i am using git version 2.34.1. Also the git extension is ok and responsive during Rust development.

So i updated git to the latest version which is 2.37.1 using these commands:

sudo add-apt-repository ppa:git-core/ppa

sudo apt update

sudo apt install git

Now i restarted vscode and the git extension is responsive and working properly. Also the saving is fast and everything in fine.

The problem was due to unresponsive git extension only in C++ development as far as i know. So update git to the latest version.

Update:

I think the problem still exists even after i updated git to the latest version. The delay still only happens with C++ development. The problem is solved once i initialized git in my working directory using git init. When i restart vscode, everything works fine. Here is a screenshot of the Running extensions when the problem exists (Notice the first git extension):
enter image description here

Update:

I think i knew where the problem is. The directory of my C++ project is /home/user/Projects/cpp/testing_1, in cpp/ directory i put all my C++ projects such as testing_1/, testing_2/ and so on. I initialized git in cpp/ dir before which is the parent dir of all my projects. When i deleted that .git dir in cpp/ the git extension in responsive and working fine, even when i am not initializing git in my working project such as testing_1/. I think not initializing git in the parent dir of your project solved the problem. I will see where that goes.

VS代码需要几秒钟才能将文档保存在C&#x2B;&#x2B;

请爱~陌生人 2025-02-20 21:49:15

八分之一仅使用一到三个(八进制)数字 - &nbsp; “ \ 033999c” 是5个字符加上一个null字节。

十六进制逃脱使用的数字数量如 \ x 序列。因此,“ \ x1b999c” 包含一个单个十六进制字符常数。

参见§6.4.4.4.4用于规格。

至少有两个可能的修复程序。一种是编码 \ x1b \ 033 (或 \ 33 - 它们是相同的,尽管如果之后的文本\ x1b 777a 而不是 999c ,那么三位数的八位ovene是必需的

if (write(STDOUT_FILENO, "\033999C\033999B", 10) != 10)

。串联:

if (write(STDOUT_FILENO, "\x1B" "999C" "\x1B" "999B", 10) != 10)

这是因为在 - 第5阶段转换逃脱序列,第6阶段结合了相邻的字符串文字

。这是10个非挂钩字符 - 如果您打算编写字节0x01,然后是5个字符(两次),那么12个字符更有意义,并且您需要更改字符串中断的地方

。 > 11 :

#include <stdio.h>

int main(void)
{
    char data[] = "\x1b" "999C" "\x1b" "999B";
    printf("%zu\n", sizeof(data));
    return 0;
}

删除序列,GCC投资:

xe43.c: In function ‘main’:
xe43.c:5:19: error: hex escape sequence out of range [-Werror]
     char data[] = "\x1b999C\x1b999B";
                   ^~~~~~~~~~~~~~~~~~
xe43.c:5:19: error: hex escape sequence out of range [-Werror]
cc1: all warnings being treated as errors

我使用 Werror 选项进行编译,否则,只有警告没有 -werror 并运行,它会产生答案3,而不是11。

Octal escapes use one to three (octal) digits only — "\033999C" is 5 characters plus a null byte.

Hex escapes use as many hex digits as follow the \x sequence. Therefore, "\x1b999C" contains a single hex character constant.

See §6.4.4.4 Character constants in the C11 standard for the specification.

There are at least two possible fixes. One is to encode \x1B as \033 (or \33 — they're the same, though if the text after the \x1B was 777A instead of 999C, then the triple-digit octal escape would be necessary.

if (write(STDOUT_FILENO, "\033999C\033999B", 10) != 10)

A second is to split the string and use string concatenation:

if (write(STDOUT_FILENO, "\x1B" "999C" "\x1B" "999B", 10) != 10)

This works because of what is specified in §5.1.1.2 Translation phases — where phase 5 converts escape sequences and phase 6 combines adjacent string literals.

I observe that there are 10 non-null characters in this — if you intended to write the byte 0x01 followed by 5 characters (twice), then 12 makes more sense, and you need to alter where the strings break, of course.

This test code prints 11:

#include <stdio.h>

int main(void)
{
    char data[] = "\x1b" "999C" "\x1b" "999B";
    printf("%zu\n", sizeof(data));
    return 0;
}

Remove the " " sequences, and GCC complains:

xe43.c: In function ‘main’:
xe43.c:5:19: error: hex escape sequence out of range [-Werror]
     char data[] = "\x1b999C\x1b999B";
                   ^~~~~~~~~~~~~~~~~~
xe43.c:5:19: error: hex escape sequence out of range [-Werror]
cc1: all warnings being treated as errors

I compile with the -Werror option; otherwise, it would only be a warning. If compiled without -Werror and run, it produces the answer 3, not 11.

错误:十六进制逃逸序列超出范围,写功能是从3个区域读取12个字节

请爱~陌生人 2025-02-20 16:25:47

看起来您已经弄清楚了,但是对于遇到这个问题的其他任何人来说,多年来失败的射线广播中的Unity行为发生了变化。

这些天,您还应该能够检查命中率是否为空。

并命中率,如果命中率为null,则应丢下错误。

检查物理的结果。raycast是必经之路。

It looks like you figured it out, but for anyone else who hits this problem, Unity's behavior inside a failed raycast has changed over the years.

These days, you should also be able to check hit for a null.

And Hit.collider should be throwing an error if hit is null.

Checking the result of the Physics.Raycast is the way to go though.

被射线播种激活/停用的面板,停用不起作用

请爱~陌生人 2025-02-20 12:01:13

此处提供的所有出色答案都集中在原始海报的具体要求上,并集中于
{x,y,z} in {x,y,z} 的解决方案。
他们忽略的是这个问题的更广泛含义:
如何针对多个值测试一个变量?
如果使用字符串,则提供的解决方案对部分命中无效:
测试字符串“野生”是否在多个值中

>>> x = "Wild things"
>>> y = "throttle it back"
>>> z = "in the beginning"
>>> if "Wild" in {x, y, z}: print (True)
... 

,或者

>>> x = "Wild things"
>>> y = "throttle it back"
>>> z = "in the beginning"
>>> if "Wild" in [x, y, z]: print (True)
... 

在这种情况下,最容易转换为字符串,

>>> [x, y, z]
['Wild things', 'throttle it back', 'in the beginning']
>>> {x, y, z}
{'in the beginning', 'throttle it back', 'Wild things'}
>>> 

>>> if "Wild" in str([x, y, z]): print (True)
... 
True
>>> if "Wild" in str({x, y, z}): print (True)
... 
True

则应注意,如 @codeforester 所述,该方法范围丢失了此方法,如:

>>> x=['Wild things', 'throttle it back', 'in the beginning']
>>> if "rot" in str(x): print(True)
... 
True

3个字母 rot 确实存在于列表中,但不是单个单词。对“腐烂”的测试将失败,但是如果列表项目之一是“地狱中的腐烂”,那也将失败。
结果是,如果使用此方法,请注意您的搜索标准,并注意它确实有此限制。

All of the excellent answers provided here concentrate on the specific requirement of the original poster and concentrate on the if 1 in {x,y,z} solution put forward by Martijn Pieters.
What they ignore is the broader implication of the question:
How do I test one variable against multiple values?
The solution provided will not work for partial hits if using strings for example:
Test if the string "Wild" is in multiple values

>>> x = "Wild things"
>>> y = "throttle it back"
>>> z = "in the beginning"
>>> if "Wild" in {x, y, z}: print (True)
... 

or

>>> x = "Wild things"
>>> y = "throttle it back"
>>> z = "in the beginning"
>>> if "Wild" in [x, y, z]: print (True)
... 

for this scenario it's easiest to convert to a string

>>> [x, y, z]
['Wild things', 'throttle it back', 'in the beginning']
>>> {x, y, z}
{'in the beginning', 'throttle it back', 'Wild things'}
>>> 

>>> if "Wild" in str([x, y, z]): print (True)
... 
True
>>> if "Wild" in str({x, y, z}): print (True)
... 
True

It should be noted however, as mentioned by @codeforester, that word boundries are lost with this method, as in:

>>> x=['Wild things', 'throttle it back', 'in the beginning']
>>> if "rot" in str(x): print(True)
... 
True

the 3 letters rot do exist in combination in the list but not as an individual word. Testing for " rot " would fail but if one of the list items were "rot in hell", that would fail as well.
The upshot being, be careful with your search criteria if using this method and be aware that it does have this limitation.

请爱~陌生人 2025-02-19 03:58:36

完全不要写循环。您对列表中应发生的元素的期望是什么?sup> 1 ?从您的样本中看来,它应该至少一次,但可能完全是一次。

然后选择适当的表达您的期望清楚地表达了:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<string> l = new List<string> { "one", "two", "three" };
        string j = l.Single(item=>item=="one");       

        Console.WriteLine(j);
    }
}

如果一个元素完全不符合我们的标准,则以上会引发异常。您可以选择第一个最后一个(或带有 ordeffault )变体以表达您的要求和期望。


1 或换句话说,如果列表为空或列表中没有元素与您的搜索条件匹配您的期望是什么?

您的Python代码似乎只是假设两个都不是真实的。 C#旨在帮助您发现诸如此类摇摇欲坠的假设即将发挥作用的地方,并防止您以这种假设编写代码。

从历史上看,未分配的变量一直是很难追踪错误的巨大来源,因为它们要么包含垃圾(通常但并非总是很快就会引起错误)或默认值(在相当长的一段时间内看起来像是真正的价值),症状在与破裂的假设完全不同的位置出现。

Don't write the loop at all. What is your expectation for how often an element in your list should occur1? From your sample, it appears it should be at least once, but maybe exactly once.

Then pick the appropriate LINQ method that expresses your expectations clearly:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<string> l = new List<string> { "one", "two", "three" };
        string j = l.Single(item=>item=="one");       

        Console.WriteLine(j);
    }
}

The above will throw an exception if exactly one element doesn't match our criteria. You may instead pick First or Last (or with OrDefault) variants to express your requirements and expectations.


1 Or to put it another way, what is your expectations if the list is empty or no elements in the list match your search criteria?

Your python code appears to continue just assuming that neither of those are true. C# was designed to help you spot where shaky assumptions such as this are coming into play and prevent you from writing code with such assumptions.

Unassigned variables have, historically, been a massive source of hard to track down bugs because they either contain garbage (often but not always provoking an error quite soon) or a default value (which may look like a genuine value for quite some time), with the symptoms arising in a completely different location to the broken assumption.

在其内部使用变量在其外部进行循环范围。在python中可能是可能的,但在C#中不可能

请爱~陌生人 2025-02-18 20:30:34

带有2个硬件内核的处理器一次可以在两个线程上工作吗?

是的,...

...但是,想象一下自己回到维多利亚时代,雇用一堆文员来执行复杂的计算。他们需要的所有数据都在一本书中,他们应该将所有结果写回同一本书。

这本书就像计算机的内存一样,店员就像单独的CPU。由于只有一个店员可以在任何给定时间使用这本书,因此似乎没有多个以上的人,... ...

...除非您给每个店员一个记事本。他们可以去书籍,复制一些数字,然后在他们自己的记事本上工作一段时间,然后才返回从记事本的部分结果复制到书中的部分结果。这允许其他文员在书籍中任何一个文员时做一些有用的工作。

记事本就像是计算机的级别1个缓存与单个CPU关联的内存,并保存已读取的数据副本,或者需要写回主内存。计算机硬件会根据需要自动复制主内存和缓存之间的数据,因此程序不一定需要意识到缓存甚至存在。 (请参阅 https://en.wikipedia.org/wiki/wiki/cache_coherence

但是, em>程序员应该注意:如果您可以构建程序,以便将不同的线程花费大部分时间读取和编写私人变量,并且相对较少的时间访问与其他线程共享的变量,那么大多数私有变量访问将不超过L1缓存,并且线程将能够并行运行。另一方面,如果所有线程都尝试同时使用相同的变量,或者如果线程都尝试在大量数据上迭代(太大而无法适合缓存),那么它们的能力将较少。并行工作。

另请参阅:

https://en.wikipedia.org/wiki/cache_hierarchy

Does processor with 2 hardware cores can work over two threads at a time?

Yes,...

...But, Imagine yourself back in Victorian times, hiring a bunch of clerks to perform a complex computation. All of the data that they need are in one book, and they're supposed to write all of their results back into the same book.

The book is like a computer's memory, and the clerks are like individual CPUs. Since only one clerk can use the book at any given time, then it might seem as if there's no point in having more than one of them,...

... Unless, you give each clerk a notepad. They can go to the book, copy some numbers, and then work for a while just from their own notepad, before they return to copy a partial result from their notepad into the book. That allows other clerks to do some useful work when any one clerk is at the book.

The notepads are like a computer's Level 1 caches—relatively small areas of high-speed memory that are associated with a single CPU, and which hold copies of data that have been read from, or need to be written back to the main memory. The computer hardware automatically copies data between main memory and the cache as needed, so the program does not necessarily need to be aware that the cache even exists. (see https://en.wikipedia.org/wiki/Cache_coherence)

But, the programmer should to be aware: If you can structure your program so that different threads spend most of their time reading and writing private variables, and relatively little time accessing variables that are shared with other threads, then most of the private variable accesses will go no further than the L1 cache, and the threads will be able to truly run in parallel. If, on the other hand, threads all try to use the same variables at the same time, or if threads all try to iterate over large amounts of data (too large to all fit in the cache,) then they will have much less ability to work in parallel.

See also:

https://en.wikipedia.org/wiki/Cache_hierarchy

多层处理器是否真的并行执行工作?

请爱~陌生人 2025-02-18 20:28:28
a{
  color: white;
  text-decoration: none;
}

a{
  color: white;
  text-decoration: none;
}

链接不会改变颜色,并摆脱文本解释

请爱~陌生人 2025-02-18 19:35:34

尝试使用bitmap.factory类,此链接将为您提供帮助
加载大型位图有效地

Try to use Bitmap.Factory class, this link will help you
Loading Large Bitmaps Efficiently

&quot“画布:尝试绘制太大的位图”当Android n显示大小比小时大

请爱~陌生人 2025-02-18 18:46:18

这可能很棘手。

考虑一下它的一种方法是,您需要确定导入路径的根,然后原始导入是相对于它的。

假设 $ {PWD} Protos 的父。

示例#1:

如果您使用 $ {pwd} 作为 proto_path

protoc \
--proto_path=${PWD} \
--go_out=${PWD} \
  ${PWD}/protos/auth/auth_service.proto \
  ${PWD}/protos/auth/user.proto

导入应为导入“ protos/auth/auth/user.proto”;

示例#2:

如果您使用 Protos 作为 proto_path

protoc \
--proto_path=${PWD}/protos \
--go_out=${PWD} \
  ${PWD}/protos/auth/auth_service.proto \
  ${PWD}/protos/auth/user.proto

导入应为导入“ auth/user.proto”;

注释在所有情况下, proto 文件参考必须由(之一) proto_path之一

settings.json

"protoc": {
    "path": "${workspaceRoot}/protoc-21.2-linux-x86_64/bin/protoc",
    "compile_on_save": true,
    "options": [
        "--proto_path=${workspaceRoot}/protoc-21.2-linux-x86_64/include",
        "--proto_path=${workspaceRoot}/protos",
        "--go_out=${workspaceRoot}"
    ]
}

This can be tricky.

One way to think about it is that you need to determine the root of the import path and then proto imports are relative to it.

Assuming ${PWD} is the parent of protos.

Example #1:

If you use ${PWD} as the proto_path:

protoc \
--proto_path=${PWD} \
--go_out=${PWD} \
  ${PWD}/protos/auth/auth_service.proto \
  ${PWD}/protos/auth/user.proto

Then the import should be import "protos/auth/user.proto";

Example #2:

If you use protos as the proto_path:

protoc \
--proto_path=${PWD}/protos \
--go_out=${PWD} \
  ${PWD}/protos/auth/auth_service.proto \
  ${PWD}/protos/auth/user.proto

Then the import should be import "auth/user.proto";.

NOTE In all cases, the proto file references must be prefixed by (one of) a proto_path.

settings.json:

"protoc": {
    "path": "${workspaceRoot}/protoc-21.2-linux-x86_64/bin/protoc",
    "compile_on_save": true,
    "options": [
        "--proto_path=${workspaceRoot}/protoc-21.2-linux-x86_64/include",
        "--proto_path=${workspaceRoot}/protos",
        "--go_out=${workspaceRoot}"
    ]
}

从不同的文件导入原始

请爱~陌生人 2025-02-18 16:27:43

我会使用脚本

int n=4;
range r=1..n;

int a[r]=[1,3,2,5];

tuple t
{
  key int rank;
  int value;
}

{t} s={};

execute
{
  var rank=0;
  for(var i in r)
  {
    for(var j=1;j<=a[i];j++)
    {
      rank++;
      s.add(rank,a[i])
    }
  }
}

int b[k in 1..card(s)]=item(s,<k>).value;
execute
{
  writeln(b);
}

[1 3 3 3 2 2 5 5 5 5 5]

I would use scripting

int n=4;
range r=1..n;

int a[r]=[1,3,2,5];

tuple t
{
  key int rank;
  int value;
}

{t} s={};

execute
{
  var rank=0;
  for(var i in r)
  {
    for(var j=1;j<=a[i];j++)
    {
      rank++;
      s.add(rank,a[i])
    }
  }
}

int b[k in 1..card(s)]=item(s,<k>).value;
execute
{
  writeln(b);
}

gives

[1 3 3 3 2 2 5 5 5 5 5]

如何从另一个定义的数组定义数组?

请爱~陌生人 2025-02-18 04:11:27

这是 Dintictby 方法的通用实现,该方法返回了组的最后记录。

示意性地进行以下调用时:

query = query.DistinctBy(e => e.EmpId, e => e.EffectiveDt);
// or with complex keys
query = query.DistinctBy(e => new { e.EmpId, e.Other }, e => new { e.EffectiveDt, e.SomeOther});

或完全动态

query = query.DistinctBy("EmpId", "EffectiveDt");

函数会生成以下查询:

query = 
   from d in query.Select(d => d.EmpId).Distinct()
   from e in query
        .Where(e => e.EmpId == d)
        .OrderByDescending(e => e.EffectiveDt)
        .Take(1)
    select e;

或使用复杂的键:

query = 
   from d in query.Select(d => new { d.EmpId, d.Other }).Distinct()
   from e in query
        .Where(e => e.EmpId == d.EmpId && e.Other == d.Other)
        .OrderByDescending(e => e.EffectiveDt)
        .ThenByDescending(e => e.SomeOther)
        .Take(1)
    select e;

实现:

public static class QueryableExtensions
{
    public static IQueryable<T> DistinctBy<T>(
        this IQueryable<T> source,
        string distinctPropName,
        string maxPropName)
    {
        var entityParam = Expression.Parameter(typeof(T), "e");
        var distinctBy = Expression.Lambda(MakePropPath(entityParam, distinctPropName), entityParam);
        var maxBy = Expression.Lambda(MakePropPath(entityParam, maxPropName), entityParam);

        var queryExpression = Expression.Call(typeof(QueryableExtensions), nameof(QueryableExtensions.DistinctBy),
            new[] { typeof(T), distinctBy.Body.Type, maxBy.Body.Type },
            Expression.Constant(source),
            Expression.Quote(distinctBy),
            Expression.Quote(maxBy));

        var executionLambda = Expression.Lambda<Func<IQueryable<T>>>(queryExpression);
        return executionLambda.Compile()();
    }

    public static IQueryable<T> DistinctBy<T, TKey, TMax>(
        this IQueryable<T>        source, 
        Expression<Func<T, TKey>> distinctBy, 
        Expression<Func<T, TMax>> maxBy)
    {
        var distinctQuery = source.Select(distinctBy).Distinct();

        var distinctParam = Expression.Parameter(typeof(TKey), "d");
        var entityParam   = distinctBy.Parameters[0];

        var mapping = MapMembers(distinctBy.Body, distinctParam).ToList();

        var orderParam  = maxBy.Parameters[0];
        var oderMapping = CollectMembers(maxBy.Body).ToList();

        var whereExpr = mapping.Select(t => Expression.Equal(t.Item1, t.Item2))
            .Aggregate(Expression.AndAlso);
        var whereLambda = Expression.Lambda(whereExpr, entityParam);

        // d => query.Where(x => d.distinctBy == x.distinctBy).Take(1)
        Expression selectExpression = Expression.Call(typeof(Queryable), nameof(Queryable.Where), new[] { typeof(T) },
            source.Expression,
            whereLambda);

        // prepare OrderByPart
        for (int i = 0; i < oderMapping.Count; i++)
        {
            var orderMethod = i == 0 ? nameof(Queryable.OrderByDescending) : nameof(Queryable.ThenByDescending);

            var orderItem = oderMapping[i];
            selectExpression = Expression.Call(typeof(Queryable), orderMethod, new[] { typeof(T), orderItem.Type },
                selectExpression, Expression.Lambda(orderItem, orderParam));
        }

        // Take(1)
        selectExpression = Expression.Call(typeof(Queryable), nameof(Queryable.Take), new[] { typeof(T) },
            selectExpression,
            Expression.Constant(1));

        var selectManySelector =
            Expression.Lambda<Func<TKey, IEnumerable<T>>>(selectExpression, distinctParam);

        var selectManyQuery = Expression.Call(typeof(Queryable), nameof(Queryable.SelectMany),
            new[] { typeof(TKey), typeof(T) }, distinctQuery.Expression, selectManySelector);

        return source.Provider.CreateQuery<T>(selectManyQuery);
    }

    static Expression MakePropPath(Expression objExpression, string path)
    {
        return path.Split('.').Aggregate(objExpression, Expression.PropertyOrField);
    }

    private static IEnumerable<Tuple<Expression, Expression>> MapMembers(Expression expr, Expression projectionPath)
    {
        switch (expr.NodeType)
        {
            case ExpressionType.New:
            {
                var ne = (NewExpression)expr;

                for (int i = 0; i < ne.Arguments.Count; i++)
                {
                    foreach (var e in MapMembers(ne.Arguments[i], Expression.MakeMemberAccess(projectionPath, ne.Members[i])))
                    {
                        yield return e;
                    }
                }
                break;
            }

            default:
                yield return Tuple.Create(projectionPath, expr);
                break;
        }
    }

    private static IEnumerable<Expression> CollectMembers(Expression expr)
    {
        switch (expr.NodeType)
        {
            case ExpressionType.New:
            {
                var ne = (NewExpression)expr;

                for (int i = 0; i < ne.Arguments.Count; i++)
                {
                    yield return ne.Arguments[i];
                }
                break;
            }

            default:
                yield return expr;
                break;
        }
    }
}

This is universal implementation of DistinctBy method, which returns last record of the group.

Schematically when you make the following call:

query = query.DistinctBy(e => e.EmpId, e => e.EffectiveDt);
// or with complex keys
query = query.DistinctBy(e => new { e.EmpId, e.Other }, e => new { e.EffectiveDt, e.SomeOther});

Or fully dynamic

query = query.DistinctBy("EmpId", "EffectiveDt");

Function generates the following query:

query = 
   from d in query.Select(d => d.EmpId).Distinct()
   from e in query
        .Where(e => e.EmpId == d)
        .OrderByDescending(e => e.EffectiveDt)
        .Take(1)
    select e;

Or with complex keys:

query = 
   from d in query.Select(d => new { d.EmpId, d.Other }).Distinct()
   from e in query
        .Where(e => e.EmpId == d.EmpId && e.Other == d.Other)
        .OrderByDescending(e => e.EffectiveDt)
        .ThenByDescending(e => e.SomeOther)
        .Take(1)
    select e;

And realisation:

public static class QueryableExtensions
{
    public static IQueryable<T> DistinctBy<T>(
        this IQueryable<T> source,
        string distinctPropName,
        string maxPropName)
    {
        var entityParam = Expression.Parameter(typeof(T), "e");
        var distinctBy = Expression.Lambda(MakePropPath(entityParam, distinctPropName), entityParam);
        var maxBy = Expression.Lambda(MakePropPath(entityParam, maxPropName), entityParam);

        var queryExpression = Expression.Call(typeof(QueryableExtensions), nameof(QueryableExtensions.DistinctBy),
            new[] { typeof(T), distinctBy.Body.Type, maxBy.Body.Type },
            Expression.Constant(source),
            Expression.Quote(distinctBy),
            Expression.Quote(maxBy));

        var executionLambda = Expression.Lambda<Func<IQueryable<T>>>(queryExpression);
        return executionLambda.Compile()();
    }

    public static IQueryable<T> DistinctBy<T, TKey, TMax>(
        this IQueryable<T>        source, 
        Expression<Func<T, TKey>> distinctBy, 
        Expression<Func<T, TMax>> maxBy)
    {
        var distinctQuery = source.Select(distinctBy).Distinct();

        var distinctParam = Expression.Parameter(typeof(TKey), "d");
        var entityParam   = distinctBy.Parameters[0];

        var mapping = MapMembers(distinctBy.Body, distinctParam).ToList();

        var orderParam  = maxBy.Parameters[0];
        var oderMapping = CollectMembers(maxBy.Body).ToList();

        var whereExpr = mapping.Select(t => Expression.Equal(t.Item1, t.Item2))
            .Aggregate(Expression.AndAlso);
        var whereLambda = Expression.Lambda(whereExpr, entityParam);

        // d => query.Where(x => d.distinctBy == x.distinctBy).Take(1)
        Expression selectExpression = Expression.Call(typeof(Queryable), nameof(Queryable.Where), new[] { typeof(T) },
            source.Expression,
            whereLambda);

        // prepare OrderByPart
        for (int i = 0; i < oderMapping.Count; i++)
        {
            var orderMethod = i == 0 ? nameof(Queryable.OrderByDescending) : nameof(Queryable.ThenByDescending);

            var orderItem = oderMapping[i];
            selectExpression = Expression.Call(typeof(Queryable), orderMethod, new[] { typeof(T), orderItem.Type },
                selectExpression, Expression.Lambda(orderItem, orderParam));
        }

        // Take(1)
        selectExpression = Expression.Call(typeof(Queryable), nameof(Queryable.Take), new[] { typeof(T) },
            selectExpression,
            Expression.Constant(1));

        var selectManySelector =
            Expression.Lambda<Func<TKey, IEnumerable<T>>>(selectExpression, distinctParam);

        var selectManyQuery = Expression.Call(typeof(Queryable), nameof(Queryable.SelectMany),
            new[] { typeof(TKey), typeof(T) }, distinctQuery.Expression, selectManySelector);

        return source.Provider.CreateQuery<T>(selectManyQuery);
    }

    static Expression MakePropPath(Expression objExpression, string path)
    {
        return path.Split('.').Aggregate(objExpression, Expression.PropertyOrField);
    }

    private static IEnumerable<Tuple<Expression, Expression>> MapMembers(Expression expr, Expression projectionPath)
    {
        switch (expr.NodeType)
        {
            case ExpressionType.New:
            {
                var ne = (NewExpression)expr;

                for (int i = 0; i < ne.Arguments.Count; i++)
                {
                    foreach (var e in MapMembers(ne.Arguments[i], Expression.MakeMemberAccess(projectionPath, ne.Members[i])))
                    {
                        yield return e;
                    }
                }
                break;
            }

            default:
                yield return Tuple.Create(projectionPath, expr);
                break;
        }
    }

    private static IEnumerable<Expression> CollectMembers(Expression expr)
    {
        switch (expr.NodeType)
        {
            case ExpressionType.New:
            {
                var ne = (NewExpression)expr;

                for (int i = 0; i < ne.Arguments.Count; i++)
                {
                    yield return ne.Arguments[i];
                }
                break;
            }

            default:
                yield return expr;
                break;
        }
    }
}

转换为linq表达树

请爱~陌生人 2025-02-17 20:00:04

基于范围的循环(<代码>(t i:v)内部使用 std ::开始 std :: list 或任何具有 .begin() .end> .end()的类返回迭代器,

,它确实适用于指针。

但是 代码>。指针。

那么如何为数组创建调试?

如果要使用动态分配的数组,则必须将数组大小传递

template <class T> void print(T v[], size_t size) 

给循环的正常大小

for(size_t i = 0; i < size; i++) { ... }

,另一种可能性是为数组大小制作模板,例如:有人可以解释这个模板代码,以使我有一个数组的大小?

A range-based for loop (for(T i : v) internally uses std::begin and std::end to determine the range it hast to iterate over. These methods work for arrays whose size is fixed at compile time, e.g. int arr[10];, for any standard container, like std::vector, std::list, or any class that has a .begin() and .end()-method that return iterators, I think.

However, it does not work for pointers.

In fact print(T arr[]) equals print(T *arr). You can't determine the length of an array, when you only got a pointer. You can't even determine wether or not this pointer is pointing to an array. So you can't use range-based for loops with pointers.

So how to create a debug for array ?

If you want to use dynamically allocated arrays you have to pass the arrays size along

template <class T> void print(T v[], size_t size) 

and use a normal for loop

for(size_t i = 0; i < size; i++) { ... }

Another possibility is to make a template for array-size, as in this question: Can someone explain this template code that gives me the size of an array?

数组C&#x2B;&#x2B;的调试模板

请爱~陌生人 2025-02-17 14:37:12

更新:进一步谷歌搜索,我发现了这一点: https://github.com/rails/rails/rails/rails/rails/rails/rails/issues/issues/issues/issues/issues/issues /44185 ,有一个对我有用的解决方案。

基本上,方法被弃用,而新方法是使用

data: { turbo_method: :delete, turbo_confirm: "Are you sure?" }

。如果这不起作用,请尝试

rails importmap:install
rails turbo:install stimulus:install

先运行命令。

至少对我有用。

UPDATE: Googling further, I found this: https://github.com/rails/rails/issues/44185, which had a solution that worked for me.

Basically, method is deprecated, and the new way is to use

data: { turbo_method: :delete, turbo_confirm: "Are you sure?" }

instead. If this doesn't work, try running the commands

rails importmap:install
rails turbo:install stimulus:install

first.

It worked for me, at least.

Rails,为什么link_to始终使用方法[GET],即使我已经指定方法[post]或[delete]

请爱~陌生人 2025-02-17 03:16:04

如果您提供明确的断点列表 ggplot 将“服从”。因此,您可以使用以下代码:

ggplot(data=df, aes(x=date, y=value)) +
  geom_line(linetype='solid', alpha = 1, size = 1.5, color='blue') +
  geom_point(alpha = 1, size = 4, color='blue') + 
  scale_x_date(breaks = as.Date(c("2022-07-31", "2022-08-31", "2022-09-30", "2022-10-31")))

甚至更短:

ggplot(data=df, aes(x=date, y=value)) +
  geom_line(linetype='solid', alpha = 1, size = 1.5, color='blue') +
  geom_point(alpha = 1, size = 4, color='blue') + 
  scale_x_date(breaks = df$date)

产生此图:

“在此处输入图像描述”

解决方案似乎很琐碎,所以我必须问:这是您所追求的吗?

编辑

如果您有许多数据点,则相同的原理具有。绘制您的数据,但要明确分配休息时间,例如在以下代码中:
(此外,标签被旋转45°),

## mock-up data
df2 <- structure(list(date = structure(seq(19204, 19296, 1), class = "Date"),
                     value = c(seq(3.5, 3.6, length.out = 31),
                               seq(3.6, 4.05, length.out = 31),
                               seq(4.05, 4.13, length.out = 31)) ), 
                 row.names = c(NA, -93L),
                 class = "data.frame")

## define my_breaks                
my_breaks = as.Date(c("2022-07-31", "2022-08-31", "2022-09-30", "2022-10-31"))

ggplot(data=df2, aes(x=date, y=value)) +
  geom_line(linetype='solid', alpha = 1, size = 1.5, color='blue') +
  geom_point(alpha = 1, size = 3, color='blue') + 
  scale_x_date(breaks = my_breaks) +                          ## breaks
  theme(axis.text.x = element_text(angle = 45, hjust = 1))    ## rotate

该标签得出以下图:

”在此处输入图像描述”

If you provide an explicit list of breaks, ggplot will "obey". So, you could use the following code:

ggplot(data=df, aes(x=date, y=value)) +
  geom_line(linetype='solid', alpha = 1, size = 1.5, color='blue') +
  geom_point(alpha = 1, size = 4, color='blue') + 
  scale_x_date(breaks = as.Date(c("2022-07-31", "2022-08-31", "2022-09-30", "2022-10-31")))

or even shorter:

ggplot(data=df, aes(x=date, y=value)) +
  geom_line(linetype='solid', alpha = 1, size = 1.5, color='blue') +
  geom_point(alpha = 1, size = 4, color='blue') + 
  scale_x_date(breaks = df$date)

yielding this plot:

enter image description here

The solution seems trivial, so I have to ask: Is this what you are after?

Edit

In case you have many data points, the same principle holds. Plot your data, but assign your breaks explicitly, like in the following code:
(In addition, the labels are rotated by 45°)

## mock-up data
df2 <- structure(list(date = structure(seq(19204, 19296, 1), class = "Date"),
                     value = c(seq(3.5, 3.6, length.out = 31),
                               seq(3.6, 4.05, length.out = 31),
                               seq(4.05, 4.13, length.out = 31)) ), 
                 row.names = c(NA, -93L),
                 class = "data.frame")

## define my_breaks                
my_breaks = as.Date(c("2022-07-31", "2022-08-31", "2022-09-30", "2022-10-31"))

ggplot(data=df2, aes(x=date, y=value)) +
  geom_line(linetype='solid', alpha = 1, size = 1.5, color='blue') +
  geom_point(alpha = 1, size = 3, color='blue') + 
  scale_x_date(breaks = my_breaks) +                          ## breaks
  theme(axis.text.x = element_text(angle = 45, hjust = 1))    ## rotate

Which yields this plot:

enter image description here

GGPLOT2 X轴显示下个月的起点,而不是本月的结束日期

请爱~陌生人 2025-02-17 01:33:26

替换此段:

+ ",CCCC," + ",," + ",," +

随之而来的是:

+ ",CCCC,,," + 

但是您将在专用的CSV库中更好地做 ,其中Nuget上有几种不错的选择。

此外,如果您使用的是 StringBuilder ,因为您听说它更快,请记住,更快的是相对的。 StringBuilder 的速度比此类工作的字符串串联要快,但是如果您最终要写入网络流,文件或Web响应

Replace this segement:

+ ",CCCC," + ",," + ",," +

with this:

+ ",CCCC,,," + 

But you'll really do MUCH better with a dedicated csv library, of which there are several good options on NuGet.

Additionally, if you're using StringBuilder because you heard it's faster, remember that faster is relative. StringBuilder is faster than string concatenation for this kind of work, but if you're ultimately going to writing to a network stream, file, or web response you'll do even better using a StreamWriter

将存储的过程数据转换为CSV。我试图弄清楚如何使用空的逗号和报价

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

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