城歌

文章 评论 浏览 32

城歌 2025-02-16 16:48:40

在Ruby中,内部类访问变量/方法如何?

Ruby没有“内部”或“外部”类的概念。听起来您来自Beta,Scala或Newspeak之类的语言,但Ruby不是Beta,Scala或Newspeak。一般而言,任何编程语言都可以正常工作,而编程语言的规范是如何有效的,而不是某些其他编程语言的规范如何工作。 Beta,Scala和Newspeak的课程嵌套了,但Ruby没有。

在Ruby中,您可以词法嵌套 a class 定义,但这不会创建嵌套类。如果将类的定义嵌套在另一个类的定义中,则不会在这两个类之间创建任何类型的关系。没有任何。您不能从另一个类中“访问一个类别的变量/方法”,因为您可以遵循的两个类之间没有关系以获取这些变量/方法。

嵌套类定义唯一的事情是命名空间由外部类的内类定义定义的常数。就是这样。这两个类之间没有关系,唯一的关系是 constant 和类之间。

只是不可能。

在Ruby中创建关系的方法是 shastaritance ,而不是嵌套(因为没有嵌套)。在Ruby中创建对象之间的关系的方法是关联,聚合或组成,而不是嵌套。

Ruby IS 足够灵活,可以实现像“适当” beta式内部类别的行为。请记住,一个内类是在外部类的对象实例中“嵌套”的。我们可以使用一个实例变量模拟这一点:

class Outer
  attr_reader :Inner

  def outer_method
    __callee__
  end

  private

  attr_writer :Inner

  def initialize
    self.Inner = Class.new(self.class) do
      def inner_method
        [__callee__, outer_method]
      end
    end
  end
end

outer = Outer.new
inner = outer.Inner.new
p inner.inner_method

请注意,我使内部类从外部类中继承:那是在Ruby中进行行为共享的方法。您需要具有某种形式的继承或关联关系。嵌套不会产生关系。

In Ruby, how can inner class access variables/methods defined in outer class?

Ruby does not have a concept of "inner" or "outer" classes. It sounds like you are coming from a language like BETA, Scala, or Newspeak, but Ruby is not BETA, Scala, or Newspeak. As a general rule, any programming language works exactly how the specification for the programming language says it works, not how the specification for some other programming language says it works. BETA, Scala, and Newspeak have nested classes, but Ruby has not.

In Ruby, you can lexically nest a class definition, but that does not create a nested class. If you nest the definition of a class inside the definition of another class, that does not create any sort of relationship whatsoever between those two classes. None. You cannot "access variables/methods" of one class from the other class because there is no relationship between those two classes you could follow in order to get at those variables/methods.

The only thing a nested class definition does, is namespace the constant defined by the inner class definition to the outer class. That's it. There is no relationship between the two classes, the only relationship is between the constant and the class.

It is just not possible.

The way to create relationships between classes in Ruby is inheritance, not nesting (because there is no nesting). The way to create relationships between objects in Ruby is association, aggregation, or composition, not nesting.

Ruby is flexible enough to implement something that behaves like a "proper" BETA-style inner class. Remember, an inner class is "nested" inside an object instance of the outer class. We can emulate that using an instance variable:

class Outer
  attr_reader :Inner

  def outer_method
    __callee__
  end

  private

  attr_writer :Inner

  def initialize
    self.Inner = Class.new(self.class) do
      def inner_method
        [__callee__, outer_method]
      end
    end
  end
end

outer = Outer.new
inner = outer.Inner.new
p inner.inner_method

Please note that I made the inner class inherit from the outer class: that is the way to do behavior sharing in Ruby. You need to have some form of inheritance or association relationship. The nesting does not create a relationship.

在Ruby中,如何在外部类中定义内部类访问变量/方法?

城歌 2025-02-16 14:23:37

可以说,这样做的更多“ bash Native”方法是:

IFS=, read -r -a id_parts  < <(id)
printf '%s\n' "${id_parts[@]:1}"

An arguably more "bash native" way to do this is:

IFS=, read -r -a id_parts  < <(id)
printf '%s\n' "${id_parts[@]:1}"

以bash本机方式执行无临时文件的bash表达式

城歌 2025-02-16 12:08:09

数据“日期”和“时间”分为单独的列。我还创建了DateTime列。结果,数据帧看起来像这样:

          source        date     time             datetime
0  Investing.com  2017-05-11  08:00:00 2017-05-11 08:00:00
1  Investing.com  2017-05-11  12:00:00 2017-05-11 12:00:00
2  Investing.com  2017-05-11  16:00:00 2017-05-11 16:00:00
3      yahoo.com  2017-05-11  09:00:00 2017-05-11 09:00:00
4      yahoo.com  2017-05-11  12:00:00 2017-05-11 12:00:00
5      yahoo.com  2017-05-11  15:00:00 2017-05-11 15:00:00
6      yahoo.com  2017-05-12  06:00:00 2017-05-12 06:00:00
7      yahoo.com  2017-05-12  12:00:00 2017-05-12 12:00:00
8      yahoo.com  2017-05-12  18:00:00 2017-05-12 18:00:00

接下来,我创建一个函数my_func并将分组结果保存到数据框架中。我重置多索引,删除额外的列,然后将列重命名为结果。事实证明有点华丽,也许有人会更轻松。

import pandas as pd

df['datetime'] = df['date'].str.cat(df['time '], sep =" ")
df['datetime'] = pd.to_datetime(df['datetime'])

def my_func(x):
    result = str(df.loc[x.index,'datetime'].diff().mean())[7:]
    return result

df1 = pd.DataFrame(df.groupby(['source','date'])['date'].apply(my_func))

df1 = df1.stack(0).reset_index()
df1 = df1.drop(columns='level_2')
df1.rename(columns={0: 'Average_Daily_time'}, inplace=True)

print(df1)

输出

          source        date Average_Daily_time
0  Investing.com  2017-05-11           04:00:00
1      yahoo.com  2017-05-11           03:00:00
2      yahoo.com  2017-05-12           06:00:00

Data 'date' and 'time' divided into separate columns. I also create a datetime column. As a result, the dataframe looks like this:

          source        date     time             datetime
0  Investing.com  2017-05-11  08:00:00 2017-05-11 08:00:00
1  Investing.com  2017-05-11  12:00:00 2017-05-11 12:00:00
2  Investing.com  2017-05-11  16:00:00 2017-05-11 16:00:00
3      yahoo.com  2017-05-11  09:00:00 2017-05-11 09:00:00
4      yahoo.com  2017-05-11  12:00:00 2017-05-11 12:00:00
5      yahoo.com  2017-05-11  15:00:00 2017-05-11 15:00:00
6      yahoo.com  2017-05-12  06:00:00 2017-05-12 06:00:00
7      yahoo.com  2017-05-12  12:00:00 2017-05-12 12:00:00
8      yahoo.com  2017-05-12  18:00:00 2017-05-12 18:00:00

Next, I create a function my_func and save the grouping results to a dataframe. I reset multi-indexes, delete the extra column and rename the column with the result. It turned out a little ornate, maybe someone will do it easier.

import pandas as pd

df['datetime'] = df['date'].str.cat(df['time '], sep =" ")
df['datetime'] = pd.to_datetime(df['datetime'])

def my_func(x):
    result = str(df.loc[x.index,'datetime'].diff().mean())[7:]
    return result

df1 = pd.DataFrame(df.groupby(['source','date'])['date'].apply(my_func))

df1 = df1.stack(0).reset_index()
df1 = df1.drop(columns='level_2')
df1.rename(columns={0: 'Average_Daily_time'}, inplace=True)

print(df1)

Output

          source        date Average_Daily_time
0  Investing.com  2017-05-11           04:00:00
1      yahoo.com  2017-05-11           03:00:00
2      yahoo.com  2017-05-12           06:00:00

计算唯一来源发布的两个新闻之间的平均每日时间

城歌 2025-02-16 08:59:57

如果要使用

因此以太更改为

current_timestamp()

CURRENT_TIMESTAMP

If you are going to use the macro of CURRENT_TIMESTAMP (aka without the parens) it must be in upper case.

So ether change to

current_timestamp()

or

CURRENT_TIMESTAMP

为什么我会得到“意外”&#x27; &quot当我尝试运行DBT Jinja型号时,错误?

城歌 2025-02-16 06:11:54

这应该做您想要的事情,但嵌套功能少得多。

library(dplyr)
df %>% mutate(Classification = case_when(AGE2 <= 6 ~ "",
                                         BMI2 < 18.5 ~ "Underwwight",
                                         BMI2 < 25 ~ "Normal weight",
                                         BMI2 < 30 ~ "Overwwight",
                                         BMI2 >= 30 ~ "Obese"
                                         ))

这将为重量分类创建一个额外的列。

A tibble:6 x 3
AGE2   BMI2   Classification
<dbl>  <dbl>  <chr>

15  22.50087    Normal weight       
17  24.88647    Normal weight       
14  22.70773    Normal weight       
9   23.49076    Normal weight       
5   22.14871            
16  23.10811    Normal weight       
6 rows

如果需要,这也很容易作为功能应用。

This should do what you want but with a lot less nested functions.

library(dplyr)
df %>% mutate(Classification = case_when(AGE2 <= 6 ~ "",
                                         BMI2 < 18.5 ~ "Underwwight",
                                         BMI2 < 25 ~ "Normal weight",
                                         BMI2 < 30 ~ "Overwwight",
                                         BMI2 >= 30 ~ "Obese"
                                         ))

This will create an additional column for the weight classification.

A tibble:6 x 3
AGE2   BMI2   Classification
<dbl>  <dbl>  <chr>

15  22.50087    Normal weight       
17  24.88647    Normal weight       
14  22.70773    Normal weight       
9   23.49076    Normal weight       
5   22.14871            
16  23.10811    Normal weight       
6 rows

This is also very easy to apply as a function if required.

创建功能以在R中的多个数据范围中对BMI进行分类

城歌 2025-02-15 23:17:27

这是一种方法

ratio = [2, 3, 5]
ratio_dec = np.divide(ratio, sum(ratio))
df['ratio'] = df['values'].apply(lambda x: np.round(np.multiply(x, ratio_dec) ,0))
df.explode('ratio')
    ID  values  ratio
0   1   10  2.0
0   1   10  3.0
0   1   10  5.0
1   2   20  4.0
1   2   20  6.0
1   2   20  10.0
2   3   30  6.0
2   3   30  9.0
2   3   30  15.0

here is one way to do it

ratio = [2, 3, 5]
ratio_dec = np.divide(ratio, sum(ratio))
df['ratio'] = df['values'].apply(lambda x: np.round(np.multiply(x, ratio_dec) ,0))
df.explode('ratio')
    ID  values  ratio
0   1   10  2.0
0   1   10  3.0
0   1   10  5.0
1   2   20  4.0
1   2   20  6.0
1   2   20  10.0
2   3   30  6.0
2   3   30  9.0
2   3   30  15.0

根据比率分开数据帧行

城歌 2025-02-15 14:04:46

只需在每列中使用一个子查询,即提及两者之间所需的时间戳,还请确保您的start_time和end_time列是时间戳类型。有关更多信息,请共享表结构,示例数据和预期输出

Just use a subquery for each column mentioning the required timestamp in between, also make sure your start_time and end_time columns are timestamp types. For more information, please share the table structure, sample data, and expected output

如何使用开始和结束时间列制作时间存储库?

城歌 2025-02-15 12:02:31

我还努力寻找可以选择的HSV值(最终选择区域)。通过大量谷歌搜索,我制作了这个小脚本来检查图像中的HSV值。

它打开您的图像(调整cv2.imread的路径)。
当您单击图像的兴趣点时,它会在图像中的该位置打印鼠标单击和HSV值的位置。

import cv2

def on_mouse(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDOWN:
        hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
        print("HSV values at ({}, {}): {}".format(x, y, hsv[y, x]))

img = cv2.imread(‘\path\to\your\image\piccie.png’)
cv2.namedWindow("image")
cv2.setMouseCallback("image", on_mouse)

while True:
    cv2.imshow("image", img)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cv2.destroyAllWindows()

I was also struggling to find what HSV values to choose (to ultimately select regions). With quite some googling I made this small script to inspect HSV values in my image.

It opens your image (adjust the path at cv2.imread).
When you click at a point of interest in the image, it prints the location of mouse-click and HSV values at that location in the image.

import cv2

def on_mouse(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDOWN:
        hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
        print("HSV values at ({}, {}): {}".format(x, y, hsv[y, x]))

img = cv2.imread(‘\path\to\your\image\piccie.png’)
cv2.namedWindow("image")
cv2.setMouseCallback("image", on_mouse)

while True:
    cv2.imshow("image", img)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cv2.destroyAllWindows()

选择正确的上和下部HSV边界,以使用`cv :: inrange`(OPENCV)进行颜色检测

城歌 2025-02-15 11:53:44

为此使用std :: vector。例如:

std::vector<int> values;
values.resize(n);

内存将分配在堆上,但这仅具有一个小的性能弊端。此外,明智的做法是不要在堆栈上分配大型数据,因为它的尺寸相当有限。

Use std::vector for this. For example:

std::vector<int> values;
values.resize(n);

The memory will be allocated on the heap, but this holds only a small performance drawback. Furthermore, it is wise not to allocate large datablocks on the stack, as it is rather limited in size.

为什么AREN&#x27; t变量长度阵列部分C&#x2B;&#x2B;标准?

城歌 2025-02-15 09:13:52

有点混乱

library(dplyr)
library(reshape2)

frame2 <- frame %>%
  reshape2::melt(id.vars = "id") %>%
  filter(value != "NA") # or na.omit()
frame2
res <- list()
l <- unique(frame2$variable)
for (i in 1:length(l)){
  dd <- frame2 %>%
    filter(variable == l[i]) %>%
    group_by(variable, value) %>%
    summarise(n = n()) %>%
    mutate(freq = n/sum(n)) %>%
    pivot_wider(id_cols = value, values_from = c(n, freq), names_from = variable) %>%
    column_to_rownames(var = "value")
  colnames(dd) <- c(as.character(l[i]), "per")
  res[[i]] <- dd
}
res

[[1]]
    A  per
cat 3 0.75
dog 1 0.25

[[2]]
    B   per
cat 3 0.375
dog 5 0.625

[[3]]
    C per
cat 2 0.5
dog 2 0.5

It's bit messy

library(dplyr)
library(reshape2)

frame2 <- frame %>%
  reshape2::melt(id.vars = "id") %>%
  filter(value != "NA") # or na.omit()
frame2
res <- list()
l <- unique(frame2$variable)
for (i in 1:length(l)){
  dd <- frame2 %>%
    filter(variable == l[i]) %>%
    group_by(variable, value) %>%
    summarise(n = n()) %>%
    mutate(freq = n/sum(n)) %>%
    pivot_wider(id_cols = value, values_from = c(n, freq), names_from = variable) %>%
    column_to_rownames(var = "value")
  colnames(dd) <- c(as.character(l[i]), "per")
  res[[i]] <- dd
}
res

[[1]]
    A  per
cat 3 0.75
dog 1 0.25

[[2]]
    B   per
cat 3 0.375
dog 5 0.625

[[3]]
    C per
cat 2 0.5
dog 2 0.5

在数据框架中提取计数及其百分比?

城歌 2025-02-15 06:40:37

本质上不可能将schema.prisma文件分为多个文件。

您可以使用 aurora 工具将模式文件分开。

It's not possible natively to split the schema.prisma file into multiple files.

You could use the Aurora tool to split the schema files.

有什么方法可以雾化Prisma模型,在schema.prisma中没有太多代码

城歌 2025-02-14 00:14:39
  1. 尝试将localhost更改为firebase命令行和应用程序中的计算机IP。一些模拟器,例如iOS模拟器,无法理解本地主机。
  2. 请粘贴A 完全可重复的样本,而不仅仅是一部分。
  3. 尝试到等待firebase.initializeapp(); main 函数,而不是initstate
  4. 首先在端口8080上手动检查Firebase Server并查看Firebase Server是否确实有效
  1. Try to change localhost to your machine ip, in both firebase command line and your app. Some simulators, such as ios simulator, cannot understand localhost.
  2. Please paste a fully reproducible sample, instead of just part of the lines.
  3. Try to await Firebase.initializeApp(); inside main function, not initState
  4. Firstly check at port 8080 manually and see whether the firebase server really works

如何将FlutterFire用于模拟器演示项目?

城歌 2025-02-13 23:03:28

作为快速n脏修复,这对我有用:
在有问题的导入之前添加这2行:

import sys
sys.path.append('C:\\Python27\\Lib\site-packages')

As quick n dirty fix, this worked for me:
Adding this 2 lines before the problematic import:

import sys
sys.path.append('C:\\Python27\\Lib\site-packages')

如何在Pycharm中使用已安装的软件包?

城歌 2025-02-13 07:02:39

作为我自己学习的一种练习,我给了它,并提出了以下方法。创建一个定制的小部件,它看起来像是如此简单的东西,看起来像是很多代码……但是它似乎按照预期的方式工作,并且可以以各种方式修改,扩展和集成与其他元素。

用法:const Maxintfield(最大:100),

实现:

class MaxIntField extends StatefulWidget {
  const MaxIntField({Key? key, this.max = 1}) : super(key: key);
  final int max;

  @override
  State<MaxIntField> createState() => _MaxIntFieldState();
}

class _MaxIntFieldState extends State<MaxIntField> {
  final TextEditingController _controller = TextEditingController();

  @override
  void initState() {
    super.initState();
    _controller.value.copyWith(text: '0');
    _controller.addListener(() {
      if (_controller.text.isNotEmpty && _controller.text != '0') {
        int intVal = int.parse(_controller.text);
        if (intVal > widget.max) {
          setState(() {
            _controller.value =
                _controller.value.copyWith(text: widget.max.toString());
            _showMyDialog();
          });
        } else if (_controller.text != intVal.toString()) {
          //remove leading '0'
          setState(() {
            _controller.value =
                _controller.value.copyWith(text: intVal.toString());
          });
        }
      }
    });
  }

// assuming using Material
  _showMyDialog() async {
    showDialog<String>(
      context: context,
      builder: (BuildContext context) => AlertDialog(
        title: const Text('AlertDialog Title'),
        content: Text('This field is limited to ${widget.max}'),
        actions: <Widget>[
          TextButton(
            onPressed: () => Navigator.pop(context, 'OK'),
            child: const Text('OK'),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      controller: _controller,
      keyboardType: TextInputType.number,
    );
  }
}

As an exercise for my own learning I gave it a go and came up with the following approach; creating a bespoke widget which admittedly looks like a lot of code for something so simple... but it appears to work as expected I think and one could modify, expand and integrate it with other elements in various ways.

Usage: const MaxIntField(max: 100),

Implementation:

class MaxIntField extends StatefulWidget {
  const MaxIntField({Key? key, this.max = 1}) : super(key: key);
  final int max;

  @override
  State<MaxIntField> createState() => _MaxIntFieldState();
}

class _MaxIntFieldState extends State<MaxIntField> {
  final TextEditingController _controller = TextEditingController();

  @override
  void initState() {
    super.initState();
    _controller.value.copyWith(text: '0');
    _controller.addListener(() {
      if (_controller.text.isNotEmpty && _controller.text != '0') {
        int intVal = int.parse(_controller.text);
        if (intVal > widget.max) {
          setState(() {
            _controller.value =
                _controller.value.copyWith(text: widget.max.toString());
            _showMyDialog();
          });
        } else if (_controller.text != intVal.toString()) {
          //remove leading '0'
          setState(() {
            _controller.value =
                _controller.value.copyWith(text: intVal.toString());
          });
        }
      }
    });
  }

// assuming using Material
  _showMyDialog() async {
    showDialog<String>(
      context: context,
      builder: (BuildContext context) => AlertDialog(
        title: const Text('AlertDialog Title'),
        content: Text('This field is limited to ${widget.max}'),
        actions: <Widget>[
          TextButton(
            onPressed: () => Navigator.pop(context, 'OK'),
            child: const Text('OK'),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      controller: _controller,
      keyboardType: TextInputType.number,
    );
  }
}

如何限制文本字段中的值颤音中的值?

城歌 2025-02-13 05:58:44

有人用纯粹的numpy回答了我:

import numpy as np

rand = np.random.default_rng(seed=0)
a = rand.uniform(low=-1, high=1, size=(10, 1))
b = rand.uniform(low=-1, high=1, size=(10, 6))


def signs():
    sa = np.sign(a)
    return sa * (sa == np.sign(b))


def main():
    signs()
    return


if __name__ == '__main__':
    main()

%timeit signs()
10.2 µs ± 678 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Someone answered me with pure numpy:

import numpy as np

rand = np.random.default_rng(seed=0)
a = rand.uniform(low=-1, high=1, size=(10, 1))
b = rand.uniform(low=-1, high=1, size=(10, 6))


def signs():
    sa = np.sign(a)
    return sa * (sa == np.sign(b))


def main():
    signs()
    return


if __name__ == '__main__':
    main()

%timeit signs()
10.2 µs ± 678 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

我需要基于两个数据框列生成新列,它如何更快?

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

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