雪化雨蝶

文章 评论 浏览 30

雪化雨蝶 2025-02-17 09:36:15

一些注释:

  1. 在2e8行上运行时,您可能需要确保不要将所有内容保留在内存中并使用快速操作。 data.table 软件包由于其性能和内存替代品而在这里很有用。也许您不需要在步骤2中将所有培训集导出到全球环境中;我看不到您在哪里使用的地方,它将占用大量内存(内存使用可能成为这里的主要问题)。
  2. 纯粹看性能,保存所有模型作为RDS对象非常耗时。除非以后需要,否则跳过此步骤可能会加快速度。如果您有内存问题并需要溢出到磁盘,则可以考虑保存预测的输出,也许使用 data.table :: fwrite ,然后随后使用 data.table :: fread with读取它。
  3. 由于某种原因,尽管 Ranger 使用多个线程进行预测函数,但根据您可以并行化的方式,并行运行这些步骤仍可能会提供一些速度改进。在Linux环境中, mclapply forks该过程,并且不会将数据复制到所有节点,因此使用其他并行化选项YMMV。其他评论/答复已经在其他评论/答复中提出了一些同行安排方式的好建议。
  4. 除非我忽略了它,否则在我看来,您可以一次对训练组进行采样,然后分为多个并行集,因为我看不到您在哪里使用多个迭代,这些迭代彼此相互依次。

以下是一个可能进一步优化的示例,具体取决于记忆配置文件

library(data.table)
library(parallel)
ncores <- floor(detectCores()/2)-1 # set no. of cores for parallel processing
trs <- setDT(train_set, keep.rownames = TRUE) # turn into data.table 
n <- 1e2 # number of sampling iterations
# sample once, then label as iterations
results <- trs[c(sample(which(trs$class==0), 50*n, replace = TRUE), 
    sample(which(trs$class==1), 60*n, replace = TRUE))]
results[, iteration:=NA_character_]
results[class==0, iteration := as.character(cut(1:(50*n), n, labels = 1:n))]
results[class==1, iteration := as.character(cut(1:(60*n), n, labels = 1:n))]
results[, iteration := factor(iteration, order(unique(as.numeric(iteration))))]

# Step 3: Train Models on Each Subset:
calc_model <- \(x) ranger(class ~  height + weight + salary, data = x, probability = TRUE)
predict_model <- \(x) data.table(predict(calc_model(x), data = test_set)$predictions)[, id:=.I]
# save time and memory not saving model as RDS file; potentially, the list of models could 
# be saved in one write operation, which could also be faster

# Step 4: Combine All Models and Use Combined Model to Make Predictions on the Test Set:
# for some reason, despite predict using multiple threads, I still profit 
# from parallelization here; skipping generation of X to save memory
results_2 <- mclapply(results[, unique(iteration)], 
    \(x){predict_model(results[iteration == x])}, mc.cores=ncores)
final_predictions <- rbindlist(results_2)[, lapply(.SD, mean), .SDcols=c("0", "1"), by="id"]

在2022-06-27上由(v2.0.1)

A few notes:

  1. When running on 2E8 rows, you may want to make sure not to keep everything in memory and use fast operations. The data.table package may be useful here due to its performance and in-memory replacements. Maybe you do not need to export all training sets into the Global environment in step 2; I do not see where you use that, and it will take up a lot of memory (memory usage may become a primary concern here).
  2. Looking purely at performance, saving all the models as RDS objects is quite time consuming. Unless required later, skipping this step might speed things up quite a bit. If you have memory issues and need to spill to disk, you may consider saving the predicted output, perhaps with data.table::fwrite and subsequently read it in with data.table::fread.
  3. For some reason, despite the ranger and predict functions using multiple threads, running these steps in parallel may still give some speed improvements, depending on the way you can parallelize. In a linux environment, mclapply forks the process and does not copy data to all the nodes, so YMMV using other parallelization options. A few good suggestions for alternative ways to schedule in parallel are already in other comments/replies.
  4. Unless I overlooked it, it seems to me that you could sample your training set once and then split into multiple parallel sets, as I did not see where you would use multiple iterations that feed sequentially into each other.

Below is one example that probably could be optimized further, depending on the memory profile

library(data.table)
library(parallel)
ncores <- floor(detectCores()/2)-1 # set no. of cores for parallel processing
trs <- setDT(train_set, keep.rownames = TRUE) # turn into data.table 
n <- 1e2 # number of sampling iterations
# sample once, then label as iterations
results <- trs[c(sample(which(trs$class==0), 50*n, replace = TRUE), 
    sample(which(trs$class==1), 60*n, replace = TRUE))]
results[, iteration:=NA_character_]
results[class==0, iteration := as.character(cut(1:(50*n), n, labels = 1:n))]
results[class==1, iteration := as.character(cut(1:(60*n), n, labels = 1:n))]
results[, iteration := factor(iteration, order(unique(as.numeric(iteration))))]

# Step 3: Train Models on Each Subset:
calc_model <- \(x) ranger(class ~  height + weight + salary, data = x, probability = TRUE)
predict_model <- \(x) data.table(predict(calc_model(x), data = test_set)$predictions)[, id:=.I]
# save time and memory not saving model as RDS file; potentially, the list of models could 
# be saved in one write operation, which could also be faster

# Step 4: Combine All Models and Use Combined Model to Make Predictions on the Test Set:
# for some reason, despite predict using multiple threads, I still profit 
# from parallelization here; skipping generation of X to save memory
results_2 <- mclapply(results[, unique(iteration)], 
    \(x){predict_model(results[iteration == x])}, mc.cores=ncores)
final_predictions <- rbindlist(results_2)[, lapply(.SD, mean), .SDcols=c("0", "1"), by="id"]

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

并行版的代码运行需要更长的时间

雪化雨蝶 2025-02-17 08:18:30

您可以使用如下的纯虚拟驱动器。即使它是纯虚拟的,您仍然需要实施它。您不需要在派生类中声明破坏者。

class TargetClass : //I will never instantiate this class
    public ClassA,
    public ClassB
{
public:
    TargetClass() : ClassA(), ClassB() {} //I don't want to call the CommonBaseClass ctor
    virtual ~TargetClass() = 0;
};

class SubclassOfTarget :
    public TargetClass
{
public:
    SubclassOfTarget(int a) : CommonBaseClass(a), TargetClass()
    {}
};

TargetClass::~TargetClass()
{}

int main()
{
    SubclassOfTarget c(15);
    c.DoSomething();
    c.DoSomethingElse();
}

You can use a pure virtual destructor as follows. Even although it is pure virtual, you still need to implement it. You do not need to declare destructors in the derived classes.

class TargetClass : //I will never instantiate this class
    public ClassA,
    public ClassB
{
public:
    TargetClass() : ClassA(), ClassB() {} //I don't want to call the CommonBaseClass ctor
    virtual ~TargetClass() = 0;
};

class SubclassOfTarget :
    public TargetClass
{
public:
    SubclassOfTarget(int a) : CommonBaseClass(a), TargetClass()
    {}
};

TargetClass::~TargetClass()
{}

int main()
{
    SubclassOfTarget c(15);
    c.DoSomething();
    c.DoSomethingElse();
}

问题创建抽象类,没有虚拟纯方法C&#x2B;&#x2B;

雪化雨蝶 2025-02-17 08:05:15

WASM没有从文件系统中读取。您需要将文件复制到WASM虚拟文件系统中,以便能够引用文件。

Wasm doesn't read from the file system. You need to copy files into wasm virtual file system for it to be able to reference files.

ffmpeg.wasm-用节点JS检索视频元数据

雪化雨蝶 2025-02-17 06:53:53

旧参数DefaultTrackSelector最近使用您的问题可能与该更改有关。

The old parameters DefaultTrackSelector took have recently been deprecated with the 2.18.0 update and your problem might be related to that change.

java.lang.nosuchmethoderror:无虚拟方法setParameters(lcom/google/google/android/exoplayer2/trackSelection/defaultTrackSelector $ paramet

雪化雨蝶 2025-02-17 03:49:22

您的问题是该部分:使用getType = std :: function&lt; const t&amp;(void)&gt ;; gt ;; get {[this]()()(){return Internal; }}

lambda在此处不返回内部作为参考,因此返回 internal 的副本,在这里 - 我不知道 std :: function 已实现 - std :: function 必须保留 internal 的副本,但将其返回以引用该副本而不是悬空。

将其更改为 get {[this]() - &gt;夯; {返回内部; }} 似乎解决了问题。

Your problem is this part: using getType = std::function<const T&(void)>; in combination with get{[this] () { return internal; }}.

The lambda does not return the internal as a reference here, so a copy of internal is returned, and - here I don't know how std::function is implemented - std::function has to hold a copy of internal but returns it as a reference to that copy which is than dangling.

Changing it to get{[this] () -> T& { return internal; }} seems to solve the problem.

为什么在优化标志上不正确的返回值不正确?

雪化雨蝶 2025-02-17 02:10:45

事实证明,这比我预期的要简单得多。 group_add()订阅消息,但是如果没有该步骤,仍然可以 group_send()到组 - 因此可以将异常处理播放器1发送到主机组没有任何玩家在该组中收到消息。

Turns out this was a lot simpler than I expected. group_add() subscribes to messages, but without that step it is still possible to group_send() to a group - so an exception processing player 1 can be sent to the host group without any players receiving messages in that group.

Django频道 - 可能“仅写”频道组?

雪化雨蝶 2025-02-16 18:54:34

使用 natsort 用于自然排序:

from natsort import natsorted

mac_list = natsorted(output_list, key=lambda d: d['interface'])

或分开并转换为整数:

mac_list = sorted(output_list,
                  key=lambda d: tuple(map(int, d['interface'].split('/'))))

输出:输出:

[{'interface': '0/3', 'mac': '45:67:89:AB:CD:EF'},
 {'interface': '0/5', 'mac': '34:56:78:9A:BC:DE'},
 {'interface': '0/16', 'mac': '12:34:56:78:9A:BC'},
 {'interface': '0/20', 'mac': '01:23:45:67:89:AB'},
 {'interface': '0/31', 'mac': '23:45:67:89:AB:CD'}]

Use natsort for natural sorting:

from natsort import natsorted

mac_list = natsorted(output_list, key=lambda d: d['interface'])

Or split and convert to integers:

mac_list = sorted(output_list,
                  key=lambda d: tuple(map(int, d['interface'].split('/'))))

output:

[{'interface': '0/3', 'mac': '45:67:89:AB:CD:EF'},
 {'interface': '0/5', 'mac': '34:56:78:9A:BC:DE'},
 {'interface': '0/16', 'mac': '12:34:56:78:9A:BC'},
 {'interface': '0/20', 'mac': '01:23:45:67:89:AB'},
 {'interface': '0/31', 'mac': '23:45:67:89:AB:CD'}]

python在字典列表中按数字排序

雪化雨蝶 2025-02-16 15:57:17

通过运行 npm I - 仅包锁命令解决了此问题。

如果它抛出 npm warn config global`–-global`,`` - local`被弃用''。使用` - location = global` 错误,然后运行 npm i -package-lock-ly-ly-ly-lecocation = global

Solved this issue by running npm i --package-lock-only command.

if it throws npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead error then run npm i --package-lock-only --location=global

高度严重性脆弱性NPX创建反应应用

雪化雨蝶 2025-02-16 09:20:51

TLDR

JavaScript具有词汇(也称为静态)范围和闭合。这意味着您可以通过查看源代码来告诉标识符的范围。

这四个范围是:

  1. 全局 - 所有
  2. 功能可见 - 在功能(及其子函数和块)
  3. 块中可见 - 在块(及其子块)
  4. 模块中可见

模块中可见 -在特殊情况外的 全局和模块范围,变量使用 var (函数范围), LET (块范围)和 const (块范围)。大多数其他形式的标识符声明具有严格模式的块范围。

概述

范围是标识符有效的代码库的区域。

词汇环境是标识符名称与与之关联的值之间的映射。

范围是由词汇环境的链接嵌套形成的,嵌套中的每个级别都对应于祖先执行上下文的词汇环境。

这些链接的词汇环境形成了范围“链”。标识符分辨率是沿该链搜索匹配标识符的过程。

标识符分辨率仅在一个方向上发生:向外。这样,外词汇环境就无法“看到”内部词汇环境。

确定 scope ///www.ecma-internations.org/ecma-262/10.0/index.html#sec-names-and-keywords“ rel =“ noreferrer”>“ noreferrer”> didentifier 在

  1. javascript 被宣布
  2. 您是否在严格模式 href =“ https://developer.mozilla.org/en-us/docs/glossary/sloppy_mode” rel =“ noreferrer”> nonoreferrer“> non-Strict模式

可以声明的某些方式:

  1. var var var var var ,<代码>让和 const
  2. 函数参数
  3. 捕获块参数
  4. 函数声明
  5. 名为函数表达式
  6. 在全局对象上隐式定义属性(即,错过 var 在非图案模式下)
  7. import 语句
  8. evary

可以声明某些位置标识符:

  1. 全局上下文
  2. 函数函数正文
  3. 正常块
  4. 控制结构的顶部(例如,循环,循环 ,
  5. 如果
  6. 等等

​在这种情况下,它们被添加为全局对象上的属性并具有全局范围。在 eval 函数中使用了单独的规则。

让&const

使用 LET const 具有块范围,除了直接在全球上下文中声明时, 标识符具有块范围具有全球范围。

注意: const var 升起。这意味着他们的逻辑位置是其封闭范围(块或函数)的顶部。但是,使用 LET const 声明的变量无法读取或分配给,直到控件已通过源代码中的声明点为止。临时时期被称为时间死区。

function f() {
    function g() {
        console.log(x)
    }
    let x = 1
    g()
}
f() // 1 because x is hoisted even though declared with `let`!

函数参数名称

函数参数名称范围范围为功能主体。请注意,这有轻微的复杂性。声明为默认参数的函数在参数列表,而不是功能的主体。

功能声明

功能声明具有严格模式的块范围,并在非图案模式下具有函数范围。注意:基于不同浏览器的古怪历史实现,非图案模式是一组复杂的紧急规则。

命名函数表达式

名为函数表达式范围范围(例如,出于递归目的)。

在非图案模式下全局对象上的隐式定义属性

,全局对象上隐式定义的属性具有全局范围,因为全局对象位于范围链的顶部。在严格的模式下,不允许这些。

评估

字符串中,使用 var 声明的变量将放置在当前范围中,或者,如果 eval 间接使用,则作为属性作为属性全局对象。

示例

以下将引发参考器,因为名称 x y z 在函数之外没有含义 f f

function f() {
    var x = 1
    let y = 1
    const z = 1
}
console.log(typeof x) // undefined (because var has function scope!)
console.log(typeof y) // undefined (because the body of the function is a block)
console.log(typeof z) // undefined (because the body of the function is a block)

以下将为 y z 抛出参考文献,但对于 x 而不是不受块的约束。封锁控制结构的物体,例如, ,而 的行为也相似。

{
    var x = 1
    let y = 1
    const z = 1
}
console.log(x) // 1
console.log(typeof y) // undefined because `y` has block scope
console.log(typeof z) // undefined because `z` has block scope

在下面, x 在循环外看到,因为 var 具有函数范围:

for(var x = 0; x < 5; ++x) {}
console.log(x) // 5 (note this is outside the loop!)

...由于这种行为,您需要谨慎关闭循环中使用 var 声明的变量。在此处声明的变量 x 只有一个实例,它在循环外逻辑上位于逻辑上。

以下打印 5 ,五次,然后打印 5 第六次 console.log 在循环外:

for(var x = 0; x < 5; ++x) {
    setTimeout(() => console.log(x)) // closes over the `x` which is logically positioned at the top of the enclosing scope, above the loop
}
console.log(x) // note: visible outside the loop

以下打印未定义,因为 x 是块分布的。回调是一个异步运行的。 Let 变量的新行为意味着每个匿名函数都通过名为 x 的不同变量关闭(与> var 不同,所以整数 0 通过 4 打印。

for(let x = 0; x < 5; ++x) {
    setTimeout(() => console.log(x)) // `let` declarations are re-declared on a per-iteration basis, so the closures capture different variables
}
console.log(typeof x) // undefined

以下内容不会抛出 ReferenceError ,因为 X 的可见性不受块的约束;但是,它将打印未定义,因为该变量尚未初始化(因为语句)。

if(false) {
    var x = 1
}
console.log(x) // here, `x` has been declared, but not initialised

使用 Let 在循环的顶部声明的变量范围范围范围:循环的主体:

for(let x = 0; x < 10; ++x) {} 
console.log(typeof x) // undefined, because `x` is block-scoped

以下将抛出 ReferenceError ,因为 X 的可见性受块的约束:

if(false) {
    let x = 1
}
console.log(typeof x) // undefined, because `x` is block-scoped

使用 var , let 或 const 均示为模块的变量:

// module1.js

var x = 0
export function f() {}

//module2.js

import f from 'module1.js'

console.log(x) // throws ReferenceError

以下将在全局对象上声明属性,因为变量使用<<<代码> var 在全局上下文中以属性的形式添加到全局对象:

var x = 1
console.log(window.hasOwnProperty('x')) // true

const 在全局上下文中没有添加属性,但仍具有全局范围:

let x = 1
console.log(window.hasOwnProperty('x')) // false

函数参数可以认为是在功能主体中声明的:

function f(x) {}
console.log(typeof x) // undefined, because `x` is scoped to the function

捕获块参数范围范围为接管块体:

try {} catch(e) {}
console.log(typeof e) // undefined, because `e` is scoped to the catch block

命名函数表达式仅范围范围范围范围为表达式本身:

(function foo() { console.log(foo) })()
console.log(typeof foo) // undefined, because `foo` is scoped to its own expression

在非图案模式下,全局对象上隐式定义的属性是全球范围的。在严格的模式下,您会遇到错误。

x = 1 // implicitly defined property on the global object (no "var"!)

console.log(x) // 1
console.log(window.hasOwnProperty('x')) // true

在非图片模式下,功能声明具有函数范围。在严格的模式下,它们具有块范围。

'use strict'
{
    function foo() {}
}
console.log(typeof foo) // undefined, because `foo` is block-scoped

在引擎盖

范围下它的工作方式定义为词汇标识符有效的代码区域。

在JavaScript中,每个函数对象都有一个隐藏的 [[环境]] 参考,它是对词汇环境

调用函数时,将调用隐藏的 [[call]] 方法。此方法创建一个新的执行上下文,并在新的执行上下文和函数对象的词汇环境之间建立链接。它通过将 [[环境]] 值复制到外部参考在新执行环境的词汇环境上字段。

请注意,新的执行上下文与函数对象的词汇环境之间的链接称为a 闭合

因此,在JavaScript中,范围是通过外部参考文献以“链”链接在一起的词汇环境实现的。这条词汇环境链称为范围链,标识符分辨率由搜索链条寻找匹配的标识符。

找出更多

TLDR

JavaScript has lexical (also called static) scoping and closures. This means you can tell the scope of an identifier by looking at the source code.

The four scopes are:

  1. Global - visible by everything
  2. Function - visible within a function (and its sub-functions and blocks)
  3. Block - visible within a block (and its sub-blocks)
  4. Module - visible within a module

Outside of the special cases of global and module scope, variables are declared using var (function scope), let (block scope), and const (block scope). Most other forms of identifier declaration have block scope in strict mode.

Overview

Scope is the region of the codebase over which an identifier is valid.

A lexical environment is a mapping between identifier names and the values associated with them.

Scope is formed of a linked nesting of lexical environments, with each level in the nesting corresponding to a lexical environment of an ancestor execution context.

These linked lexical environments form a scope "chain". Identifier resolution is the process of searching along this chain for a matching identifier.

Identifier resolution only occurs in one direction: outwards. In this way, outer lexical environments cannot "see" into inner lexical environments.

There are three pertinent factors in deciding the scope of an identifier in JavaScript:

  1. How an identifier was declared
  2. Where an identifier was declared
  3. Whether you are in strict mode or non-strict mode

Some of the ways identifiers can be declared:

  1. var, let and const
  2. Function parameters
  3. Catch block parameter
  4. Function declarations
  5. Named function expressions
  6. Implicitly defined properties on the global object (i.e., missing out var in non-strict mode)
  7. import statements
  8. eval

Some of the locations identifiers can be declared:

  1. Global context
  2. Function body
  3. Ordinary block
  4. The top of a control structure (e.g., loop, if, while, etc.)
  5. Control structure body
  6. Modules

Declaration Styles

var

Identifiers declared using var have function scope, apart from when they are declared directly in the global context, in which case they are added as properties on the global object and have global scope. There are separate rules for their use in eval functions.

let and const

Identifiers declared using let and const have block scope, apart from when they are declared directly in the global context, in which case they have global scope.

Note: let, const and var are all hoisted. This means that their logical position of definition is the top of their enclosing scope (block or function). However, variables declared using let and const cannot be read or assigned to until control has passed the point of declaration in the source code. The interim period is known as the temporal dead zone.

function f() {
    function g() {
        console.log(x)
    }
    let x = 1
    g()
}
f() // 1 because x is hoisted even though declared with `let`!

Function parameter names

Function parameter names are scoped to the function body. Note that there is a slight complexity to this. Functions declared as default arguments close over the parameter list, and not the body of the function.

Function declarations

Function declarations have block scope in strict mode and function scope in non-strict mode. Note: non-strict mode is a complicated set of emergent rules based on the quirky historical implementations of different browsers.

Named function expressions

Named function expressions are scoped to themselves (e.g., for the purpose of recursion).

Implicitly defined properties on the global object

In non-strict mode, implicitly defined properties on the global object have global scope, because the global object sits at the top of the scope chain. In strict mode, these are not permitted.

eval

In eval strings, variables declared using var will be placed in the current scope, or, if eval is used indirectly, as properties on the global object.

Examples

The following will throw a ReferenceError because the namesx, y, and z have no meaning outside of the function f.

function f() {
    var x = 1
    let y = 1
    const z = 1
}
console.log(typeof x) // undefined (because var has function scope!)
console.log(typeof y) // undefined (because the body of the function is a block)
console.log(typeof z) // undefined (because the body of the function is a block)

The following will throw a ReferenceError for y and z, but not for x, because the visibility of x is not constrained by the block. Blocks that define the bodies of control structures like if, for, and while, behave similarly.

{
    var x = 1
    let y = 1
    const z = 1
}
console.log(x) // 1
console.log(typeof y) // undefined because `y` has block scope
console.log(typeof z) // undefined because `z` has block scope

In the following, x is visible outside of the loop because var has function scope:

for(var x = 0; x < 5; ++x) {}
console.log(x) // 5 (note this is outside the loop!)

...because of this behavior, you need to be careful about closing over variables declared using var in loops. There is only one instance of variable x declared here, and it sits logically outside of the loop.

The following prints 5, five times, and then prints 5 a sixth time for the console.log outside the loop:

for(var x = 0; x < 5; ++x) {
    setTimeout(() => console.log(x)) // closes over the `x` which is logically positioned at the top of the enclosing scope, above the loop
}
console.log(x) // note: visible outside the loop

The following prints undefined because x is block-scoped. The callbacks are run one by one asynchronously. New behavior for let variables means that each anonymous function closed over a different variable named x (unlike it would have done with var), and so integers 0 through 4 are printed.:

for(let x = 0; x < 5; ++x) {
    setTimeout(() => console.log(x)) // `let` declarations are re-declared on a per-iteration basis, so the closures capture different variables
}
console.log(typeof x) // undefined

The following will NOT throw a ReferenceError because the visibility of x is not constrained by the block; it will, however, print undefined because the variable has not been initialised (because of the if statement).

if(false) {
    var x = 1
}
console.log(x) // here, `x` has been declared, but not initialised

A variable declared at the top of a for loop using let is scoped to the body of the loop:

for(let x = 0; x < 10; ++x) {} 
console.log(typeof x) // undefined, because `x` is block-scoped

The following will throw a ReferenceError because the visibility of x is constrained by the block:

if(false) {
    let x = 1
}
console.log(typeof x) // undefined, because `x` is block-scoped

Variables declared using var, let or const are all scoped to modules:

// module1.js

var x = 0
export function f() {}

//module2.js

import f from 'module1.js'

console.log(x) // throws ReferenceError

The following will declare a property on the global object because variables declared using var within the global context are added as properties to the global object:

var x = 1
console.log(window.hasOwnProperty('x')) // true

let and const in the global context do not add properties to the global object, but still have global scope:

let x = 1
console.log(window.hasOwnProperty('x')) // false

Function parameters can be considered to be declared in the function body:

function f(x) {}
console.log(typeof x) // undefined, because `x` is scoped to the function

Catch block parameters are scoped to the catch-block body:

try {} catch(e) {}
console.log(typeof e) // undefined, because `e` is scoped to the catch block

Named function expressions are scoped only to the expression itself:

(function foo() { console.log(foo) })()
console.log(typeof foo) // undefined, because `foo` is scoped to its own expression

In non-strict mode, implicitly defined properties on the global object are globally scoped. In strict mode, you get an error.

x = 1 // implicitly defined property on the global object (no "var"!)

console.log(x) // 1
console.log(window.hasOwnProperty('x')) // true

In non-strict mode, function declarations have function scope. In strict mode, they have block scope.

'use strict'
{
    function foo() {}
}
console.log(typeof foo) // undefined, because `foo` is block-scoped

How it works under the hood

Scope is defined as the lexical region of code over which an identifier is valid.

In JavaScript, every function-object has a hidden [[Environment]] reference that is a reference to the lexical environment of the execution context (stack frame) within which it was created.

When you invoke a function, the hidden [[Call]] method is called. This method creates a new execution context and establishes a link between the new execution context and the lexical environment of the function-object. It does this by copying the [[Environment]] value on the function-object, into an outer reference field on the lexical environment of the new execution context.

Note that this link between the new execution context and the lexical environment of the function object is called a closure.

Thus, in JavaScript, scope is implemented via lexical environments linked together in a "chain" by outer references. This chain of lexical environments is called the scope chain, and identifier resolution occurs by searching up the chain for a matching identifier.

Find out more.

JavaScript中变量的范围是什么?

雪化雨蝶 2025-02-16 09:00:15

您没有通过反射计算获得“相同的CRC值”(是否反映)。这是一个完全不同的值,因为消息的位以相反的顺序处理。

“当您切换” :您只需使用与应用程序所期望的CRC定义(是否反映)。 CRC是否反映是定义CRC的几个参数之一,以及CRC,多项式,初始值以及最终独家或值的位置。您可以在一百上找到的定义不同的crcs 在这里/a>。

“为什么有两个” :前进实现之所以存在,是因为这与数学最紧密相对应,在多项式的二进制表示中,多项式最不重要的术语是多项式的最低术语。之所以存在反射的实现,是因为它可以意识到可以在软件中更简单地实现,但指令较少,但仍具有相同的错误检测性能。

这是两个具有相同多项式的常见32位CRC的示例。向前,CRC-32/BZIP位智力实现:

uint32_t crc32bzip2_bit(uint32_t crc, void const *mem, size_t len) {
    unsigned char const *data = mem;
    if (data == NULL)
        return 0;
    crc = ~crc;
    for (size_t i = 0; i < len; i++) {
        crc ^= (uint32_t)data[i] << 24;
        for (unsigned k = 0; k < 8; k++) {
            crc = crc & 0x80000000 ? (crc << 1) ^ 0x4c11db7 : crc << 1;
        }
    }
    crc = ~crc;
    return crc;
}

反射的CRC-32/ZIP位:

uint32_t crc32iso_hdlc_bit(uint32_t crc, void const *mem, size_t len) {
    unsigned char const *data = mem;
    if (data == NULL)
        return 0;
    crc = ~crc;
    for (size_t i = 0; i < len; i++) {
        crc ^= data[i];
        for (unsigned k = 0; k < 8; k++) {
            crc = crc & 1 ? (crc >> 1) ^ 0xedb88320 : crc >> 1;
        }
    }
    crc = ~crc;
    return crc;
}

主要节省是一个指令,是数据字节的转移,您可以通过反射的实现来摆脱。还有您&amp; 带有( 1 vs. 0x80000000 )的常数,这也可以保存指令或寄存器,或只需导致指令较短,具体取决于指令集中支持的即时值的大小。

对于字节计算也可以避免这种转变:

uint32_t crc32bzip2_byte(uint32_t crc, void const *mem, size_t len) {
    unsigned char const *data = mem;
    if (data == NULL)
        return 0;
    for (size_t i = 0; i < len; i++) {
        crc = (crc << 8) ^
              table_byte[((crc >> 24) ^ data[i]) & 0xff];
    }
    return crc;
}

VS。

uint32_t crc32iso_hdlc_byte(uint32_t crc, void const *mem, size_t len) {
    unsigned char const *data = mem;
    if (data == NULL)
        return 0;
    for (size_t i = 0; i < len; i++) {
        crc = (crc >> 8) ^
              table_byte[(crc ^ data[i]) & 0xff];
    }
    return crc;
}

You do not get the "same CRC value" (reflected or not) with the reflected calculation. It is an entirely different value, because the bits of the message are processed in the opposite order.

"when you switch": You simply use the CRC definition, reflected or not, that matches what the application is expecting. Whether the CRC is reflected is one of several parameters that define the CRC, along with the number of the bits in the CRC, the polynomial, the initial value, and the final exclusive or value. You can find the definition of over a hundred different CRCs here.

"why are there two": The forward implementation exists because that corresponds most closely to the mathematics, with the least significant term of the polynomial in the least significant bit of the binary representation of the polynomial. The reflected implementation exists because it was realized that it could be implemented in software a little more simply, with fewer instructions, but still have the same error-detection performance.

Here is an example for two common 32-bit CRCs with the same polynomial. Forward, CRC-32/BZIP bit-wise implementation:

uint32_t crc32bzip2_bit(uint32_t crc, void const *mem, size_t len) {
    unsigned char const *data = mem;
    if (data == NULL)
        return 0;
    crc = ~crc;
    for (size_t i = 0; i < len; i++) {
        crc ^= (uint32_t)data[i] << 24;
        for (unsigned k = 0; k < 8; k++) {
            crc = crc & 0x80000000 ? (crc << 1) ^ 0x4c11db7 : crc << 1;
        }
    }
    crc = ~crc;
    return crc;
}

Reflected CRC-32/ZIP bit-wise:

uint32_t crc32iso_hdlc_bit(uint32_t crc, void const *mem, size_t len) {
    unsigned char const *data = mem;
    if (data == NULL)
        return 0;
    crc = ~crc;
    for (size_t i = 0; i < len; i++) {
        crc ^= data[i];
        for (unsigned k = 0; k < 8; k++) {
            crc = crc & 1 ? (crc >> 1) ^ 0xedb88320 : crc >> 1;
        }
    }
    crc = ~crc;
    return crc;
}

The main savings is one instruction, the shift up of the data byte, that you can get rid of with the reflected implementation. Also the constant that you & with (1 vs. 0x80000000) is smaller, which may also save an instruction or a register, or perhaps just result in a shorter instruction, depending on the size of immediate values supported in the instruction set.

The shift is avoided for byte-wise calculations as well:

uint32_t crc32bzip2_byte(uint32_t crc, void const *mem, size_t len) {
    unsigned char const *data = mem;
    if (data == NULL)
        return 0;
    for (size_t i = 0; i < len; i++) {
        crc = (crc << 8) ^
              table_byte[((crc >> 24) ^ data[i]) & 0xff];
    }
    return crc;
}

vs.

uint32_t crc32iso_hdlc_byte(uint32_t crc, void const *mem, size_t len) {
    unsigned char const *data = mem;
    if (data == NULL)
        return 0;
    for (size_t i = 0; i < len; i++) {
        crc = (crc >> 8) ^
              table_byte[(crc ^ data[i]) & 0xff];
    }
    return crc;
}

为什么在软件中实现CRC的两个变体

雪化雨蝶 2025-02-16 05:16:11

我通过使用工人和工作人员修复了它

Android更新文件在后台

雪化雨蝶 2025-02-16 00:39:35

这是关于我要做的。

configure.ac 中,添加 ac_prog_sed

makefile.am 中,添加

[…]
xdgdesktopdir = $(datadir)/applications
pixmapsdir    = $(datadir)/pixmaps

SED_CMDS  =
SED_CMDS += 's|[@]bindir@|$(bindir)|g'
SED_CMDS += 's|[@]pixmapsdir@|$(pixmapsdir)|g'

xdgdesktop_DATA += wombat.desktop
EXTRA_DIST      += wombat.desktop.in
CLEANFILES      += wombat.desktop
wombat.desktop: wombat.desktop.in Makefile
        $(SED) $(SED_CMDS) $(srcdir)/wombat.desktop.in > wombat.desktop
[…]

然后将您的 wombat.desktop 重命名为 wombat.desktop.in and write

[…]
Exec=@bindir@/wombat
Icon=@pixmapsdir@/wombat.svg
[…]

(不确定PixMaps/是否是正确的不过,安装SVG文件的位置)

wombat.desktop.in 将受到版本的控制。 wombat.desktop 将不受控制,并且很可能会添加到 .gitignore

/data/wombat.desktop

This is about what I would do.

In configure.ac, add AC_PROG_SED.

In Makefile.am, add

[…]
xdgdesktopdir = $(datadir)/applications
pixmapsdir    = $(datadir)/pixmaps

SED_CMDS  =
SED_CMDS += 's|[@]bindir@|$(bindir)|g'
SED_CMDS += 's|[@]pixmapsdir@|$(pixmapsdir)|g'

xdgdesktop_DATA += wombat.desktop
EXTRA_DIST      += wombat.desktop.in
CLEANFILES      += wombat.desktop
wombat.desktop: wombat.desktop.in Makefile
        $(SED) $(SED_CMDS) $(srcdir)/wombat.desktop.in > wombat.desktop
[…]

Then rename your wombat.desktop to wombat.desktop.in and write

[…]
Exec=@bindir@/wombat
Icon=@pixmapsdir@/wombat.svg
[…]

(not sure whether pixmaps/ is the correct place to install an SVG file, though)

wombat.desktop.in will be version controlled. wombat.desktop will not be version controlled, and might very well be added to .gitignore:

/data/wombat.desktop

在makefile.am(自动工具)中使用sed

雪化雨蝶 2025-02-15 19:57:25

没有什么!将其留在 ef 上,它将管理这些关系。请注意,我可以说关系是一对多的答案问题有自己的注释钥匙,您必须使用两个键

nothing! leave it to EF, it will manage these relations. as a note, I can say the relations are one-to-many each Answer and Question has own Comment so if you want to put foreign keys you must use two keys for both of them

如何设计可以参考问题表或答案表的评论表?

雪化雨蝶 2025-02-15 15:46:12

Flutter Clean 为我工作。运行颤动清洁,然后重试。

flutter clean worked for me. Run flutter clean and try again.

youtube_player_flutter卡在无限加载扑来

雪化雨蝶 2025-02-15 15:05:28

Open Office和Libre Office .ODT文件是.zip文件。

如果更名为.zip后缀,则将实际内容fie获得为content.xml。

可以写一个脚本以删除XML语句设置索引标记。

发现libreoffice生成的XML文件更简单地处理了,一旦将.ODT重新串起了处理的content.xml文件,索引标记就消失了,并且与OpenOffice version.file相比,问题少。

Open Office and Libre Office .odt files are .zip files.

If renamed with .zip suffix the actual content fie is obtained as content.xml.

A script can be written to remove xml statements setting index marks.

Found the LibreOffice generated xml file simpler to process and once the .odt is re-zipped with the processed content.xml file the index marks disappear and there are less problems than with the OpenOffice version.file.

如何为OpenOffice Writer编写宏以删除所有索引Markerkers

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

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