def dict_merge(a: dict, b: dict) -> dict: """Recursively merge dicts. Not just simple a['key'] = b['key'], if both a and b have a key who's value is a dict then dict_merge is called on both values and the result stored in the returned dictionary. https://www.xormedia.com/recursively-merge-dictionaries-in-python/""" if not isinstance(a, (dict, _frozendict)) or not isinstance(b, (dict, _frozendict)): raise TypeError('Expected both dictionaries as arguments') if isinstance(a, _frozendict): a = dict(a) if isinstance(b, _frozendict): b = dict(b) result = _deepcopy(a) for k, v in b.items(): if k in result: if isinstance(result[k], dict) and isinstance(v, dict): result[k] = dict_merge(result[k], v) elif isinstance(result[k], list) and isinstance(v, (set, list, tuple)): result[k].extend(v) elif isinstance(result[k], set) and isinstance(v, (set, list, tuple)): result[k].update(v) else: result[k] = _deepcopy(v) else: result[k] = _deepcopy(v) return result
def dict_merge(o, v): ''' Recursively climbs through dictionaries and merges them together. :param o: The first dictionary :param v: The second dictionary :returns: A dictionary (who would have guessed?) .. note:: Make sure `o` & `v` are indeed dictionaries, bad things will happen otherwise! ''' if not isinstance(v, dict): return v res = _deepcopy(o) for key in v.keys(): if res.get(key) and isinstance(res[key], dict): res[key] = dict_merge(res[key], v[key]) else: res[key] = _deepcopy(v[key]) return res
def inv(mat): """ To solve the inverse matrix of the given matrix. """ if mat.shape[0] != mat.shape[1]: raise IndexError("square matrix expected") if Matrix.det(mat) == 0: return None if not mat: return mat array = _deepcopy(mat.array) e = Matrix.eye(mat.shape[0]) for i, row in enumerate(array): row.extend(e.array[i]) array = Matrix._transform(array, mat.shape[0], True)[0] for i in range(mat.shape[0]): if array[i][i] != 1: array[i] = list(map(lambda x: x/array[i][i], array[i])) for row in array: del row[0: mat.shape[0]] return Matrix(array)
def __init__(self, matrix, unconnected=0): self.vertex_num = len(matrix) _ = {len(row) for row in matrix} if len(_) != 1 or self.vertex_num not in _: raise IndexError self.matrix = _deepcopy(matrix) self.unconnected = unconnected
def transform(self, state, invert=False): '''Given the content of one cell of the state matrix, 'divide' in 2 halfs. The upper is understood as the row and the lower as the column in the sbox. The sbox is a paramenter because the transformation use one sbox or its invers, but the procedure is the same. Input: Output: ''' output = _deepcopy(state) if self._useCalc: if invert: sbox = self._invertsbox_call_ else: sbox = self._sbox_call_ for i in range(len(output)): if type(output[i]) == list: for j in range(len(output[i])): output[i][j] = sbox(output[i][j]) else: output[i] = sbox(output[i]) # else: # if invert: # sbox = self._sbox_inverted # else: # sbox = self._sbox # for i in range(len(output)): # if type(output[i]) == list: # for j in range(len(output[i])): # r, c = self.__hexValue2MatrixCoords(output[i][j]) # output[i][j] = sbox[r][c] # else: # r, c = self.__hexValue2MatrixCoords(output[i]) # output[i] = sbox[r][c] return output
def newParam(prog, var="default"): """ Return a new parameter set for given program prog -> file format, needs to be in _paramdict preset -> variant of default set, if present """ return _deepcopy(_paramdict[prog][var])
def Insert( self, index, element ): ''' Insert element in index. ''' element = _deepcopy(element) self.values.insert(index,element) if isinstance(self,Matrix): self.rows += 1 elif isinstance(self,Vector): self.length += 1
def copy_burp(brp_in, brp_out): """ Copies all file, report, block, and code information from the input BurpFile to the output BurpFile, except does not copy over filename or mode. """ assert isinstance(brp_in, BurpFile) and isinstance(brp_out, BurpFile), "Input object must be an instance of BurpFile." for attr in BurpFile.burp_attr: setattr(brp_out, attr, _deepcopy(getattr(brp_in, attr))) return
def sections(self): """ Returns a list of sections from the config :return: list(str) """ if self._bootstrap: return [section.schema for section in self._CONFIG_SCHEMA.schema.keys()] else: return _deepcopy(self._configuration.keys())
def permutekeys(self, perm, deepcopy=False): mkd = type(self)() mkd.__dict__ = _deepcopy(self.__dict__) if hasattr(perm, '__call__'): _permute = perm else: _permute = lambda k: tuple(k[i] for i in perm) mkd._keyorder = OrderedSet() if deepcopy: for k, v in self.sorteditemsmk(): v = _deepcopy(v) mkd.set(_permute(k), v) else: for k, v in self.sorteditemsmk(): mkd.set(_permute(k), v) return mkd
def __deepcopy__(self, memodict=None): if memodict is None: memodict = {} cls = self.__class__ new_mat = cls() memodict[id(self)] = new_mat for key, item in self.__dict__.items(): setattr(new_mat, key, _deepcopy(item, memodict)) return new_mat
def __init__( self, *values ): ''' Constructor. Takes as many arguments as desired. Copy constructor is also implemented. The arithmetic operators are defined to be applied element by element. Special operations have special syntax: - Dot product is the __pow__ method (** operator). - Appending values is performed using the Add method. ... ''' self.values = _deepcopy(list(values)) self.length = len(self.values)
def collapsekeys(self, height, deepcopy=False): assert height > 1 mkd = type(self)() if deepcopy: for k, v in self.sorteditemsmk(height=height): mkd[k] = _deepcopy(v) else: for k, v in self.sorteditemsmk(height=height): mkd[k] = v return mkd
def options(self, section): """ Returns a list of option names for the section in the config :param section: The name of the section, e.g. "main" or "s3" :type section: str :return: list(str) """ if self._bootstrap: schema_options = {section.schema: [option.schema for option in self._CONFIG_SCHEMA.schema[section]] for section in self._CONFIG_SCHEMA.schema} return schema_options[section] else: return _deepcopy(self._configuration[section].keys())
def append(self, population: Population): """Append the next step in the trajectory. Parameters ---------- population: Population The population to append to this list """ if not isinstance(population, Population): raise TypeError("Only Population objects should be recorded!") if self._trajectory is None: self._trajectory = [] self._trajectory.append(_deepcopy(population))
def _extract(data: _tany) -> _tlist_any: if _is_list(data): result = _deepcopy(data) elif _is_dictionary(data): result = list(data.values()) elif _is_iterable(data): result = list(data) else: result = None if result is None: raise TypeError('The data type is not supported.') return result
def _get_mil_internal(self): """ Get a deep copy of the MIL program object, if available. It's available whenever an MLModel object is constructed using the unified converter API [`coremltools.convert()`](https://apple.github.io/coremltools/source/coremltools.converters.mil.html#coremltools.converters._converters_entry.convert). Returns ------- program: coremltools.converters.mil.Program Examples -------- >>> mil_prog = model._get_mil_internal() """ return _deepcopy(self._mil_program)
def __init__(self, obj: Obj, probe: Probe, scan_grid: ScanGrid, intensities: np.ndarray, obj_array_true: np.ndarray = None, probe_wavefront_true: np.ndarray = None): self.obj = _deepcopy(obj) self.probe = _deepcopy(probe) self.scan_grid = scan_grid self.intensities = intensities self._obj_border_mask = np.pad(np.full(self.obj.shape, False), self.obj.border_shape, mode="constant", constant_values=True) self.obj_array_true = obj_array_true self.probe_wavefront_true = probe_wavefront_true self.shuffle_order = [] self.losses = [] self.obj_errors = [] self.probe_errors = []
def _subclass_factory(cls, default_maxdepth, _memo=dict(), **nspace): assert default_maxdepth > 0 key = tuple([default_maxdepth] + sorted(nspace.items())) ret = _memo.get(key, None) if ret is None: kwargs = _deepcopy(nspace) class _submkd(cls): def __init__(self, maxdepth=default_maxdepth, **ignored): cls.__init__(self, maxdepth=maxdepth, **kwargs) def __reduce_ex__(self, proto): return (MultiKeyDict, (), self.__dict__, None, self.iteritems()) _submkd.__name__ = name = '_submkd__%d' % id(_submkd) globals()[name] = _memo[key] = ret = _submkd return ret
def apply(self, envelope): """ Применяет профиль безопасности к конверту SOAP :param envelope: Soap конверт :return: Soap envelope with applied security """ logger.info("Signing document ...") unsigned = _deepcopy(envelope) try: return sign_document(envelope, self.certificate, self.private_key, self._private_key_pass, self.digest_method) except ValueError, e: logger.error("Error occurred while signing document:\n{0}\n" "Keep it unsigned ...".format(e.message)) return unsigned
def dijstra(self, g : _g.Graph, s : _g.Vertex): ''' 单源最短路径Dijstra算法 ''' self.initialize_single_source(g, s) S = [] Q = _deepcopy(g.veterxs) while len(Q) != 0: Q.sort(reverse=True) u = Q.pop() S += [u] adj = g.getvertexadj(u) if adj is not None: for v in adj: edge = g.getedge(u, v) self.relax(u, v, edge.weight)
def copy_burp(brp_in, brp_out): """ Copies all file, report, block, and code information from the input BurpFile to the output BurpFile, except does not copy over filename or mode. Args: brp_in : BurpFile instance to copy data from brp_out : BurpFile instance to copy data to Returns: None """ assert isinstance(brp_in, BurpFile) and isinstance( brp_out, BurpFile), "Input object must be an instance of BurpFile." for attr in BurpFile.burp_attr: setattr(brp_out, attr, _deepcopy(getattr(brp_in, attr))) return
def note(self): ''' Summary ==== Print chapter8.4 note Example ==== ```python Chapter8_4().note() ``` ''' print('chapter8.4 note as follow') print('当桶排序的输入符合均匀分布时,即可以以线性时间运行,与计数排序类似,桶排序也对输入作了某种假设') print('具体来说,计数排序假设输入是由一个小范围内的整数构成,而桶排序则假设输入由一个随机过程产生,该过程将元素均匀地分布在区间[0,1)上') print('桶排序的思想就是把区间[0,1)划分成n个相同大小的子区间,或称桶。然后将n个输入分布到各个桶中去') print('因为输入数均匀分布在[0,1)上,所以一般不会有很多数落在一个桶中的情况') print('为了得到结果,先对桶中的数进行排序,然后按次序把桶中的元素列出来即可。') print('在桶排序的算法当中') print('桶排序算法中,假设输入的是一个含n个元素的数组A,且每个元素满足[0,1)') print('还需要一个辅助数组B[0..n-1]来存放链表(桶),并假设可以用某种机制来维护这些表') print('桶排序的期望时间复杂度为Θ(n),证明过程略') A = [0.79, 0.13, 0.16, 0.64, 0.39, 0.20, 0.89, 0.53, 0.71, 0.42] print('练习8.4-1 数组A', _deepcopy(A), '的桶排序过程为:', self.bucketsort(A)) print('练习8.4-2 略') print('练习8.4-3 E(X^2)=DX+E^2(X)=9/16+1 E^2(X)=E(X)E(X)=1') print('练习8.4-4 所有点到圆心的距离都服从均匀分布,所以采用桶排序') print('练习8.4-5 略') print('思考题8-1 给定n个不同的输入元素,对于任何确定或随机的比较排序算法,其期望运行时间都有下界Ω(nlgn)') print('思考题8-2 以线性时间原地置换排序:假设有一个由n个数据记录组成的数组要排序,且每个记录的关键字的值0或1') print(' 算法的运行时间为O(n),算法是稳定的,算法是原地排序的') print('思考题8-3 排序不同长度的数据项,字符串所有字符串字符的ascii码都不大于z,所以用基数排序,O(n)') print('思考题8-4 水壶:假设给定了n个红色的水壶和n个蓝色的水壶,他们的形状尺寸都不相同,所有红色水壶中所盛水的量都不同。') print(' 所有红色水壶中所盛水的量都不一样,蓝色水壶也是一样的;此外,对于每一个红色的水壶,都有一个对应的蓝色水壶,两者所盛的水量是一样的,反之亦然') print(' 任务是将匹配的红色水壶和蓝色水壶找出来,假设用1,2,3,4,5代表不同的水量') print('[1,2,3,4,5]和[5,4,3,2,1]的匹配为:', self.find_matching_kettle([1,2,3,4,5], [5,4,3,2,1])) print(' 只会双重循环比较算法,对于下界为O(nlgn),考虑二叉树和递归算法吧,随机化算法也不会') print('思考题8-5 k排序,1排序就是完全排序') print(' 一个n元素的数组是k排序的,当且仅当对所有元素,当前A[i]<=A[i+k]') print('思考题8-6 合并已排序列表的下界') print(' 合并两个已知已排序列表这样的问题是经常出现的。它是合并排序的一个子过程') print(' 决策树说明比较次数有一个下界2n-o(n),还有一个更紧确的2n-1界') print('Han将排序算法的界改善至O(nlglgnlglglgn),尽管这些算法在理论上有重要的突破,', '但都相当复杂,在目前来看,不太可能与现有的,正在实践中使用的排序算法竞争')
def updateSegment(self, segmentID: str = None, segmentJSON: dict = None) -> object: """ Method that update a specific segment based on the dictionary passed to it. Arguments: segmentID : REQUIRED : Segment ID to be deleted segmentJSON : REQUIRED : the dictionary that represents the JSON statement for the segment. """ if segmentJSON is None or segmentID is None: print('No segment or segementID data has been pushed') return None data = _deepcopy(segmentJSON) seg = _putData(self._endpoint_company + self._getSegments + '/' + segmentID, data=data, headers=self._header) return seg
def __init__(self, canvas, quotationInformation): self.__canvas = canvas self.__quotationInformation = quotationInformation self.__count, self.__pageNo, self.__partIndex = 0, 1, 0 self.__isNextPage = False self._createInnerTemplate() _createQuotationOuterTemplate(self.__canvas, 1, 1) if self.__isNextPage: self.__canvas.showPage() nextQuotationInformation = _deepcopy(quotationInformation) nextQuotationInformation['particulars'] = nextQuotationInformation['particulars'][self.__count:] nextQuotationInformation['hsnCodes'] = nextQuotationInformation['hsnCodes'][self.__count:] nextQuotationInformation['quantities'] = nextQuotationInformation['quantities'][self.__count:] nextQuotationInformation['rates'] = nextQuotationInformation['rates'][self.__count:] nextQuotationInformation['amounts'] = nextQuotationInformation['amounts'][self.__count:] QuotationTemplate(canvas, nextQuotationInformation)
def __mul__(self, other): # => a*b ''' ''' if type(other) == int: # a * n = [a, a,..., a] res = [] for i in range(other): res.append(_deepcopy(self)) return res a = _copy(self._coefficients) b = _copy(other._coefficients) res = self.__multiply__(a, b) self._debug_stream("c = a * b = %s * %s = %s" % (self.__interpretToStr__(a), self.__interpretToStr__(b), self.__interpretToStr__(res))) p = BinaryExtensionModuloConstructor(res) p.xors = self.xors return p
def sortbykey(self, array, keys): ''' 根据keys的大小来排序array ''' A = _deepcopy(array) length = len(A) for j in range(length): minIndex = j # 找出A中第j个到最后一个元素中的最小值 # 仅需要在头n-1个元素上运行 for i in range(j, length): if keys[i] <= keys[minIndex]: minIndex = i # 最小元素和最前面的元素交换 min = A[minIndex] A[minIndex] = A[j] A[j] = min return A
def _load_configuration(self, default_parameters, section): """Load parameters from configuration. Args: default_parameters (dict): default parameters section (str): Section in configuration.""" # Load default parameters parameters = _deepcopy(default_parameters) # Update with configuration for section in (section, '%s.%s' % (section, self._name)): self._get_parameters( { key: self._config[section].get_literal(key) for key in self._config[section] }, parameters, copy=False) return parameters
def set_input_files(self, input_files: InputFiles): """Set the input files that are used to initialise the simulation Parameters ---------- input_files: InputFiles The set of input files that will be used to load the Network. If a string is passed then the InputFiles will be loaded based on that string. """ if isinstance(input_files, str): input_files = InputFiles.load(input_files, repository=self._repository_dir) print("Using input files:") print(input_files) self.input_files = _deepcopy(input_files)
def _readData(self, data_rows: list, anomaly: bool = False, cols: list = None, item_id: bool = False): """ read the data from the requests and returns a dataframe. Parameters: data_rows : REQUIRED : Rows that have been returned by the request. anomaly : OPTIONAL : Boolean to tell if the anomaly detection has been used. cols : OPTIONAL : list of columns names """ data_rows = _deepcopy(data_rows) dict_data = {} dict_data = {row['value']: row['data'] for row in data_rows} if cols is not None: n_metrics = len(cols) - 1 if item_id: # adding the itemId in the data returned cols.append('item_id') for row in data_rows: dict_data[row['value']].append(row['itemId']) if anomaly: # set full columns cols = cols + [ f'{metric}-{suffix}' for metric in cols[1:] for suffix in ['expected', 'UpperBound', 'LowerBound'] ] # add data to the dictionary for row in data_rows: for item in range(n_metrics): dict_data[row['value']].append( row.get('dataExpected', [0 for i in range(n_metrics)])[item]) dict_data[row['value']].append( row.get('dataUpperBound', [0 for i in range(n_metrics)])[item]) dict_data[row['value']].append( row.get('dataLowerBound', [0 for i in range(n_metrics)])[item]) df = _pd.DataFrame(dict_data).T # require to transform the data df.reset_index(inplace=True, ) df.columns = cols return df
def modify_factor(sim, key_viscosity): """ Modifies factor for viscosity. """ params = _deepcopy(sim.params) params_old = sim.params sim_old = sim if key_viscosity == "nu_2": nu_old = params.nu_2 params.nu_2 = params.nu_2 * factor elif key_viscosity == "nu_8": nu_old = params.nu_8 params.nu_8 = params.nu_8 * factor else: raise ValueError params.init_fields.type = "in_script" params.time_stepping.t_end = t_end return params, nu_old
def permute_bysorting(self, array): ''' 随机打乱排列一个数组 Args = array : 随机排列前的数组 Return: = random_array : 随机排列后的数组 Example = >>> Chapter5_3().permute_bysorting([1, 2, 3, 4]) ''' n = len(array) P = _deepcopy(array) for i in range(n): P[i] = _randint(1, n**3) _time.sleep(0.002) return self.sortbykey(array, P)
def tile(self, reps): """ :type reps: tuple, list Generate a matrix by repeating the given matrix. >>> m = Matrix([[1, 2, 3], [2, 4, 6], [7, 8, 9]]) >>> m.tile((2, 1)) [[1 2 3] [2 4 6] [7 8 9] [1 2 3] [2 4 6] [7 8 9]] >>> m.tile((1, 2)) [[1 2 3 1 2 3] [2 4 6 2 4 6] [7 8 9 7 8 9]] >>> m.tile((1, 0)) [[]] >>> m.tile((0, 2)) [[1 2 3 1 2 3] [2 4 6 2 4 6] [7 8 9 7 8 9]] >>> m.tile((0, 1)) [[1 2 3] [2 4 6] [7 8 9]] """ array = _deepcopy(self.array) for i in range(reps[0]-1): array += array mat = Matrix(array) if reps[1] == 0: return Matrix() mat = mat.repeat(reps[1], 1) return mat
def countingsort(self, A, k): ''' 计数排序,无需比较,非原地排序,时间复杂度`Θ(n)` Args === `A` : 待排序数组 `k` : 数组中的元素都不大于k Return === `sortedarray` : 排序好的数组 Example === ```python >>> Chapter8_2().countingsort([0,1,1,3,4,6,5,3,5], 6) >>> [0,1,1,3,3,4,5,5,6] ``` ''' C = [] B = _deepcopy(A) k = 27 for i in range(k): C.append(0) length = len(A) for j in range(length): C[A[j]] = C[A[j]] + 1 for i in range(1, k): C[i] = C[i] + C[i - 1] for i in range(length): j = length - 1 - i B[C[A[j]] - 1] = A[j] C[A[j]] = C[A[j]] - 1 return B
def __init__(self, configuration=None): """ Parses the configuraiton file for validity and returns a ConfigParser like object which support set and get \ among other common methods :param configuration: The ConfigParser, file, or dict representing the configuration :type configuration: ConfigParser, file, or dict :raises InvalidConfig: If the config does not validate against the defined schema .. note:: Setting configuratoin to None create the StinyConfiguration object in bootstrap mode. In this mode, you may set any values that you like and it will defer validation until write. """ self._bootstrap = False if isinstance(configuration, ConfigParser): self._configuration = self._get_valid(self._configparser_to_dict(configuration)) elif isinstance(configuration, file): p = SafeConfigParser() p.readfp(configuration) self._configuration = self._get_valid(self._configparser_to_dict(p)) elif isinstance(configuration, dict): self._configuration = self._get_valid(_deepcopy(configuration)) elif configuration is None: self._configuration = dict() self._bootstrap = True
def get_grid_extent(grid): """ Get grid extent from a .sgrd file INPUTS grid [str] grid system file name (.sgrd) OUTPUTS extent [np.ndarray] grid extent [xmin, xmax, ymin, ymax] """ if type(grid) in (_OrderedDict, dict): # grid is a gridsystem gs = _deepcopy(grid) else: # Check inputs grid = _validation.input_file(grid, 'grid', True) # Get grid system and values gs = grid_system(grid) xmin = gs['POSITION_XMIN'] ymin = gs['POSITION_YMIN'] dxy = gs['CELLSIZE'] nx = gs['CELLCOUNT_X'] ny = gs['CELLCOUNT_Y'] # Create extent extent = _np.array([xmin, xmin + dxy * (nx - 1), ymin, ymin + dxy * (ny - 1)]) return(extent) # get_grid_extent()
def get_grid_info(self): """ Use gdal library for extract raster information as a dictionary OUTPUT rinfo [dict] raster information dictionary """ # Check grid connection if type(self.driver) is not _gdal.Dataset: # it is a valid gdal dataset? raise TypeError('You must connect with a raster file!') # Get raster properties geotrans = _deepcopy(self.driver.GetGeoTransform()) # get transformation projref = self.driver.GetProjectionRef() # get projection drivername = self.driver.GetDriver().ShortName # get file driver xsize = self.driver.RasterXSize # get x size ysize = self.driver.RasterYSize # get y size bands = self.driver.RasterCount # count number of layers # Output data rinfo = {'geotransform': geotrans, 'projectionref': projref, 'drivername': drivername, 'xsize': xsize, 'ysize': ysize, 'bands': bands} return(rinfo) # grid_info()
def set_variables(self, variables: VariableSet): """This function sets the adjustable variable values to those specified in 'variables' in A COPY OF THIS PARAMETERS OBJECT. This returns the copy. It does not change this object Parameters ---------- variables: VariableSet The variables that will be adjusted before the model run. This adjusts the parameters and returns them in a deep copy Returns ------- params: Parameters A copy of this set of parameters with the variables adjusted """ params = _deepcopy(self) if isinstance(variables, dict): variables = VariableSet(variables) variables.adjust(params) return params
def transitive_closure(self, g : _g.Graph): ''' 有向图`g`的传递闭包 ''' n = g.vertex_num t = _np.zeros((n, n)) for i in range(n): for j in range(n): edge = g.getedge(g.veterxs[i], g.veterxs[j]) if i == j or edge in g.edges: t[i][j] = 1 else: t[i][j] = 0 t_last = _deepcopy(t) for k in range(n): for i in range(n): for j in range(n): result = t_last[i][j] or (t_last[i][k] and t_last[k][j]) if result == True: t[i][j] = 1 else: t[i][j] = 0 t_last = t return t
def Ring(self): return _deepcopy(self.__sbox.getRing())
def Mu(self): return _deepcopy(self.__sbox.getMu())
def Field(self): return _deepcopy(self.__sbox.getField())
def Clear( self ): ''' Sets all the values to 0.0 . ''' self.values = _deepcopy(Zeros(self.length))
def __init__( self, nodes = list() ): ''' Initialize with the list of nodes. It is also possible to add them later with the AddNode method. ''' self.nodes = _deepcopy(nodes) self.Nnodes = len( self.nodes )
def fromdict(cls, dict_, deep=False): ret = cls() for k, v in dict_.items(): ret[k] = (cls.fromdict(v, deep) if isinstance(v, dict) else _deepcopy(v) if deep else v) return ret
def copy(self): return _deepcopy(self)
def SubfieldModulo(self): return _deepcopy(self.__cx._coefficients[0].modulo)
def PolynomialRingModulo(self): return _deepcopy(self.__cx.modulo)
def __deepcopy__(self, memo): """Create a deep copy of the dictionary.""" copy = self.__class__() for k,v in self.items(): copy[k] = _deepcopy(v, memo) return copy
def Nu(self): return _deepcopy(self.__sbox.getNu())
def permute_arrays(old_blocks,new_blocks,map_old2new): for it in old_blocks.keys(): tmp = list(_deepcopy(it)) for i in xrange(len(it)): tmp[map_old2new[1][i]] = it[map_old2new[0][i]] new_blocks[tuple(tmp)] = old_blocks[it].transpose([i for j,y in enumerate(map_old2new[0]) for i,x in enumerate(map_old2new[1]) if (x==y)])