code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# extract backend class name, eg: AirOS or OpenWRT backend_class_name = self.backend.split('.')[-1] # convert to lowercase to get the path backend_path = self.backend.lower() # import module by its path module = import_module(backend_path) # get netengine...
def _get_netengine_backend(self)
returns the netengine backend specified in self.backend for internal use only
5.250378
4.713983
1.113788
arguments = { "host": self.host } if self.config is not None: for key, value in self.config.iteritems(): arguments[key] = value if self.port: arguments["port"] = self.port return arguments
def _build_netengine_arguments(self)
returns a python dictionary representing arguments that will be passed to a netengine backend for internal use only
3.018285
2.870085
1.051636
# retrieve netengine dictionary from memory or from network device_dict = getattr(self, 'netengine_dict', self.netengine.to_dict()) device = Device() device.node_id = self.node_id device.name = device_dict['name'] device.type = device_dict['type'] device....
def __create_device(self)
creates device, internal use only
2.187227
2.180424
1.00312
if request.user.is_anonymous(): group = 'public' elif request.user.is_superuser: group = 'superuser' else: try: group = request.user.groups.all().order_by('-id').first().name except IndexError: group = 'public' key = '%s:%s.%s.%s' % ( ...
def cache_by_group(view_instance, view_method, request, args, kwargs)
Cache view response by media type and user group. The cache_key is constructed this way: "{view_name:path.group.media_type}" EG: "MenuList:/api/v1/menu/.public.application/json" Possible groups are: * public * superuser * the rest are retrieved from DB (registered, community, trusted...
2.761907
2.378428
1.161232
schema = copy.deepcopy(schema) resolver = resolver class Model(base_class): def __init__(self, *args, **kwargs): self.__dict__['schema'] = schema self.__dict__['resolver'] = resolver base_class.__init__(self, *args, **kwargs) if resolver is not None: ...
def model_factory(schema, resolver=None, base_class=model.Model, name=None)
Generate a model class based on the provided JSON Schema :param schema: dict representing valid JSON schema :param name: A name to give the class, if `name` is not in `schema`
2.179967
2.472012
0.881859
original = self.__dict__['__original__'] return jsonpatch.make_patch(original, dict(self)).to_string()
def patch(self)
Return a jsonpatch object representing the delta
7.520489
6.278191
1.197875
deprecation_msg = 'Model.changes will be removed in warlock v2' warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2) return copy.deepcopy(self.__dict__['changes'])
def changes(self)
Dumber version of 'patch' method
6.499334
6.12828
1.060548
try: if self.resolver is not None: jsonschema.validate(obj, self.schema, resolver=self.resolver) else: jsonschema.validate(obj, self.schema) except jsonschema.ValidationError as exc: raise exceptions.ValidationError(str(exc))
def validate(self, obj)
Apply a JSON schema to an object
2.364742
2.203838
1.073011
magic = bytearray(fileContent)[:4] return magic == p('>I', 0xfeedface) or magic == p('>I', 0xfeedfacf) or magic == p('<I', 0xfeedface) or magic == p('<I', 0xfeedfacf)
def isSupportedContent(cls, fileContent)
Returns if the files are valid for this filetype
3.586481
3.426506
1.046687
header = OatHeader.from_buffer(data) if header.magic != b'oat\n': raise BinaryError('No valid OAT file') key_value_store_bytes = (c_ubyte * header.keyValueStoreSize).from_buffer(data, sizeof(OatHeader)) key_value_store = self.__parseKeyValueStore(key_value_store_byt...
def _parseOatHeader(self, data)
Returns the OatHeader
3.695541
3.603812
1.025453
offset = 0 key_value_store = {} while offset != len(data): key = get_str(data, offset) offset += len(key)+1 value = get_str(data, offset) offset += len(value)+1 key_value_store[key] = value return key_value_store
def __parseKeyValueStore(self, data)
Returns a dictionary filled with the keys and values of the key value store
2.288126
2.095538
1.091904
return addr - section.header.VirtualAddress + section.header.PointerToRawData
def to_raw_address(addr, section)
Converts the addr from a rva to a pointer to raw data in the file
10.287416
7.536322
1.365045
classes = None machine = IMAGE_FILE_MACHINE[c_ushort.from_buffer(data,imageDosHeader.header.e_lfanew+4).value] if machine == IMAGE_FILE_MACHINE.I386: classes = PE32 elif machine == IMAGE_FILE_MACHINE.AMD64: classes = PE64 return classes
def _getSuitableClasses(self, data, imageDosHeader)
Returns the class which holds the suitable classes for the loaded file
4.549967
4.35251
1.045366
ioh = IMAGE_DOS_HEADER.from_buffer(data) if ioh.e_magic != b'MZ': raise BinaryError('No valid PE/COFF file') return ImageDosHeaderData(header=ioh)
def _parseImageDosHeader(self, data)
Returns the ImageDosHeader
7.489472
6.600646
1.134657
inth = self._classes.IMAGE_NT_HEADERS.from_buffer(data, imageDosHeader.header.e_lfanew) if inth.Signature != b'PE': raise BinaryError('No valid PE/COFF file') return ImageNtHeaderData(header=inth)
def _parseImageNtHeaders(self, data, imageDosHeader)
Returns the ImageNtHeaders
8.070989
7.389606
1.092208
sections = [] optional_header_offset = imageDosHeader.header.e_lfanew + 4 + sizeof(IMAGE_FILE_HEADER) offset = optional_header_offset + imageNtHeaders.header.FileHeader.SizeOfOptionalHeader # start reading behind the dos- and ntheaders image_section_header_size = sizeof(IMAGE...
def _parseSections(self, data, imageDosHeader, imageNtHeaders, parse_header_only=False)
Parses the sections in the memory and returns a list of them
3.785077
3.835295
0.986906
for section in sections: if data_directory_entry.VirtualAddress >= section.header.VirtualAddress and \ data_directory_entry.VirtualAddress < section.header.VirtualAddress + section.header.SizeOfRawData : return section
def _getSectionForDataDirectoryEntry(self, data_directory_entry, sections)
Returns the section which contains the data of DataDirectory
2.692927
2.687867
1.001883
data_directory_data_list = [None for i in range(15)] # parse DataDirectory[Export] export_data_directory = imageNtHeaders.header.OptionalHeader.DataDirectory[ImageDirectoryEntry.EXPORT] export_section = self._getSectionForDataDirectoryEntry(export_data_directory, sections) ...
def _parseDataDirectory(self, data, sections, imageNtHeaders)
Parses the entries of the DataDirectory and returns a list of the content
1.773828
1.746835
1.015453
if not exportSection: return functions = [] export_directory = IMAGE_EXPORT_DIRECTORY.from_buffer(exportSection.raw, to_offset(dataDirectoryEntry.VirtualAddress, exportSection)) offset = to_offset(export_directory.Name, exportSection) checkOffset(offset, exp...
def _parseDataDirectoryExport(self, data, dataDirectoryEntry, exportSection)
Parses the EmportDataDirectory and returns an instance of ExportDirectoryData
2.606729
2.490594
1.04663
if not importSection: return raw_bytes = (c_ubyte * dataDirectoryEntry.Size).from_buffer(importSection.raw, to_offset(dataDirectoryEntry.VirtualAddress, importSection)) offset = 0 import_descriptors = [] while True: import_descriptor = IMAGE_IMP...
def _parseDataDirectoryImport(self, dataDirectoryEntry, importSection)
Parses the ImportDataDirectory and returns a list of ImportDescriptorData
3.332496
3.157945
1.055274
offset = to_offset(thunkRVA, importSection) table_offset = 0 thunks = [] while True: thunk = IMAGE_THUNK_DATA.from_buffer(importSection.raw, offset) offset += sizeof(IMAGE_THUNK_DATA) if thunk.Ordinal == 0: break th...
def __parseThunks(self, thunkRVA, importSection)
Parses the thunks and returns a list
3.632852
3.60224
1.008498
offset = to_offset(thunk.header.AddressOfData, importSection) if 0xf0000000 & thunk.header.AddressOfData == 0x80000000: thunk.ordinal = thunk.header.AddressOfData & 0x0fffffff else: ibn = IMAGE_IMPORT_BY_NAME.from_buffer(importSection.raw, offset) ch...
def __parseThunkData(self, thunk,importSection)
Parses the data of a thunk and sets the data
5.421215
5.656774
0.958358
ptr = ctypes.cast(ctypes.pointer(data), ctypes.c_void_p) if offset: ptr = ctypes.c_void_p(ptr.value + offset) if ptr_type != ctypes.c_void_p: ptr = ctypes.cast(ptr, ptr_type) return ptr
def get_ptr(data, offset=None, ptr_type=ctypes.c_void_p)
Returns a void pointer to the data
2.062918
1.978588
1.042621
bs = (ctypes.c_ubyte * len(barray))() pack_into('%ds' % len(barray), bs, 0, barray) return bs
def to_ubyte_array(barray)
Returns a c_ubyte_array filled with the given data of a bytearray or bytes
3.914747
3.488834
1.122079
with open(fileName, 'rb') as binFile: b = binFile.read() return to_ubyte_array(b)
def _readFile(self, fileName)
Returns the bytes of the file.
6.047751
5.542386
1.091182
classes = None if data[EI.CLASS] == ELFCLASS.BITS_32: if data[EI.DATA] == ELFDATA.LSB: classes = LSB_32 elif data[EI.DATA] == ELFDATA.MSB: classes = MSB_32 elif data[EI.CLASS] == ELFCLASS.BITS_64: if data[EI.DATA] == E...
def _getSuitableClasses(self, data)
Returns the class which holds the suitable classes for the loaded file
2.159812
2.089038
1.033879
ehdr = self.__classes.EHDR.from_buffer(data) return EhdrData(header=ehdr)
def _parseElfHeader(self, data)
Returns the elf header
13.172213
12.660591
1.040411
offset = elfHeader.header.e_phoff segments = [] for i in range(elfHeader.header.e_phnum): phdr = self.__classes.PHDR.from_buffer(data, offset) segment_bytes = (c_ubyte * phdr.p_filesz).from_buffer(data, phdr.p_offset) phdrData = PhdrData(header=phdr,...
def _parseSegments(self, data, elfHeader)
Return a list of segments
3.102842
3.075405
1.008922
offset = elfHeader.header.e_shoff shdrs = [] for i in range(elfHeader.header.e_shnum): shdr = self.__classes.SHDR.from_buffer(data, offset) section_bytes = None ba_section_bytes = None if shdr.sh_type != SHT.NOBITS: section...
def _parseSections(self, data, elfHeader)
Returns a list of sections
2.620285
2.597582
1.00874
for section in sections: strtab = sections[section.header.sh_link] if section.header.sh_type in (int(SHT.DYNSYM), int(SHT.SYMTAB)): section.symbols = self.__parseSymbolEntriesForSection(section, strtab)
def _parseSymbols(self, sections)
Sets a list of symbols in each DYNSYM and SYMTAB section
6.488317
5.000396
1.29756
for section in sections: if section.header.sh_link != SHN.UNDEF and section.header.sh_type in (SHT.REL, SHT.RELA): symbols = sections[section.header.sh_link].symbols relocations = self.__parseRelocationEntries(section, symbols) section.relocat...
def _parseRelocations(self, sections)
Parses the relocations and add those to the section
3.651873
3.528735
1.034896
tsnapints = np.ceil(tsnapint/self.dt) while(self.t < self.tmax): self._step_forward() if self.t>=tsnapstart and (self.tc%tsnapints)==0: yield self.t return
def run_with_snapshots(self, tsnapstart=0., tsnapint=432000.)
Run the model forward, yielding to user code at specified intervals. Parameters ---------- tsnapstart : int The timestep at which to begin yielding. tstapint : int The interval at which to yield.
4.885612
5.289904
0.923573
evals,evecs = np.linalg.eig(-self.S) asort = evals.argsort() # deformation wavenumbers and radii self.kdi2 = evals[asort] self.radii = np.zeros_like(self.kdi2) self.radii[0] = self.g*self.H/np.abs(self.f) # barotropic def. radius self.radii[1:] = 1./np...
def vertical_modes(self)
Calculate standard vertical modes. Simply the eigenvectors of the stretching matrix S
5.59083
5.182256
1.078841
if forward: pt = np.linalg.solve(self.pmodes[np.newaxis,np.newaxis],p.T).T else: pt = np.einsum("ik,k...->i...",self.pmodes,p) return pt
def modal_projection(self,p,forward=True)
Performs a field p into modal amplitudes pn using the basis [pmodes]. The inverse transform calculates p from pn
4.400532
4.221218
1.042479
# background vel. if len(np.shape(self.U)) == 0: self.U = (self.U * np.ones((self.ny))) print(np.shape(self.U)) self.set_U(self.U) # the meridional PV gradients in each layer self.Qy = (self.beta + np.gradient(np.gradient(self.U, self.dy), self.dy))[n...
def _initialize_background(self)
Set up background state (zonal flow and PV gradients).
8.221167
7.585704
1.083771
# The sqg model is diagonal. The inversion is simply qh = -kappa**2 ph self.a = np.asarray(self.Nb*np.sqrt(self.wv2i))[np.newaxis, np.newaxis, :, :]
def _initialize_inversion_matrix(self)
the inversion
26.367605
25.444248
1.036289
self.Ubg = np.asarray(U)[np.newaxis,...]
def set_U(self, U)
Set background zonal flow
11.385039
9.240565
1.232072
dx, dy = self._rk4_integrate(self.x, self.y, uv0fun, uv1fun, dt) self.x = self._wrap_x(self.x + dx) self.y = self._wrap_y(self.y + dy)
def step_forward_with_function(self, uv0fun, uv1fun, dt)
Advance particles using a function to determine u and v. Parameters ---------- uv0fun : function Called like ``uv0fun(x,y)``. Should return the velocity field u, v at time t. uv1fun(x,y) : function Called like ``uv1fun(x,y)``. Should return th...
2.94629
3.057389
0.963662
u0, v0 = uv0fun(x, y) k1u = dt*u0 k1v = dt*v0 x11 = self._wrap_x(x + 0.5*k1u) y11 = self._wrap_y(y + 0.5*k1v) u11, v11 = uv1fun(x11, y11) k2u = dt*u11 k2v = dt*v11 x12 = self._wrap_x(x + 0.5*k2u) y12 = self._wrap_y(y + 0.5*k2v) ...
def _rk4_integrate(self, x, y, uv0fun, uv1fun, dt)
Integrates positions x, y using velocity functions uv0fun, uv1fun. Returns dx and dy, the displacements.
1.444532
1.444977
0.999692
dx = x1-x0 dy = y1-y0 # roll displacements across the borders if self.pix: dx[ dx > self.Lx/2 ] -= self.Lx dx[ dx < -self.Lx/2 ] += self.Lx if self.piy: dy[ dy > self.Ly/2 ] -= self.Ly dy[ dy < -self.Ly/2 ] += self.Ly ...
def _distance(self, x0, y0, x1, y1)
Utitlity function to compute distance between points.
3.115432
3.134862
0.993802
## no longer necessary because we accept pre-padded arrays # assert c.shape == (self.Ny, self.Nx), 'Shape of c needs to be (Ny,Nx)' # first pad the array to deal with the boundaries # (map_coordinates can't seem to deal with this by itself) # pad twice ...
def interpolate_gridded_scalar(self, x, y, c, order=1, pad=1, offset=0)
Interpolate gridded scalar C to points x,y. Parameters ---------- x, y : array-like Points at which to interpolate c : array-like The scalar, assumed to be defined on the grid. order : int Order of interpolation pad : int ...
5.553874
5.549593
1.000771
def step_forward_with_gridded_uv(self, U0, V0, U1, V1, dt, order=1): # create interpolation functions which return u and v # pre-pad arrays so it only has to be done once # for linear interpolation (default order=1), only one pad is necessary pad = order ...
Advance particles using a gridded velocity field. Because of the Runga-Kutta timestepping, we need two velocity fields at different times. Parameters ---------- U0, V0 : array-like Gridded velocity fields at time t - dt. U1, V1 : array-like ...
null
null
null
var_dens = 2. * np.abs(ph)**2 / model.M**2 # only half of coefs [0] and [nx/2+1] due to symmetry in real fft2 var_dens[...,0] /= 2 var_dens[...,-1] /= 2 return var_dens.sum(axis=(-1,-2))
def spec_var(model, ph)
Compute variance of ``p`` from Fourier coefficients ``ph``. Parameters ---------- model : pyqg.Model instance The model object from which `ph` originates ph : complex array The field on which to compute the variance Returns ------- var_dens : float The variance of `...
7.257128
6.633011
1.094093
ph2 = 2.*ph2 ph2[...,0] = ph2[...,0]/2. ph2[...,-1] = ph2[...,-1]/2. return ph2.sum(axis=(-1,-2))
def spec_sum(ph2)
Compute total spectral sum of the real spectral quantity``ph^2``. Parameters ---------- model : pyqg.Model instance The model object from which `ph` originates ph2 : real array The field on which to compute the sum Returns ------- var_dens : float The sum of `ph2`
3.224791
4.541286
0.710105
if model.kk.max()>model.ll.max(): kmax = model.ll.max() else: kmax = model.kk.max() # create radial wavenumber dkr = np.sqrt(model.dk**2 + model.dl**2) kr = np.arange(dkr/2.,kmax+dkr,dkr) phr = np.zeros(kr.size) for i in range(kr.size): fkr = (model.wv>=kr[i...
def calc_ispec(model, ph)
Compute isotropic spectrum `phr` of `ph` from 2D spectrum. Parameters ---------- model : pyqg.Model instance The model object from which `ph` originates ph : complex array The field on which to compute the variance Returns ------- kr : array isotropic wavenumber ...
4.128743
3.744814
1.102523
self.S = np.zeros((self.nz, self.nz)) if (self.nz==2) and (self.rd) and (self.delta): self.del1 = self.delta/(self.delta+1.) self.del2 = (self.delta+1.)**-1 self.Us = self.Ubg[0]-self.Ubg[1] self.F1 = self.rd**-2 / (1.+self.delta) ...
def _initialize_stretching_matrix(self)
Set up the stretching matrix
2.180824
2.153673
1.012607
self.H = self.Hi.sum() if np.asarray(self.U).ndim == 2: self.Ubg = self.U * np.ones((self.ny)) else: self.Ubg = np.expand_dims(self.U,axis=1) * np.ones((self.ny)) if not (self.nz==2): self.gpi = self.g*(self.rhoi[1:]-self.rhoi[:-1])/self.rh...
def _initialize_background(self)
Set up background state (zonal flow and PV gradients).
4.304323
4.20208
1.024332
ens = 0. for j in range(self.nz): ens = .5*self.Hi[j] * self.spec_var(self.wv2*self.ph[j]) return 2.*pi*np.sqrt( self.H / ens.sum() ) / 86400
def _calc_eddy_time(self)
estimate the eddy turn-over time in days
11.929751
10.585613
1.126978
self.add_diagnostic('entspec', description='barotropic enstrophy spectrum', function= (lambda self: np.abs((self.Hi[:,np.newaxis,np.newaxis]*self.qh).sum(axis=0))**2/self.H) ) self.add_diagnostic('KEspec_modal', description='...
def _initialize_model_diagnostics(self)
Extra diagnostics for layered model
3.361173
3.332833
1.008503
# Background zonal flow (m/s): self.H = self.Hi.sum() self.set_U1U2(self.U1, self.U2) self.U = self.U1 - self.U2 # the F parameters self.F1 = self.rd**-2 / (1.+self.delta) self.F2 = self.delta*self.F1 # the meridional PV gradients in each layer...
def _initialize_background(self)
Set up background state (zonal flow and PV gradients).
4.610403
4.353104
1.059107
self.set_q(np.vstack([q1[np.newaxis,:,:], q2[np.newaxis,:,:]])) #self.q[0] = q1 #self.q[1] = q2 # initialize spectral PV #self.qh = self.fft2(self.q) # check that it works if check: np.testing.assert_allclose(self.q1, q1) np.test...
def set_q1q2(self, q1, q2, check=False)
Set upper and lower layer PV anomalies. Parameters ---------- q1 : array-like Upper layer PV anomaly in spatial coordinates. q1 : array-like Lower layer PV anomaly in spatial coordinates.
4.096721
4.067869
1.007093
if len(np.shape(U1)) == 0: U1 = U1 * np.ones((self.ny)) if len(np.shape(U2)) == 0: U2 = U2 * np.ones((self.ny)) #self.Ubg = np.array([U1,U2])[:,np.newaxis,np.newaxis] self.U1 = U1 self.U2 = U2 self.Ubg = np.array([U1,U2])
def set_U1U2(self, U1, U2)
Set background zonal flow. Parameters ---------- U1 : number Upper layer flow. Units: m/s U2 : number Lower layer flow. Units: m/s
2.290553
2.365082
0.968488
ens = .5*self.Hi[0] * self.spec_var(self.wv2*self.ph1) + \ .5*self.Hi[1] * self.spec_var(self.wv2*self.ph2) return 2.*pi*np.sqrt( self.H / ens ) / 86400
def _calc_eddy_time(self)
estimate the eddy turn-over time in days
7.57753
6.671824
1.135751
self.add_diagnostic('entspec', description='barotropic enstrophy spectrum', function= (lambda self: np.abs(self.del1*self.qh[0] + self.del2*self.qh[1])**2.) ) self.add_diagnostic('APEflux', description='spectral flux of availab...
def _initialize_model_diagnostics(self)
Extra diagnostics for two-layer model
2.873313
2.846292
1.009493
# The bt model is diagonal. The inversion is simply qh = -kappa**2 ph self.a = -(self.wv2i+self.kd2)[np.newaxis, np.newaxis, :, :]
def _initialize_inversion_matrix(self)
the inversion
32.207237
30.520565
1.055263
ens = .5*self.H * self.spec_var(self.wv2*self.ph) return 2.*pi*np.sqrt( self.H / ens ) / year
def _calc_eddy_time(self)
estimate the eddy turn-over time in days
28.029192
23.22216
1.207002
assert len(x) == self.N assert len(y) == self.N u = np.zeros(self.N, self.x.dtype) v = np.zeros(self.N, self.y.dtype) for n in xrange(self.N): # don't include self interaction if prev: x0 = self.xprev[np.r_[:n,n+1:self.N]] ...
def calc_uv(self, x, y, prev=False)
Calculate velocity at x and y points due to vortex velocity field. Assumes x and y are vortex positions and are ordered the same as x0 and y0. The ordering is used to neglect to vortex self interaction.
1.929928
1.855914
1.03988
dx, dy = self.distance(x0, y0, x, y) #print 'dx, dy:', dx, dy rr2 = (dx**2 + dy**2)**-1 u = - s0 * dy * r_twopi * rr2 v = s0 * dx * r_twopi * rr2 #print 'u, v', u, v return u, v
def uv_at_xy(self, x, y, x0, y0, s0)
Returns two arrays of u, v
3.48944
3.572896
0.976642
if len(args) < 2: return args args.sort() ret = [args[0]] for next_i, (s, e) in enumerate(args, start=1): if next_i == len(args): ret[-1] = ret[-1][0], max(ret[-1][1], e) break ns, ne = args[next_i] if e > ns or ret[-1][1] > ns: ret[-1] =...
def reduce(args)
>>> reduce([(2, 4), (4, 9)]) [(2, 4), (4, 9)] >>> reduce([(2, 6), (4, 10)]) [(2, 10)]
2.799748
2.694515
1.039055
r if len(ranges) and isinstance(ranges[0], int_types): ranges = [ranges] iset = self._iset self._maxlen = max(self._maxlen, max(r[1] - r[0] + 1 for r in ranges)) if len(ranges) > 30 or len(iset) < len(ranges): iset.extend(ranges) iset.sort() ...
def add(self, ranges)
r"""Add a single (or many) [start, end, \*] item to the tree.
3.528614
3.491798
1.010543
iset = self._iset l = binsearch_left_start(iset, other[0] - self._maxlen, 0, len(iset)) r = binsearch_right_end(iset, other[1], 0, len(iset)) iopts = iset[l:r] iiter = (s for s in iopts if s[0] <= other[1] and s[1] >= other[0]) for o in iiter: yield o
def find(self, other)
Return an interable of elements that overlap other in the tree.
4.049693
3.684032
1.099255
global zhcdicts if zhcdicts: return if filename == _DEFAULT_DICT: zhcdicts = json.loads(get_module_res(filename).read().decode('utf-8')) else: with open(filename, 'rb') as f: zhcdicts = json.loads(f.read().decode('utf-8')) zhcdicts['SIMPONLY'] = frozenset(zhc...
def loaddict(filename=DICTIONARY)
Load the dictionary from a specific JSON file.
3.733443
3.7405
0.998113
global zhcdicts, dict_zhcn, dict_zhsg, dict_zhtw, dict_zhhk, pfsdict if zhcdicts is None: loaddict(DICTIONARY) if locale == 'zh-cn': if dict_zhcn: got = dict_zhcn else: dict_zhcn = zhcdicts['zh2Hans'].copy() dict_zhcn.update(zhcdicts['zh2CN'])...
def getdict(locale)
Generate or get convertion dict cache for certain locale. Dictionaries are loaded on demand.
1.83765
1.819229
1.010126
if zhcdicts is None: loaddict(DICTIONARY) simp, trad = 0, 0 if full: for ch in s: if ch in zhcdicts['SIMPONLY']: simp += 1 elif ch in zhcdicts['TRADONLY']: trad += 1 if simp > trad: return True elif simp...
def issimp(s, full=False)
Detect text is whether Simplified Chinese or Traditional Chinese. Returns True for Simplified; False for Traditional; None for unknown. If full=False, it returns once first simplified- or traditional-only character is encountered, so it's for quick and rough identification; else, it compares the count a...
3.114169
2.865672
1.086715
rdict = update.copy() if update else {} for r in convtable: if ':uni' in r: if locale in r: rdict[r[':uni']] = r[locale] elif locale[:-1] == 'zh-han': if locale in r: for word in r.values(): rdict[word] = r[locale] ...
def convtable2dict(convtable, locale, update=None)
Convert a list of conversion dict to a dict for a certain locale. >>> sorted(convtable2dict([{'zh-hk': '列斯', 'zh-hans': '利兹', 'zh': '利兹', 'zh-tw': '里茲'}, {':uni': '巨集', 'zh-cn': '宏'}], 'zh-cn').items()) [('列斯', '利兹'), ('利兹', '利兹'), ('巨集', '宏'), ('里茲', '利兹')]
4.192649
3.982085
1.052878
zhdict = getdict(locale) pfset = pfsdict[locale] if update: zhdict = zhdict.copy() zhdict.update(update) newset = set() for word in update: for ch in range(len(word)): newset.add(word[:ch+1]) pfset = pfset | newset ch = [] N = ...
def tokenize(s, locale, update=None)
Tokenize `s` according to corresponding locale dictionary. Don't use this for serious text processing.
2.982745
3.039673
0.981272
if len(sys.argv) == 2 and sys.argv[1] in Locales: locale = sys.argv[1] convertfunc = convert elif len(sys.argv) == 3 and sys.argv[1] == '-w' and sys.argv[2] in Locales: locale = sys.argv[2] convertfunc = convert_for_mw else: thisfile = __file__ if __name__ == '__...
def main()
Simple stdin/stdout interface.
2.60724
2.609729
0.999046
eof = False while not eof: ret, eof, info = manager.list(bucket_name, prefix=prefix, limit=limit, marker=marker) if ret is None: raise QiniuError(info) if not eof: marker = ret['marker'] for item in ret['items']:...
def bucket_lister(manager, bucket_name, prefix=None, marker=None, limit=None)
A generator function for listing keys in a bucket.
3.495265
3.525875
0.991318
config = os.environ.get(name, getattr(settings, name, default)) if config is not None: if isinstance(config, six.string_types): return config.strip() else: return config else: raise ImproperlyConfigured( "Can't find config for '%s' either in e...
def get_qiniu_config(name, default=None)
Get configuration variable from environment variable or django setting.py
3.067578
2.485989
1.233947
if not username: username = utils.mxid2localpart(self.identity) content = { "type": "m.login.application_service", "username": username, } return self._send("POST", "/register", content, api_path=MATRIX_V2_API_PATH)
def register(self, username="")
Performs /register with type: m.login.application_service Args: username(str): Username to register.
5.35987
5.113366
1.048208
if os.path.isdir(filename): logger.error("Err: File '%s' is a directory", filename) return None if not os.path.isfile(filename): logger.error("Err: File '%s' does not exist", filename) return None try: with open(filename, 'r') as sourcefile: songs = ...
def load_from_file(filename)
Load a list of filenames from an external text file.
2.954865
2.814244
1.049967
parser = argparse.ArgumentParser(description='Find lyrics for a set of mp3' ' files and embed them as metadata') parser.add_argument('-j', '--jobs', help='Number of parallel processes', type=int, metavar='N', default=1) parser.add_argument('-...
def parse_argv()
Parse command line arguments. Settings will be stored in the global variables declared above.
2.739112
2.743435
0.998424
msg = '' try: songs = parse_argv() if not songs: msg = 'No songs specified' except ValueError as error: msg = str(error) if msg: logger.error('%s: Error: %s', sys.argv[0], msg) return 1 logger.debug('Running with %s', songs) try: ...
def main()
Main function.
3.606323
3.531309
1.021243
if sys.version_info.major != 2 and isinstance(slug, bytes): slug = slug.decode('ascii') slug = slug + '==' # base64 padding return uuid.UUID(bytes=base64.urlsafe_b64decode(slug))
def decode(slug)
Returns the uuid.UUID object represented by the given v4 or "nice" slug
4.143461
3.844455
1.077776
rawBytes = bytearray(uuid.uuid4().bytes) rawBytes[0] = rawBytes[0] & 0x7f # Ensure slug starts with [A-Za-f] return _convert_bytes_to_slug(rawBytes)
def nice()
Returns a randomly generated uuid v4 compliant slug which conforms to a set of "nice" properties, at the cost of some entropy. Currently this means one extra fixed bit (the first bit of the uuid is set to 0) which guarantees the slug will begin with [A-Za-f]. For example such slugs don't require special ...
6.448881
4.425087
1.457345
assert(normal_mutations.chrom == self.chrom) assert(normal_mutations.pos == self.pos) assert(normal_mutations.ref == self.ref) def passes_normal_criteria(mut): return (mut.count >= maf_count_threshold and mut.maf > maf_min) or \ (mut.count < maf_coun...
def filter_against_normal(self, normal_mutations, maf_min=0.2, maf_count_threshold=20, count_min=1)
Filters mutations that are in the given normal
2.17908
2.184126
0.99769
if self.type == ".": ref = self.ref alt = self.change start = self.pos end = self.pos elif self.type == "-": ref = self.change alt = "-" start = self.pos + 1 end = start + len(self.change) el...
def to_oncotator(self)
Returns mutation in oncotator input format. Assumes mutations have vcf/mpileup style positions.
2.202632
1.92574
1.143785
# Add all the normal matrix API routes if room_handler: room = resources.Room(room_handler, self.Api) self.add_route("/rooms/{room_alias}", room) if transaction_handler: transaction = resources.Transaction(transaction...
def add_handlers(self, room_handler=None, transaction_handler=None, user_handler=None)
Adds routes to Application that use specified handlers.
2.836207
2.89176
0.980789
path = path or [] conflict = _Conflict(conflict) for key in right: if key in left: if isinstance(left[key], Mapping) and isinstance(right[key], Mapping): # recurse, merge left and right dict values, update path for current 'step' _merge(left[key], ri...
def _merge(left, right, path=None, conflict=_Conflict.error)
Merges values in place from *right* into *left*. :param left: mapping to merge into :param right: mapping to merge from :param path: `list` of keys processed before (used for error reporting only, should only need to be provided by recursive calls) :param conflict: action to be taken on merge c...
3.983952
4.126365
0.965487
result = {} for key, value in mapping.items(): if isinstance(value, Mapping): # recursively split key(s) in value value = _split_keys(value, separator) # reject non-str keys, avoid complicating access patterns if not isinstance(key, str): raise ...
def _split_keys(mapping, separator='.', colliding=None)
Recursively walks *mapping* to split keys that contain the separator into nested mappings. .. note:: Keys not of type `str` are not supported and will raise errors. :param mapping: the mapping to process :param separator: the character (sequence) to use as the separator between keys ...
5.02283
4.985247
1.007539
message = '{} => {}'.format(name, value) log_mon.info({'metric_name': name, 'value': value, 'message': message, **kwargs})
def log_mon_value(name, value=1, **kwargs)
simplest monitoring function to be aggregated with sum
4.780349
4.998107
0.956432
new_storage = _proxy('store') _state.store = type('store', (object,), {}) new_storage.store = dict() return new_storage.store
def create_store()
A helper for setting the _proxy and slapping the store object for us. :return: A thread-local storage as a dictionary
11.454544
10.252982
1.117191
def validated_form(request, **kwargs): # import ipdb; ipdb.set_trace() data = request.query_params.dict() if request.method in ['GET'] else request.data if isinstance(data, QueryDict): form = form_class(data={**data.dict(), **kwargs}) elif isinstance(data, dict): ...
def use_form(form_class, request=None, **top_kwargs)
Validate request (query_params or request body with args from url) with serializer and pass validated data dict to the view function instead of request object.
2.276278
2.197919
1.035651
if request_callback is None: return lambda fn: request(fn, **kwargs) else: return Request(request_callback, **kwargs).decorate_module(request_callback)
def request(request_callback=None, **kwargs)
Chisel request decorator
5.03033
4.058857
1.239346
if client.pool_id in self._client_ids: log.info("%r is already in the penalty box. Ignoring.", client) return release = time.time() + self._min_wait heapq.heappush(self._clients, (release, (client, self._min_wait))) self._client_ids.add(client.pool_id)
def add(self, client)
Add a client to the penalty box.
5.032525
3.801935
1.323675
now = time.time() while self._clients and self._clients[0][0] < now: _, (client, last_wait) = heapq.heappop(self._clients) connect_start = time.time() try: client.echo("test") # reconnected if this succeeds. self._client_ids.r...
def get(self)
Get any clients ready to be used. :returns: Iterable of redis clients
4.292105
4.064026
1.056121
if is_callable(_object): _validator = _object @wraps(_validator) def decorated(value): ensure(isinstance(value, basestring), "not of type string") return _validator(value) return decorated ensure(isinstance(_object, basestring), "not of type string")
def string(_object)
Validates a given input is of type string. Example usage:: data = {'a' : 21} schema = (string, 21) You can also use this as a decorator, as a way to check for the input before it even hits a validator you may be writing. .. note:: If the argument is a callable, the decorating...
3.955105
4.040952
0.978756
if is_callable(_object): _validator = _object @wraps(_validator) def decorated(value): ensure(isinstance(value, bool), "not of type boolean") return _validator(value) return decorated ensure(isinstance(_object, bool), "not of type boolean")
def boolean(_object)
Validates a given input is of type boolean. Example usage:: data = {'a' : True} schema = ('a', boolean) You can also use this as a decorator, as a way to check for the input before it even hits a validator you may be writing. .. note:: If the argument is a callable, the decor...
4.069114
4.287477
0.94907
error_msg = 'not of type dictionary' if is_callable(_object): _validator = _object @wraps(_validator) def decorated(value): ensure(isinstance(value, dict), error_msg) return _validator(value) return decorated try: ensure(isinstance(_objec...
def dictionary(_object, *args)
Validates a given input is of type dictionary. Example usage:: data = {'a' : {'b': 1}} schema = ('a', dictionary) You can also use this as a decorator, as a way to check for the input before it even hits a validator you may be writing. .. note:: If the argument is a callable,...
5.101219
5.138889
0.99267
if is_callable(_object): _validator = _object @wraps(_validator) def decorated(value): ensure(isinstance(value, list), "not of type array") return _validator(value) return decorated ensure(isinstance(_object, list), "not of type array")
def array(_object)
Validates a given input is of type list. Example usage:: data = {'a' : [1,2]} schema = ('a', array) You can also use this as a decorator, as a way to check for the input before it even hits a validator you may be writing. .. note:: If the argument is a callable, the decoratin...
4.227934
4.372569
0.966922
if is_callable(_object): _validator = _object @wraps(_validator) def decorated(value): ensure(isinstance(value, int), "not of type int") return _validator(value) return decorated ensure(isinstance(_object, int), "not of type int")
def integer(_object)
Validates a given input is of type int.. Example usage:: data = {'a' : 21} schema = ('a', integer) You can also use this as a decorator, as a way to check for the input before it even hits a validator you may be writing. .. note:: If the argument is a callable, the decorating...
3.78668
4.100312
0.92351
'''Returns a constant `value` TensorFluent with given `dtype`. Args: value: The constant value. dtype: The output's data type. Returns: A constant TensorFluent. ''' t = tf.constant(value, dtype=dtype) scope = [] # type: List b...
def constant(cls, value: Value, dtype: tf.DType = tf.float32) -> 'TensorFluent'
Returns a constant `value` TensorFluent with given `dtype`. Args: value: The constant value. dtype: The output's data type. Returns: A constant TensorFluent.
4.592299
3.24715
1.414255
'''Returns a TensorFluent for the Bernoulli sampling op with given mean parameter. Args: mean: The mean parameter of the Bernoulli distribution. batch_size: The size of the batch (optional). Returns: The Bernoulli distribution and a TensorFluent sample drawn...
def Bernoulli(cls, mean: 'TensorFluent', batch_size: Optional[int] = None) -> Tuple[Distribution, 'TensorFluent']
Returns a TensorFluent for the Bernoulli sampling op with given mean parameter. Args: mean: The mean parameter of the Bernoulli distribution. batch_size: The size of the batch (optional). Returns: The Bernoulli distribution and a TensorFluent sample drawn from the d...
3.9502
2.533561
1.559149
'''Returns a TensorFluent for the Uniform sampling op with given low and high parameters. Args: low: The low parameter of the Uniform distribution. high: The high parameter of the Uniform distribution. batch_size: The size of the batch (optional). Returns: ...
def Uniform(cls, low: 'TensorFluent', high: 'TensorFluent', batch_size: Optional[int] = None) -> Tuple[Distribution, 'TensorFluent']
Returns a TensorFluent for the Uniform sampling op with given low and high parameters. Args: low: The low parameter of the Uniform distribution. high: The high parameter of the Uniform distribution. batch_size: The size of the batch (optional). Returns: ...
3.638813
2.183635
1.666402
'''Returns a TensorFluent for the Normal sampling op with given mean and variance. Args: mean: The mean parameter of the Normal distribution. variance: The variance parameter of the Normal distribution. batch_size: The size of the batch (optional). Returns: ...
def Normal(cls, mean: 'TensorFluent', variance: 'TensorFluent', batch_size: Optional[int] = None) -> Tuple[Distribution, 'TensorFluent']
Returns a TensorFluent for the Normal sampling op with given mean and variance. Args: mean: The mean parameter of the Normal distribution. variance: The variance parameter of the Normal distribution. batch_size: The size of the batch (optional). Returns: ...
3.519739
2.211803
1.591344
'''Returns a TensorFluent for the Gamma sampling op with given shape and scale parameters. Args: shape: The shape parameter of the Gamma distribution. scale: The scale parameter of the Gamma distribution. batch_size: The size of the batch (optional). Returns...
def Gamma(cls, shape: 'TensorFluent', scale: 'TensorFluent', batch_size: Optional[int] = None) -> Tuple[Distribution, 'TensorFluent']
Returns a TensorFluent for the Gamma sampling op with given shape and scale parameters. Args: shape: The shape parameter of the Gamma distribution. scale: The scale parameter of the Gamma distribution. batch_size: The size of the batch (optional). Returns: ...
3.802129
2.378613
1.598465
'''Returns a TensorFluent for the Exponential sampling op with given mean parameter. Args: mean: The mean parameter of the Exponential distribution. batch_size: The size of the batch (optional). Returns: The Exponential distribution and a TensorFluent sample...
def Exponential(cls, mean: 'TensorFluent', batch_size: Optional[int] = None) -> Tuple[Distribution, 'TensorFluent']
Returns a TensorFluent for the Exponential sampling op with given mean parameter. Args: mean: The mean parameter of the Exponential distribution. batch_size: The size of the batch (optional). Returns: The Exponential distribution and a TensorFluent sample drawn from...
4.418092
2.784234
1.586825
'''Returns a copy of the input fluent with stop_gradient at tensor level. Args: x: The input fluent. Returns: A TensorFluent that stops backpropagation of gradient computations. ''' scope = x.scope.as_list() batch = x.batch return TensorF...
def stop_gradient(cls, x: 'TensorFluent') -> 'TensorFluent'
Returns a copy of the input fluent with stop_gradient at tensor level. Args: x: The input fluent. Returns: A TensorFluent that stops backpropagation of gradient computations.
6.43231
2.86784
2.242911
'''Returns a copy of the inputs fluent with stop_gradient applied at batch level. Args: x: The input fluent. stop_batch: A boolean tf.Tensor with shape=(batch_size, ...) Returns: A TensorFluent that conditionally stops backpropagation of gradient computation...
def stop_batch_gradient(cls, x: 'TensorFluent', stop_batch: tf.Tensor) -> 'TensorFluent'
Returns a copy of the inputs fluent with stop_gradient applied at batch level. Args: x: The input fluent. stop_batch: A boolean tf.Tensor with shape=(batch_size, ...) Returns: A TensorFluent that conditionally stops backpropagation of gradient computations.
5.118162
2.236323
2.28865
'''Returns a TensorFluent for the abs function. Args: x: The input fluent. Returns: A TensorFluent wrapping the abs function. ''' return cls._unary_op(x, tf.abs, tf.float32)
def abs(cls, x: 'TensorFluent') -> 'TensorFluent'
Returns a TensorFluent for the abs function. Args: x: The input fluent. Returns: A TensorFluent wrapping the abs function.
4.739336
2.877649
1.646947