RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / user-369677

Aycon's questions

Martin Hope
Aycon
Asked: 2025-02-16 20:09:20 +0000 UTC

在工厂方法中释放部分创建的对象的正确方法是什么?

  • 7

我有一个需要MyClass实例化A和初始化的类。所有三个类都继承了。我无法访问这些类的源代码,但是它们的构造函数可能会因某些参数组合而引发异常。我知道在构造函数中抛出异常是一种不好的做法,因为它可能会导致类在内存中处于不一致的状态(不变违反)。因此,我没有使用直接构造函数,而是使用在内部进行初始化的工厂方法,并且。如果至少有一个类,并且已引发异常,则该函数也会引发异常。我知道如果我无法创建,那么我至少应该释放该类并引发异常。我还知道,如果我无法创建该类,我至少应该释放先前创建的和,然后在中引发异常。BCIDisposableABCMyClass.Create()ABCCreateABCBACABCreate

请告诉我是否有一个好的模式或代码示例,如果我无法构建类,我该如何清除以前初始化的部分MyClass?
如果有多于三个部分怎么办?我正在考虑使用堆栈Stack<IDisposable>来清理各个部分。


应
@user7860670 的要求添加一个最低限度可重现的示例。看来这段文字太难理解了:

class A: IDisposable
{
  private readonly int p_value;

  public A(int value)
  {
    ArgumentOutOfRangeException.ThrowIfNegative(value);
    p_value = value;
  }

  public void Print()
  {
    Console.WriteLine($"Value is: {p_value}");
  }

  public void Dispose()
  {
    Console.WriteLine("A disposed");
  }
}


class B : IDisposable
{
  private readonly int p_value;

  public B(int value)
  {
    ArgumentOutOfRangeException.ThrowIfLessThan(value, 10);
    p_value = value;
  }

  public void Print()
  {
    Console.WriteLine($"Value is: {p_value}");
  }

  public void Dispose()
  {
    Console.WriteLine("B disposed");
  }
}


class C : IDisposable
{
  private readonly int p_value;

  public C(int value)
  {
    ArgumentOutOfRangeException.ThrowIfLessThan(value, 20);
    p_value = value;
  }

  public void Print()
  {
    Console.WriteLine($"Value is: {p_value}");
  }

  public void Dispose()
  {
    Console.WriteLine("C disposed");
  }
}

class MyClass
{
  private readonly A a;
  private readonly B b;
  private readonly C c;

  protected MyClass(A _a, B _b, C _c) { a = _a; b = _b; c = _c;}

  public MyClass Create(int _value)
  {
    // Maybe throw error
    A a = new A(_value);

    // Maybe throw error
    // Need free A
    B b = new B(_value);

    // Maybe throw error
    // Need free A
    // Need free B
    C c = new C(_value);

    return new (a, b, c);
  }
}
c#
  • 1 个回答
  • 70 Views
Martin Hope
Aycon
Asked: 2024-12-10 22:06:57 +0000 UTC

工厂上的“using”语句将工厂委托给实例的资源释放

  • 6

这是一个最低限度可重现的示例:

namespace IterableDisposeTest
{
  interface IInstance
  {
    int ID { get; }
  }

  class Instance : IInstance
  {
    private static int p_counter = 0;

    public int ID { get; }

    public Instance(MagicVariable _magicVariable)
    {
      ID = p_counter++;
      Console.WriteLine(_magicVariable.MagicString);
    }
  }

  interface IProducer
  {
    public IEnumerable<IInstance> GetNextInstance();
  }
  
   
  class Producer : IProducer
  {
    private MagicVariable p_magicVariable;

    public Producer(MagicVariable _magicVariable)
    {
      p_magicVariable = _magicVariable;
    }

    public IEnumerable<IInstance> GetNextInstance()
    {
      for (int i = 0; i < 42; i++)
        yield return new Instance(p_magicVariable);
    }
  }

  class ProducerFactory: IDisposable
  {
    private bool disposedValue;
    private MagicVariable p_magicVariable = new MagicVariable();

    public IEnumerable<Producer> GetNextProducer()
    {
      while (true)
        yield return new Producer(p_magicVariable);
    }

    protected virtual void Dispose(bool disposing)
    {
      if (!disposedValue)
      {
        Console.WriteLine("ProducerFactory Disposed");
        if (disposing)
        {

        }

        p_magicVariable.Dispose();
        disposedValue = true;
      }
    }

    ~ProducerFactory()
    {
      Dispose(disposing: false);
    }

    public void Dispose()
    {
      Dispose(disposing: true);
      GC.SuppressFinalize(this);
    }
  }

  class MagicVariable: IDisposable
  {
    private string p_magicString = "I'm MAGIC!";
    private bool p_disposedValue;

    public string MagicString
    {
      get
      {
        ObjectDisposedException.ThrowIf(p_disposedValue, typeof(string));
        return p_magicString;
      }
    }

    protected virtual void Dispose(bool disposing)
    {
      if (!p_disposedValue)
      {
        Console.WriteLine("MagicVariable Disposed");
        if (disposing)
        {
        }

        p_disposedValue = true;
      }
    }

    ~MagicVariable()
    {
      Dispose(disposing: false);
    }

    public void Dispose()
    {
      Dispose(disposing: true);
      GC.SuppressFinalize(this);
    }
  }

  static class SuperProducer
  {
    public static IEnumerable<IProducer> GetNextProducer()
    {
      using ProducerFactory factory = new ProducerFactory();
      foreach(var producer in factory.GetNextProducer())
        yield return producer;
    }
  }

  internal class Program
  {
    static void Main(string[] args)
    {
      IProducer? producer = SuperProducer.GetNextProducer().FirstOrDefault((IProducer?)null);
      if (producer != null)
      {
        // Thrown ObjectDisposedException there:
        foreach (IInstance instance in producer.GetNextInstance())
          Console.WriteLine($"Instance id is: {instance.ID}");
      }
    }
  }
}

它会导致异常ObjectDisposedException,因为工厂在第 124 行退出语句时被释放。using困境如下 - 只有当语句中没有创建工厂时,错误才会消失using,但这与 RAII 概念相矛盾,工厂不会被创建。释放。如果你在 - 中创建一个工厂,那么它会在从第 126 行的循环using返回之前被释放。请告诉我这个示例中的架构错误是什么?IProducer你能怎样解决它?

c#
  • 1 个回答
  • 53 Views
Martin Hope
Aycon
Asked: 2024-09-04 13:36:14 +0000 UTC

GetType 不适用于 out 参数

  • 5

我写了这段代码,但它不起作用。我明白为什么,但我该如何解决它?

internal class ViewProperty<T> : IViewProperty<T>
{
  protected Dictionary<Type, object> PropetriesStorage { get; } = new();

  public bool TryGetProperty<PropType, SubType>(out PropType _property) where PropType : IViewProperty<SubType>
  {
    bool result = PropetriesStorage.TryGetValue(_property.GetType(), out var temp);
    Trace.Assert(temp is PropType);
    _property = (PropType)temp;
    return result;
  }
}

错误“CS0269 使用未分配值的输出参数‘_property’。”
参数(即使未初始化)在调用时不包含类型吗?

c#
  • 2 个回答
  • 35 Views
Martin Hope
Aycon
Asked: 2024-06-04 12:49:09 +0000 UTC

从使用“return”运算符返回的嵌套生成器函数中获取值

  • 6

这是我的代码:

def gen_middle():
    def gen_nested():
        counter = 0
        while True:
            yield counter
            counter += 1
            if counter >= 2:
                return 'My special value'

    yield from gen_nested()

def main():
    iterator = iter(gen_middle())
    
    try:
        while True:
            value = next(iterator)
            print(value)
    except StopIteration as exc:
        # returned value (with "return") from gen_nested was expected
        print(exc.value)

main()

我期望的输出:

0
1
My special value

但我得到了:

0
1
None

对此,我有两个问题。

  1. 该语句是否不会使用嵌套生成器中的值来yield from升级异常?StopIteration
  2. 我可以在不更改和函数'My special value'的代码的情况下获得这个 value()吗?gen_middlegen_nested
python
  • 1 个回答
  • 27 Views
Martin Hope
Aycon
Asked: 2024-04-05 15:49:41 +0000 UTC

选择最佳间隔重叠

  • 10

我有几个加权间隔的列表 - 这些是元组(value, start, stop):

#   0   1   2   3   4   5   6   7   8   9   10
# 1         [___]                           
# 2 [___________________________________]   
# 3 [_______]                               
# 8     [_______________________]           
# 7                     [___________________]
# 6                                 [___]   
# 4     [_______________________]           

# input
# (value: float, start: float, stop: float)
list_in = [(2, 0, 9), (3, 0, 2), (8, 1, 7), (4, 1, 7), (1, 3, 4), (5, 5, 10), (6, 8, 9)]

我想找到所有部分重叠并选择“最佳”重叠,即 最大的重叠value。

对于我的示例,正​​确答案是:

#   0   1   2   3   4   5   6   7   8   9   10
# 1                                         
# 2                                         
# 3 [___]                                   
# 8     [_______________________]           
# 7                             [___________]
# 6                                         
# 4                                         

# output
list_out = [(3, 0, 1), (8, 1, 7), (7, 7, 10)]

我会尽量保持简单,说明我所拥有的所有条件,但以下是您应该了解的最低限度:

  1. 输入的元组数组未以任何方式排序
  2. 我有一个区间树的实现,如果算法性能更高或更简单,请使用它

3)需要考虑-float('inf')区间的开始和float('inf')区间的结束。

  1. 如果两个间隔的值value相同,则越短越好。如果它们的长度相同,则它是间隔的精确副本 - 忽略精确副本。
  2. 忽略具有的间隔start == stop

如果这对您来说更容易,以下是相对间距的所有可能情况:

# Target interval:
#   0   1   2   3   4   5   6   7   8   9
#               [___________]           

# All cases for target:
#   0   1   2   3   4   5   6   7   8   9
#   [_______]                           
#       [_______]                       
#           [_______]                   
#               [_______]               
#                   [___]               
#                       [_______]       
#                           [_______]   
#                               [_______]
#           [___________________]       
#               [___________]           

区间和点的所有情况:

value, start, stop = interval
point = x

point < start
point == start
start < point and point < stop
point == stop
stop < point

我正面解决这个问题的任何尝试都会导致组合爆炸并将代码变成回调地狱

请帮忙。PS:我可以粘贴我的尝试,但它需要 200 行代码,并且开始如下:

def calc_factor(integral_value: float, depth_start: float, depth_stop: float):
    return integral_value / (depth_stop - depth_start)

def split_by_intersections(interval_l: IntegralValueInterval, interval_r: IntegralValueInterval):
    assert interval_l.depth_start < interval_l.depth_stop
    assert interval_r.depth_start < interval_r.depth_stop
    assert interval_l.depth_start > -float('inf')
    assert interval_l.depth_stop < float('inf')
    assert interval_r.depth_start > -float('inf')
    assert interval_r.depth_stop < float('inf')
    
    # if-hell I know this, but I don't know how to simplify it.
    if interval_l.depth_start < interval_r.depth_start:
        if interval_l.depth_stop < interval_r.depth_start:
            # L.start L.stop R.start R.stop
            return [interval_l, interval_r]
        
        elif interval_l.depth_stop == interval_r.depth_start:
            # L.start (L.stop R.start) R.stop
            interval_l.depth_stop -= settings.gis_delta_depth
            return [interval_l, interval_r]
        
        elif interval_l.depth_stop > interval_r.depth_start and interval_l.depth_stop < interval_r.depth_stop:
            # L.start R.start L.stop R.stop
            a = interval_l.depth_start
            b = interval_r.depth_start
            c = interval_l.depth_stop
            d = interval_r.depth_stop
            
            interval_l.depth_start = a
            interval_l.depth_stop = b - settings.gis_delta_depth
            
            interval_c = IntegralValueInterval()
            interval_c.depth_start = b
            interval_c.depth_stop = c - settings.gis_delta_depth
            left_factor = calc_factor(interval_l.integral_value, interval_c.depth_start, interval_c.depth_stop)
            right_factor = calc_factor(interval_r.integral_value, interval_c.depth_start, interval_c.depth_stop)
            if left_factor < right_factor:
                interval_c.integral_value = interval_r.integral_value
            else:
                interval_c.integral_value = interval_l.integral_value
                
            interval_r.depth_stop = d
            interval_r.depth_start = c
            
            return [interval_l, interval_c, interval_r]
        
        elif interval_l.depth_stop == interval_r.depth_stop:
            # L.start R.start (L.stop R.stop)
            left_factor = calc_factor(interval_l.integral_value, interval_l.depth_start, interval_l.depth_stop)
            right_factor = calc_factor(interval_r.integral_value, interval_r.depth_start, interval_r.depth_stop)
            if left_factor < right_factor:
                interval_l.depth_stop = interval_r.depth_start - settings.gis_delta_depth
            else:
                interval_r.depth_start = interval_l.depth_stop
                interval_l.depth_stop -= settings.gis_delta_depth
            
            return [interval_l, interval_r]
...

PS 2.0:我尝试为所有情况编写测试,发现不可能考虑到-float('inf'),float('inf')因为存在矛盾的例子,例如,[(2, -float('inf'), 6), (1, -float('inf'), 2)]不清楚哪个段更好。因此,我正在修改这个问题。


PS 3.0:我在代码中附上了“测试”,以便您可以检查您的解决方案。

def test():
    for intervals, expected in (
        # value left > value right
        ([(2, 3, 6), (1, 0, 2)], [(1, 0, 2), (2, 3, 6)]),
        ([(2, 3, 6), (1, 1, 3)], [(1, 1, 3), (2, 3, 6)]),
        ([(2, 3, 6), (1, 2, 4)], [(1, 2, 3), (2, 3, 6)]),
        ([(2, 3, 6), (1, 3, 5)], [(2, 3, 6)]),
        ([(2, 3, 6), (1, 4, 5)], [(2, 3, 6)]),
        ([(2, 3, 6), (1, 3, 6)], [(2, 3, 6)]),
        ([(2, 3, 6), (1, 2, 6)], [(1, 2, 3), (2, 3, 6)]),
        ([(2, 3, 6), (1, 2, 7)], [(1, 2, 3), (2, 3, 6), (1, 6, 7)]),
        ([(2, 3, 6), (1, 3, 7)], [(2, 3, 6), (1, 6, 7)]),
        ([(2, 3, 6), (1, 4, 6)], [(2, 3, 6)]),
        ([(2, 3, 6), (1, 5, 7)], [(2, 3, 6), (1, 6, 7)]),
        ([(2, 3, 6), (1, 6, 8)], [(2, 3, 6), (1, 6, 8)]),
        ([(2, 3, 6), (1, 7, 9)], [(2, 3, 6), (1, 7, 9)]),
        
        # value left == value right
        ([(2, 3, 6), (2, 0, 2)], [(2, 0, 2), (2, 3, 6)]),               # 2 / (6 - 3) < 2 / (2 - 0)
        ([(2, 3, 6), (2, 1, 3)], [(2, 1, 3), (2, 3, 6)]),               # 2 / (6 - 3) < 2 / (3 - 1)
        ([(2, 3, 6), (2, 2, 4)], [(2, 2, 4), (2, 4, 6)]),               # 2 / (6 - 3) < 2 / (4 - 2)
        ([(2, 3, 6), (2, 3, 5)], [(2, 3, 5), (2, 5, 6)]),               # 2 / (6 - 3) < 2 / (5 - 3)
        ([(2, 3, 6), (2, 4, 5)], [(2, 3, 4), (2, 4, 5), (2, 5, 6)]),    # 2 / (6 - 3) < 2 / (5 - 4)
        ([(2, 3, 6), (2, 3, 6)], [(2, 3, 6)]),                          # 2 / (6 - 3) == 2 / (6 - 3) (copy)
        ([(2, 3, 6), (2, 2, 6)], [(2, 2, 3), (2, 3, 6)]),               # 2 / (6 - 3) > 2 / (6 - 2)
        ([(2, 3, 6), (2, 2, 7)], [(2, 2, 3), (2, 3, 6), (2, 6, 7)]),    # 2 / (6 - 3) > 2 / (7 - 2)
        ([(2, 3, 6), (2, 3, 7)], [(2, 3, 6), (2, 6, 7)]),               # 2 / (6 - 3) > 2 / (7 - 3)
        ([(2, 3, 6), (2, 4, 6)], [(2, 3, 4), (2, 4, 6)]),               # 2 / (6 - 3) < 2 / (6 - 4)
        ([(2, 3, 6), (2, 5, 7)], [(2, 3, 5), (2, 5, 7)]),               # 2 / (6 - 3) < 2 / (7 - 5)
        ([(2, 3, 6), (2, 6, 8)], [(2, 3, 6), (2, 6, 8)]),               # 2 / (6 - 3) < 2 / (8 - 6)
        ([(2, 3, 6), (2, 7, 9)], [(2, 3, 6), (2, 7, 9)]),               # 2 / (6 - 3) < 2 / (9 - 7)
        
        # value left < value right
        ([(2, 3, 6), (3, 0, 2)], [(3, 0, 2), (2, 3, 6)]),
        ([(2, 3, 6), (3, 1, 3)], [(3, 1, 3), (2, 3, 6)]),
        ([(2, 3, 6), (3, 2, 4)], [(3, 2, 4), (2, 4, 6)]),
        ([(2, 3, 6), (3, 3, 5)], [(3, 3, 5), (2, 5, 6)]),
        ([(2, 3, 6), (3, 4, 5)], [(2, 3, 4), (3, 4, 5), (2, 5, 6)]),
        ([(2, 3, 6), (3, 3, 6)], [(3, 3, 6)]),
        ([(2, 3, 6), (3, 2, 6)], [(3, 2, 6)]),
        ([(2, 3, 6), (3, 2, 7)], [(3, 2, 7)]),
        ([(2, 3, 6), (3, 3, 7)], [(3, 3, 7)]),
        ([(2, 3, 6), (3, 4, 6)], [(2, 3, 4), (3, 4, 6)]),
        ([(2, 3, 6), (3, 5, 7)], [(2, 3, 5), (3, 5, 7)]),
        ([(2, 3, 6), (3, 6, 8)], [(2, 3, 6), (3, 6, 8)]),
        ([(2, 3, 6), (3, 7, 9)], [(2, 3, 6), (3, 7, 9)]),
    ):
        actual = list(max_values(intervals))
        if actual != expected:
            print(intervals, expected, actual)


test()
python
  • 2 个回答
  • 135 Views
Martin Hope
Aycon
Asked: 2024-03-06 19:11:45 +0000 UTC

装饰者隐藏自己

  • 5

我正在尝试创建一个与我的目的类似的装饰器,但是我的实现(在纯Pythonproperty中类似)不起作用。在包装之前我无法访问类变量。这是一个最小的可重现示例:propertyself

class MyWrapper(object):
    def __init__(self, first=None, second=None) -> None:
        self.first = first
        self.second = second

    def __call__(self, *args, **kwargs):
        if self.first is not None:
            self.first(*args, **kwargs)
        
        if self.second is not None:
            self.second(*args, **kwargs)
    
    def second_handler(self, func):
        wrapper = type(self)(self.first, func)
        return wrapper
        
        
class TestClass(object):
    def __init__(self, name) -> None:
        self.name = name
    
    @MyWrapper
    def foo(self):
        print(f'Hello, {self.name}!')
    
    @foo.second_handler
    def foo(self):
        print(f'Bye, {self.name}!')
    
    
def main(*args, **kwargs):
    instance = TestClass('User')
    instance.foo()


if __name__ == '__main__':
    main()

应该输出:

Hi User!
Bye, User!

在调用时,self它被装饰器替换,我与原始类的属性失去了联系。

python
  • 1 个回答
  • 49 Views
Martin Hope
Aycon
Asked: 2024-02-12 21:38:08 +0000 UTC

标志子集的所有排列

  • 6

我有一组任意大小的二进制标志作为数字int。

例如,数字“18”< 2**5=> 最少 5 个标志。

我需要使用相当复杂的方案找到设置标志的所有组合。我宁愿举一个例子并展示我想要得到的东西。我想编写一个生成器,它以数字作为输入并仅返回该数字*的设置位的所有组合。例如,考虑数字 18:

>>> bin(18)
'0b10010'

我想制作一个将返回以下内容的生成器:

yield [True, False, False, True, False] # исходное число
yield [False, False, False, True, False] # первый флаг установлен в 'False'
yield [True, False, False, False, False] # только второй флаг установлен в 'False'
yield [False, False, False, False, False] # оба флага установлены в `False`
  1. 只能更改原始数字中的单位。
  2. 标志的排序顺序很重要;标志从左到右排序。
  3. 生成的序列不包含重复。
  4. 两个标志被关闭的组合必须始终出现在仅一个标志被关闭的任何组合之后。那是
[True, True, False, True]

比

[True, False, False, True]

和什么

[True, True, False, False]

因此,生成器必须首先吐出最接近原始序列的组合。

如果返回数字而不是列表,我会很高兴int。以我为例:

yield 18
yield 2
yield 16
yield 0

为什么这是必要的?我正在寻找一组输入数据的最接近的组合(在 Levenshtein 度量中(没有邻居排列))来训练神经网络来预测某个集合。标志指示源数据中是否存在列。我通过谓词运行结果数字来了解它是否适​​合我。

CPU_Bound 算法(要求渐进复杂度)。



最后,根据@MBo 和@Stanislav Volodarskiy 的答案,我使用了以下代码(欢迎批评!):

from itertools import combinations

def gen_submasks(n:int):
    def gen_bases(n:int):
        while n > 0:
            yield (base := 1 << n.bit_length() - 1)
            n = n ^ base
            
            # alternative syntax:
            # base = 1 << n.bit_length() - 1
            # yield base
            # n ^= base
    
    for count in range(n.bit_count()):
        for combination in combinations(gen_bases(n), count):
            yield n - sum(combination)
    
    yield 0

def main():
    n = 41
    for submask in gen_submasks(n):
        print(bin(submask)[2:].zfill(n.bit_length()))

main()

# 101001
# 001001
# 100001
# 101000
# 000001
# 001000
# 100000
# 000000
python
  • 2 个回答
  • 126 Views
Martin Hope
Aycon
Asked: 2024-02-10 08:45:28 +0000 UTC

Python 参数中的规范(开始、停止)

  • 5

是否有一种优雅的方法来指定一个参数,将切片的开始和结束封装为slice,但不包含步骤?现在我正在使用类似 module 中的声明bisect,但我想要更简洁的东西,并且不分隔loand hi:

def find_left_lt(a, x, lo=0, hi=None, key=None):
python
  • 1 个回答
  • 32 Views
Martin Hope
Aycon
Asked: 2024-02-07 19:36:44 +0000 UTC

通过签名重载方法,如“next”方法中所示

  • 6

我想要一个可以接受(包括None)或不接受参数的方法。比如它在内置方法中的工作方式next,可以接受一个参数default,可以接受None作为参数default,也可能根本不接受,StopIterationError如果序列为空就调用它。根据这个答案,我正在尝试重载这样的StackOverflow方法:touch_first

from itertools import chain, repeat

class EnumerateUtils:
    def touch_first(self, iterable):
        # Raise StopIterationError if sequence is empty
        
        iterable_iterator = iter(iterable)
        first_element = next(iterable_iterator)
        return (first_element, chain(repeat(first_element, 1), iterable_iterator))

class EnumerateUtilsOverloaded(EnumerateUtils):
    def touch_first(self, iterable, default, *args, **kwargs):
        # No raise errors
        try:
            return super().touch_first(iterable, *args, **kwargs)
        except StopIteration:
            return default

sequence = chain(range(0, 5), repeat(None, 1), range(6, 10))
empty_seq = []

def check_without_default(seq):
    util = EnumerateUtilsOverloaded()
    item = util.touch_first(seq)
    if item is not None:
        first_element, new_sequence = item
        print(first_element)
        print(list(new_sequence))

check_without_default(sequence) # -> I WANT: 0\n[0, 1, 2, 3, 4, None, 6, 7, 8, 9]
check_without_default(empty_seq) # -> I WANT: no print, but StopIterationError raised as in 'next' method without default

然而我只得到了TypeError "EnumerateUtilsOverloaded.touch_first() missing 1 required positional argument: 'default'",因为我没有为变量指定默认值default。但是,如果我这样做,代码将正常工作,但check_without_default(empty_seq)不会像该方法那样输出或引发StopIterationErrornext任何内容,我真的很喜欢这个。

如何获得所需的执行逻辑next?我无法区分缺席default和default=None。


最后,根据@andreymal的回答,我使用了以下代码(没有类):

from itertools import chain, repeat

_sentinel = object()

def touch_first(iterable, default=_sentinel, *args, **kwargs):
    iterable_iterator = iter(iterable)
    first_element = None
    if default == _sentinel:
        first_element = next(iterable_iterator)
    else:
        first_element = next(iterable_iterator, default)
    
    return (first_element, chain(repeat(first_element, 1), iterable_iterator))
python
  • 2 个回答
  • 55 Views
Martin Hope
Aycon
Asked: 2024-01-30 12:35:38 +0000 UTC

如何找出您的计算机上有哪些(几个/所有)Python 版本?

  • 5

我试图弄清楚如何在控制台中自动查找并显示计算机(Linux 和 Windows)上存在且可检测到的所有 Python 版本。谷歌搜索仅向我显示有关如何查找当前安装版本的答案。我认为 Stackoverflow 上应该有一个答案。

python
  • 2 个回答
  • 49 Views
Martin Hope
Aycon
Asked: 2023-11-08 20:34:24 +0000 UTC

rarfile 引发错误无法读取足够的数据:req=65536 got=0

  • 5

这个问题是问题的精确副本,但是仍然没有答案,并且这个问题的答案对我没有帮助。

简而言之,当尝试使用 .rar 解压 Rar 存档时会发生此错误rarfile。也就是说,函数调用extract会引发BadRarFile消息"Failed the read enough data: req=65536 got=0"。我深入研究了源代码很长时间,发现尝试从实用程序管道描述符中读取时会发生错误unrar- 它是无声的(不是很有用):(


它解压缩相邻文件,但在该文件上给出错误。我保证:

  • rarfile使用pip已安装的
  • unrar使用pip已安装的
  • unrar使用apt已安装的
  • 是的,在大多数情况下它都能正常工作,这是一个 heisenbug
  • 是的,它rarfile正确地识别和使用unrar。

请提供任何帮助。

python
  • 1 个回答
  • 27 Views
Martin Hope
Aycon
Asked: 2023-10-13 11:25:52 +0000 UTC

消除Python中的循环类引用依赖

  • 3

请看一下缩小后的代码:

from abc import ABC, abstractmethod

class AbstractProduct(ProductFactory, ABC):
    @abstractmethod
    def some_method(self):
        ''' Is abstract method '''

class Product1(AbstractProduct):
    def some_method(self):
        print('I am a Product1!')

class Product2(AbstractProduct):
    def some_method(self):
        print('I am a Product2!')

class ProductFactory:
    knowed_types = {
        0: Product1,
        1: Product2
    }

    @classmethod
    def create_product(cls, type_id:int):
        if type_id in cls.knowed_types:
            return cls.knowed_types[type_id]()

该代码不起作用,因为这些类循环相互引用。如何在不破坏当前代码逻辑的情况下打破循环依赖?该片段仅用于演示目的。我不需要专门用这段代码来解决问题。我想知道一般情况下,Python是否有内置的方法来消除这样的循环依赖?例如,在 Django 中,您可以将类名括在引号中以推迟依赖关系解析。在 C++ 中,您可以在文件的开头声明函数签名,然后声明其实现。纯Python中有类似的机制吗?

python
  • 2 个回答
  • 129 Views
Martin Hope
Aycon
Asked: 2023-09-25 12:55:26 +0000 UTC

如何在请求之间保存关键数据(密码)?

  • 5

我正在编写一个文件共享网站。它包含一个用于浏览服务器文件夹中文件的树。用户单击该文件夹,并向服务器发送一个请求GET,其中包含该文件夹路径的参数。服务器返回JSON此文件夹中文件结构的表示,并且用户“展开”此文件夹的树枝。如果用户选择的文件是存档,则服务器返回JSON存档中文件夹结构的表示。如果存档使用密码加密,服务器将返回错误并要求用户输入密码,以便向他显示存档的内容。


问题是:

  1. 如何使用GET质询安全地传输密码?(我知道这是一个愚蠢的想法,但我希望你能提出另一种方法。这不适合PUT我使用)

  2. 如果存档是嵌套的并且用户需要输入两个密码,如何保存上一个请求的密码?

# Исходное дерево:

+--- Root
|    +--- Folder 1
|    \--- File 1

# Пользователь нажал на "Folder 1"

+--- Root
|    +--- Folder 1
|    |    +--- Folder 2
|    |    |--- Archive 1
|    |    \--- Folder 3
|    \--- File 1


# Пользователь нажал на "Archive 1"
# Сервер попытался отобразить файлы "Archive 1"
# и оказалось, что он требует пароль
# Сервер возвращает "Forbidden" и перед
# пользователем появляется модальное окно с
# предложением ввести пароль. Пользователь
# вводит пароль и он отправляется (КАК?)
# вместе с запросом "GET".

+--- Root
|    +--- Folder 1
|    |    +--- Folder 2
|    |    |--- Archive 1
|    |    |    +--- Folder 4
|    |    |    |--- Archive 2
|    |    |    |--- File 2
|    |    |    \--- Folder 5
|    |    \--- Folder 3
|    \--- File 1


# Если сейчас пользователь нажмёт на
# "Archive 2", то у меня будут проблемы,
# потому что сервер обязан будет помнить
# пароль от первого архива и должен
# запросить пароль от второго архива.
# Каждый раз сервер начинает обход папок
# с корня "ROOT" как функция
# "scandir".

我应该将密码存储在服务器上吗?在会议中?强制用户立即输入密码列表?存储在js中?如何安全储存和运输?


REST 意识形态对这项任务有何看法?这是一个例外还是有一些好的解决方案?如果我在服务器上以明文形式存储密码,我应该多久清除一次用户会话?

http
  • 1 个回答
  • 54 Views
Martin Hope
Aycon
Asked: 2023-09-21 15:47:57 +0000 UTC

如何创建 lambda 风格的函数存根?

  • 7

我创建了一个树类来跟踪内部变量中的元素数量length。在此类的构造函数中,我传递了hook一个函数,length每当子树的元素数量发生变化时,该函数都会更改树的父级。

class Tree(list):
    def __init__(self, change_length_hook=lambda *_:None, *args, **kwds):
        super().__init__(*args, **kwds)
        self.length = 0
        self._change_length_hook = change_length_hook

    def _change_length(self, cnt:int=1, ml:int=1):
            self.length += cnt * ml
            self._change_length_hook(cnt, ml)
    
    def __add__(self, other):
        if isinstance(other, Tree):
            self._change_length(other.length)
            return self.__class__(self + other)
        
        self._change_length(len(other))
        return self.__class__(self + list(other))

我想要某种根树的存根,它可以接受任意数量的参数,并且在调用时不执行任何操作,这样我就可以将它指定为函数的默认参数,这样调用它就不会成为树根的问题_change_length_hook。


所以我想要类似的东西lambda *_, **_: None,但它不起作用。有什么建议么?

python
  • 2 个回答
  • 40 Views
Martin Hope
Aycon
Asked: 2023-09-21 12:00:41 +0000 UTC

分配给切片意味着什么?

  • 9

我正在查看一个类的实现collections.UserList,并发现了一些不寻常的语法:

def __init__(self, initlist=None):
        self.data = []
        if initlist is not None:
            # XXX should this accept an arbitrary sequence?
            if type(initlist) == type(self.data):
                self.data[:] = initlist
            elif isinstance(initlist, UserList):
                self.data[:] = initlist.data[:]
            else:
                self.data = list(initlist)

这行是什么意思? self.data[:] = initlist.data[:] 我猜这是创建列表的浅表副本,但为什么要这样呢?为什么不简单写self.data = initlist.data[:]呢?这样的语法是否会产生一些我不知道的效果?

python
  • 2 个回答
  • 53 Views
Martin Hope
Aycon
Asked: 2023-09-18 13:50:11 +0000 UTC

“顶级”括号表达式的正则表达式

  • 5

我正在尝试编写一个正则表达式,它将正确匹配大括号内的所有表达式,但会忽略所有嵌套的出现。我不希望正则表达式导致灾难性的回报。这里有两行(为了可读性添加了换行符):

1) "Пакет {0} требует наличия не менее {features.count} функций компании
 {company.name} в городе {company.location.city}"

2) "associated_data = {"package":42, "features":{"count":12, "items":[...]}, 
"company": "name":"Contoso", "location":{"city":"Saint Petersburg"}}}"

在第一行中,我想匹配:

['{0}', '{features.count}', '{company.name}', '{company.location.city}']

在第二行我想匹配:

['{"package":42, "features":{"count":12, "items":[...]}, 
"company": "name":"Contoso", "location":{"city":"Saint Petersburg"}}}']

例如,贪婪算法r'(?<!\\)\{.*(?<!\\)\}'在第一行失败,因为它匹配整个内容:

['{0} требует наличия не менее {features.count} функций компании {company.name} 
в городе {company.location.city}']

非贪婪的 ( r'(?<!\\)\{[^{}]*(?<!\\)}') 落在第二个上,因为他取:

['{"count":12, "items":[...]}', '{"city":"Saint Petersburg"}']

您可能会问,“Rexx 如何猜测您到底想要什么?”;我会回答 - “正则表达式必须找到在嵌套的最高级别上由正确的大括号对包围的最小表达式。”。

python
  • 2 个回答
  • 61 Views
Martin Hope
Aycon
Asked: 2023-06-28 17:34:34 +0000 UTC

皮兰斯抱怨调用 Union 函数参数

  • 5

我有以下代码作为最低限度可重现的示例:

from typing import Any, Callable, Generic, Optional, TypeVar, Union
from random import choice

T1 = TypeVar("T1")

class qux(Generic[T1]):
    def foo(self) -> Callable[[T1], None]:
        def foo_wrapper(arg:T1):
            print(f'Bar wrapper called with argument {arg}')

        return foo_wrapper

    def bar(self) -> Callable[[], None]:
        def bar_wrapper():
            print('Foo wrapper called without arguments')
        
        return bar_wrapper
        
    def buzz(self, func:Union[Callable[[T1], Any], Callable[[], Any]], arg: Optional[T1] = None):
        if arg:
            func(arg)
        else:
            func()
            
    def choice_impl(self, flag:bool):
        if flag:
            return self.foo()
        else:
            return self.bar()
    
qux_instance = qux()
value = None
if choice((True, False)):
    value = 42

flag = value is not None

implementation = qux_instance.choice_impl(flag=flag)
if flag:
    qux_instance.buzz(func=implementation, arg=value)
else:
    qux_instance.buzz(func=implementation)

皮兰斯在第 21 行发誓:

Expected 0 positional arguments  (parameter) arg: T1@qux

和23:

Expected 1 more positional argument (parameter) func: ((T1@qux) -> Any) | (() -> Any)

因为它不知道func函数参数buzz在调用时将具有什么签名。虽然这段代码运行起来总是没有错误。我怎么解决这个问题?这是 Pylance 的错误还是与停止问题有关?还是我的手歪了?

python
  • 1 个回答
  • 26 Views
Martin Hope
Aycon
Asked: 2023-06-26 12:48:01 +0000 UTC

`pathlib` 中 `os.path.commonpath()` 的类似物

  • 8

pathlib我正在尝试尽可能使用图书馆os.path。

commonpath()告诉我,这个库中有类似的函数吗?我没有找到。如果没有内置函数,我不会为其编写代码,而只是使用os.path.commonpath().

python
  • 1 个回答
  • 40 Views
Martin Hope
Aycon
Asked: 2023-06-09 15:26:31 +0000 UTC

python 中的执行线程可以在等待完成之前在 `await` 之后执行命令吗?

  • 5

假设我有以下代码:

from my_module import MyTask
import asyncio

async def main():
    async def controll(fsuspend):
        await asyncio.sleep(2)
        resume = await fsuspend()
        await asyncio.sleep(2)
        await resume()
    
    run, suspend, cancel = MyTask()
    await run
    print('Test')
    await control(suspend)

asyncio.run(main())
  1. 在函数等待完成之前,函数代码control不会运行run?
  2. 如何检查该函数是否suspend在异步上下文中工作?
  3. 需要使用线程同时运行run两者?control
  4. 在这种情况下,函数会print向控制台打印一条消息吗?
  5. 该函数会在运行结束前print打印一条消息吗?
python
  • 1 个回答
  • 31 Views
Martin Hope
Aycon
Asked: 2023-05-31 13:38:15 +0000 UTC

在python中插入字符串时如何在没有缩进的情况下引用一个值?

  • 5

下一个模板:

'module: "{module:10s}"; file: "{filename:10s}"; line: "{lineno:3d}"; msg: "{message}";'

匹配字符串:

module: "views     "; file: "views.py  "; line: " 62"; msg: "text";

哪个缩进模式匹配行(?):

module: "views";      file: "views.py";   line: "62";  msg: "text";
python
  • 1 个回答
  • 34 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5