repo
stringlengths
1
29
path
stringlengths
24
332
code
stringlengths
39
579k
niftynet
niftynet//utilities/versioneer_version.pyfile:/utilities/versioneer_version.py:function:get_keywords/get_keywords
def get_keywords(): """Get the keywords needed to look up the version information.""" git_refnames = '$Format:%d$' git_full = '$Format:%H$' git_date = '$Format:%ci$' keywords = {'refnames': git_refnames, 'full': git_full, 'date': git_date} return keywords
fpi-0.1.1
fpi-0.1.1//fpi/drag.pyfile:/fpi/drag.py:function:Mikhailov_Freire/Mikhailov_Freire
def Mikhailov_Freire(Re): """Calculates drag coefficient of a smooth sphere using the method in [1]_ as described in [2]_. .. math:: C_D = \\frac{3808[(1617933/2030) + (178861/1063)Re + (1219/1084)Re^2]} {681Re[(77531/422) + (13529/976)Re - (1/71154)Re^2]} Parameters ---------- Re : float Reynolds number of the sphere, [-] Returns ------- Cd : float Drag coefficient [-] Notes ----- Range is Re <= 118300 Examples -------- >>> Mikhailov_Freire(200.) 0.7514111388018659 References ---------- .. [1] Mikhailov, M. D., and A. P. Silva Freire. "The Drag Coefficient of a Sphere: An Approximation Using Shanks Transform." Powder Technology 237 (March 2013): 432-35. doi:10.1016/j.powtec.2012.12.033. .. [2] Barati, Reza, Seyed Ali Akbar Salehi Neyshabouri, and Goodarz Ahmadi. "Development of Empirical Models with High Accuracy for Estimation of Drag Coefficient of Flow around a Smooth Sphere: An Evolutionary Approach." Powder Technology 257 (May 2014): 11-19. doi:10.1016/j.powtec.2014.02.045. """ Cd = 3808.0 * (1617933.0 / 2030.0 + 178861.0 / 1063.0 * Re + 1219.0 / 1084.0 * Re ** 2) / (681.0 * Re * (77531.0 / 422.0 + 13529.0 / 976.0 * Re - 1.0 / 71154.0 * Re ** 2)) return Cd
agraph-python-101.0.3
agraph-python-101.0.3//src/franz/openrdf/util/http.pyfile:/src/franz/openrdf/util/http.py:function:normalize_headers/normalize_headers
def normalize_headers(headers): """ Create a dictionary of headers from: * A list of curl-style headers * None * a dictionary (return a *copy*). :param headers: List or dict of header (may also be None). :type headers: Iterable[string] | dict[string, string] | None :return: A dictionary of headers suitable for requests. :rtype: dict[string,string] """ if headers is None: return {} elif isinstance(headers, dict): return headers.copy() else: result = {} for line in headers: key, sep, value = line.partition(':') if sep is None: raise Exception('Internal error - invalid header line (%s)' % line) result[key.strip().lower()] = value.strip() return result
gridmap-0.14.0
gridmap-0.14.0//gridmap/job.pyfile:/gridmap/job.py:function:_execute/_execute
def _execute(job): """ Cannot pickle method instances, so fake a function. Used by _process_jobs_locally """ job.execute() return job.ret
isbnlib_loc
isbnlib_loc//_loc.pyfile:/_loc.py:function:_clean_publisher/_clean_publisher
def _clean_publisher(publisher): """Clean the Publisher field of some unnecessary annotations.""" if ':' in publisher: publisher = publisher.split(':')[1] publisher = publisher.replace(' ; ', '; ').replace('/', '') return publisher.strip(':.,; ')
attrdict
attrdict//mixins.pyclass:Attr/_constructor
@classmethod def _constructor(cls, mapping, configuration): """ A standardized constructor used internally by Attr. mapping: A mapping of key-value pairs. It is HIGHLY recommended that you use this as the internal key-value pair mapping, as that will allow nested assignment (e.g., attr.foo.bar = baz) configuration: The return value of Attr._configuration """ raise NotImplementedError('You need to implement this')
pydruid-0.5.9
pydruid-0.5.9//env/lib/python3.7/copyreg.pyfile:/env/lib/python3.7/copyreg.py:function:__newobj_ex__/__newobj_ex__
def __newobj_ex__(cls, args, kwargs): """Used by pickle protocol 4, instead of __newobj__ to allow classes with keyword-only arguments to be pickled correctly. """ return cls.__new__(cls, *args, **kwargs)
progress-reporter-2.0
progress-reporter-2.0//versioneer.pyfile:/versioneer.py:function:plus_or_dot/plus_or_dot
def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if '+' in pieces.get('closest-tag', ''): return '.' return '+'
telegram_click-3.3.4
telegram_click-3.3.4//telegram_click/util.pyfile:/telegram_click/util.py:function:escape_for_markdown/escape_for_markdown
def escape_for_markdown(text: (str or None)) ->str: """ Escapes text to use as plain text in a markdown document :param text: the original text :return: the escaped text """ text = str(text) escaped = text.replace('*', '\\*').replace('_', '\\_') return escaped
GSAS-II-WONDER_osx-1.0.4
GSAS-II-WONDER_osx-1.0.4//GSAS-II-WONDER/GSASIIElem.pyfile:/GSAS-II-WONDER/GSASIIElem.py:function:GetFFC5/GetFFC5
def GetFFC5(ElSym): """Get 5 term form factor and Compton scattering data :param ElSym: str(1-2 character element symbol with proper case); :return El: dictionary with 5 term form factor & compton coefficients """ import FormFactors as FF El = {} FF5 = FF.FFac5term[ElSym] El['fa'] = FF5[:5] El['fc'] = FF5[5] El['fb'] = FF5[6:] Cmp5 = FF.Compton[ElSym] El['cmpz'] = Cmp5[0] El['cmpa'] = Cmp5[1:6] El['cmpb'] = Cmp5[6:] return El
qtile-plasma-1.5.5
qtile-plasma-1.5.5//plasma/enum.pyfile:/plasma/enum.py:function:_is_descriptor/_is_descriptor
def _is_descriptor(obj): """Returns True if obj is a descriptor, False otherwise.""" return hasattr(obj, '__get__') or hasattr(obj, '__set__') or hasattr(obj, '__delete__')
cve-bin-tool-1.0
cve-bin-tool-1.0//cve_bin_tool/checkers/systemd.pyfile:/cve_bin_tool/checkers/systemd.py:function:guess_contains_systemd/guess_contains_systemd
def guess_contains_systemd(lines): """Tries to determine if a file includes systemd """ for line in lines: if 'sd_bus_error_copy' in line: return 1 if 'sd_bus_error_is_set' in line: return 1 if 'sd_bus_error_add_map' in line: return 1 return 0
CDS-1.0.1
CDS-1.0.1//cds/modules/migrator/utils.pyfile:/cds/modules/migrator/utils.py:function:update_access/update_access
def update_access(data, *access): """Merge access rights information. :params data: current JSON structure with metadata and potentially an `_access` key. :param *access: List of dictionaries to merge to the original data, each of them in the form `action: []`. """ current_rules = data.get('_access', {}) for a in access: for k, v in a.items(): current_x_rules = set(current_rules.get(k, [])) current_x_rules.update(v) current_rules[k] = list(current_x_rules) data['_access'] = current_rules
pymoca-0.7.0
pymoca-0.7.0//src/pymoca/backends/casadi/_options.pyfile:/src/pymoca/backends/casadi/_options.py:function:_get_default_options/_get_default_options
def _get_default_options(): """ Returns a dictionary with the available compiler options and the default values Returns: default_options (Dict) """ return {'library_folders': [], 'verbose': False, 'check_balanced': True, 'mtime_check': True, 'cache': False, 'codegen': False, 'expand_mx': False, 'unroll_loops': True, 'inline_functions': True, 'expand_vectors': False, 'replace_parameter_expressions': False, 'replace_constant_expressions': False, 'eliminate_constant_assignments': False, 'replace_parameter_values': False, 'replace_constant_values': False, 'eliminable_variable_expression': None, 'factor_and_simplify_equations': False, 'detect_aliases': False, 'reduce_affine_expression': False}
wcf
wcf//records/text.pyclass:UniqueIdTextRecord/parse
@classmethod def parse(cls, fp): """ >>> from io import BytesIO >>> fp = BytesIO(b'\\x00\\x11"3DUfw\\x88\\x99\\xaa\\xbb\\xcc\\xdd\\xee\\xff') >>> str(UniqueIdTextRecord.parse(fp)) 'urn:uuid:33221100-5544-7766-8899-aabbccddeeff' """ u = fp.read(16) return cls(bytes_le=u)
statsmodels
statsmodels//graphics/boxplots.pyfile:/graphics/boxplots.py:function:_show_legend/_show_legend
def _show_legend(ax): """Utility function to show legend.""" leg = ax.legend(loc=1, shadow=True, fancybox=True, labelspacing=0.2, borderpad=0.15) ltext = leg.get_texts() llines = leg.get_lines() frame = leg.get_frame() from matplotlib.artist import setp setp(ltext, fontsize='small') setp(llines, linewidth=1)
interkamen_career-1.18.9
interkamen_career-1.18.9//interkamen_career/modules/support_modules/standart_functions.pyclass:BasicFunctionsS/count_unzero_items
@staticmethod def count_unzero_items(items_list): """Count nonzero items in list.""" counter = 0 for item in items_list: if items_list[item] != 0: counter += 1 return counter
pmix-0.6.2
pmix-0.6.2//pmix/utils.pyfile:/pmix/utils.py:function:newline_space_fix/newline_space_fix
def newline_space_fix(text): """Replace "newline-space" with "newline". This function was particularly useful when converting between Google Sheets and .xlsx format. Args: text (str): The string to work with Returns: The text with the appropriate fix. """ newline_space = '\n ' fix = '\n' while newline_space in text: text = text.replace(newline_space, fix) return text
pypago
pypago//toolsec.pyfile:/toolsec.py:function:distance/distance
def distance(lat1, lon1, lat2, lon2, geoid): """ Computes the distance between the points (lon1, lat1) and (lon2, lat2). This function used the :py:func:`mpl_toolkits.basemap.pyproj.Geod.inv` function. :param float lat1: latitude of the first point :param float lon1: longitude of the first point :param float lat2: latitude of the second point :param float lon2: longitude of the second point :param mpl_toolkits.basemap.pyproj.Geod geoid: :py:class:`mpl_toolkits.basemap.pyproj.Geod` object used to compute the distance :return: distance between the two points :rtype: float """ output = geoid.inv(lon1, lat1, lon2, lat2) return output[-1]
bitcoin_tools
bitcoin_tools//utils.pyfile:/utils.py:function:change_endianness/change_endianness
def change_endianness(x): """ Changes the endianness (from BE to LE and vice versa) of a given value. :param x: Given value which endianness will be changed. :type x: hex str :return: The opposite endianness representation of the given value. :rtype: hex str """ if len(x) % 2 == 1: x += '0' y = x.decode('hex') z = y[::-1] return z.encode('hex')
fake-blender-api-2.79-0.3.1
fake-blender-api-2.79-0.3.1//bpy/ops/paintcurve.pyfile:/bpy/ops/paintcurve.py:function:slide/slide
def slide(align: bool=False, select: bool=True): """Select and slide paint curve point :param align: Align Handles, Aligns opposite point handle during transform :type align: bool :param select: Select, Attempt to select a point handle before transform :type select: bool """ pass
aea-0.3.2.post1
aea-0.3.2.post1//aea/helpers/exec_timeout.pyclass:ExecTimeoutThreadGuard/stop
@classmethod def stop(cls, force: bool=False) ->None: """ Stop supervisor thread. Actual stop performed on force == True or if number of stops == number of starts :param force: force stop regardless number of start. :return: None """ with cls._lock: if not cls._supervisor_thread: return cls._start_count -= 1 if cls._start_count <= 0 or force: cls._loop.call_soon_threadsafe(cls._stopped_future.set_result, True ) cls._supervisor_thread.join() cls._supervisor_thread = None
threeML-1.1.0
threeML-1.1.0//versioneer.pyfile:/versioneer.py:function:render_pep440_old/render_pep440_old
def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces['closest-tag']: rendered = pieces['closest-tag'] if pieces['distance'] or pieces['dirty']: rendered += '.post%d' % pieces['distance'] if pieces['dirty']: rendered += '.dev0' else: rendered = '0.post%d' % pieces['distance'] if pieces['dirty']: rendered += '.dev0' return rendered
maildaemon
maildaemon//config.pyfile:/config.py:function:validate_config/validate_config
def validate_config(config: dict): """Validate the maildaemon configuration.""" for name, connection in config.get('connections', {}).items(): assert isinstance(name, str), type(name) assert name, name assert 'protocol' in connection, connection assert isinstance(connection['protocol'], str), type(connection[ 'protocol']) assert connection['protocol'], connection assert 'domain' in connection, connection assert isinstance(connection['domain'], str), type(connection['domain'] ) assert connection['domain'], connection assert isinstance(connection.get('ssl', False), bool), type(connection ['ssl']) assert isinstance(connection.get('port', 1), int), type(connection[ 'port']) assert connection.get('port', 1) > 0, connection['port'] assert isinstance(connection.get('login', 'test'), str), type( connection['login']) assert connection.get('login', 'test'), connection['login'] assert isinstance(connection.get('password', 'test'), str), type( connection['password']) assert connection.get('password', 'test'), connection['password'] for name, filter_ in config.get('filters', {}).items(): for connection_name in filter_.get('connections', []): assert connection_name in config['connections'] assert 'condition' in filter_, filter_ assert isinstance(filter_['condition'], str), type(filter_['condition'] ) for action in filter_.get('actions', []): assert isinstance(action, str), type(action)
Treadmill-0.0.2
Treadmill-0.0.2//treadmill/sysinfo.pyfile:/treadmill/sysinfo.py:function:_total_bogomips_windows/_total_bogomips_windows
def _total_bogomips_windows(): """Return sum of bogomips value for all CPUs.""" return 5000
PSyclone-1.8.1
PSyclone-1.8.1//src/psyclone/psyir/backend/fortran.pyfile:/src/psyclone/psyir/backend/fortran.py:function:_reverse_map/_reverse_map
def _reverse_map(op_map): """ Reverses the supplied fortran2psyir mapping to make a psyir2fortran mapping. :param op_map: mapping from string representation of operator to enumerated type. :type op_map: :py:class:`collections.OrderedDict` :returns: a mapping from PSyIR operation to the equivalent Fortran string. :rtype: dict with :py:class:`psyclone.psyGen.Operation.Operator` keys and str values. """ mapping = {} for operator in op_map: mapping_key = op_map[operator] mapping_value = operator if mapping_key not in mapping: mapping[mapping_key] = mapping_value return mapping
pyade
pyade//ilshade.pyfile:/ilshade.py:function:get_default_params/get_default_params
def get_default_params(dim: int): """ Returns the default parameters of the iL-SHADE Differential Evolution Algorithm :param dim: Size of the problem (or individual). :type dim: int :return: Dict with the default parameters of the iL-SHADE Differential Evolution Algorithm. :rtype dict """ return {'population_size': 12 * dim, 'individual_size': dim, 'memory_size': 6, 'max_evals': 10000 * dim, 'callback': None, 'seed': None, 'opts': None}
wallthick
wallthick//pd8010.pyfile:/pd8010.py:function:req_thickness/req_thickness
def req_thickness(t_min, t_corr, f_tol): """ Number [m], Number [m], Number [-] -> Number [m] Returns the required wall thickness based on the following mechanical allowances: - Corrosion allowance - Fabrication tolerance Exrapolated from Equation (4) """ try: return (t_min + t_corr) / (1 - f_tol) except ZeroDivisionError: raise ZeroDivisionError('Divide by zero. Check fabrication tolerance.')
cloudant
cloudant//client.pyclass:Cloudant/iam
@classmethod def iam(cls, account_name, api_key, **kwargs): """ Create a Cloudant client that uses IAM authentication. :param account_name: Cloudant account name. :param api_key: IAM authentication API key. """ return cls(None, api_key, account=account_name, auto_renew=kwargs.get( 'auto_renew', True), use_iam=True, **kwargs)
crypt
crypt//key.pyfile:/key.py:function:SessionKeyType/SessionKeyType
def SessionKeyType(): """ Which crypto is used for session key. """ return 'AES'
manage.py-0.2.10
manage.py-0.2.10//manager/cli.pyfile:/manager/cli.py:function:tsplit/tsplit
def tsplit(string, delimiters): """Behaves str.split but supports tuples of delimiters.""" delimiters = tuple(delimiters) stack = [string] for delimiter in delimiters: for i, substring in enumerate(stack): substack = substring.split(delimiter) stack.pop(i) for j, _substring in enumerate(substack): stack.insert(i + j, _substring) return stack
trytond
trytond//modules/nereid_cms/cms.pyclass:Article/get_publish_date
@classmethod def get_publish_date(cls, records, name): """ Return publish date to render on view """ res = {} for record in records: res[record.id] = str(record.published_on) return res
dorthrithil-networkx-1.11
dorthrithil-networkx-1.11//networkx/algorithms/assortativity/pairs.pyfile:/networkx/algorithms/assortativity/pairs.py:function:node_attribute_xy/node_attribute_xy
def node_attribute_xy(G, attribute, nodes=None): """Return iterator of node-attribute pairs for all edges in G. Parameters ---------- G: NetworkX graph attribute: key The node attribute key. nodes: list or iterable (optional) Use only edges that are adjacency to specified nodes. The default is all nodes. Returns ------- (x,y): 2-tuple Generates 2-tuple of (attribute,attribute) values. Examples -------- >>> G = nx.DiGraph() >>> G.add_node(1,color='red') >>> G.add_node(2,color='blue') >>> G.add_edge(1,2) >>> list(nx.node_attribute_xy(G,'color')) [('red', 'blue')] Notes ----- For undirected graphs each edge is produced twice, once for each edge representation (u,v) and (v,u), with the exception of self-loop edges which only appear once. """ if nodes is None: nodes = set(G) else: nodes = set(nodes) node = G.node for u, nbrsdict in G.adjacency_iter(): if u not in nodes: continue uattr = node[u].get(attribute, None) if G.is_multigraph(): for v, keys in nbrsdict.items(): vattr = node[v].get(attribute, None) for k, d in keys.items(): yield uattr, vattr else: for v, eattr in nbrsdict.items(): vattr = node[v].get(attribute, None) yield uattr, vattr
uio-0.1.0.6
uio-0.1.0.6//uio/uio.pyfile:/uio/uio.py:function:parse_adl_path/parse_adl_path
def parse_adl_path(adl_path): """ Returns tuple (store_name, object_key) """ path_parts = adl_path.replace('adl://', '').split('/') store_name = path_parts[0].replace('.azuredatalakestore.net', '') object_key = '/'.join(path_parts[1:]) return store_name, object_key
genemethods-0.0.0.16
genemethods-0.0.0.16//genemethods/assemblypipeline/skesa.pyclass:Skesa/reads
@staticmethod def reads(err_log): """ Parse the outputs from bbmerge to extract the total number of reads, as well as the number of reads that could be paired :param err_log: bbmerge outputs the stats in the error file :return: num_reads, the total number of reads, paired_reads, number of paired readds """ num_reads = 0 paired_reads = 0 with open(err_log, 'r') as error_log: for line in error_log: if 'Pairs:' in line: num_reads = line.split('\t')[-1].rstrip() elif 'Joined:' in line: paired_reads = line.split('\t')[-2].rstrip() return num_reads, paired_reads
pyboto3-1.4.4
pyboto3-1.4.4//pyboto3/dynamodb.pyfile:/pyboto3/dynamodb.py:function:list_tables/list_tables
def list_tables(ExclusiveStartTableName=None, Limit=None): """ Returns an array of table names associated with the current account and endpoint. The output from ListTables is paginated, with each page returning a maximum of 100 table names. See also: AWS API Documentation Examples This example lists all of the tables associated with the current AWS account and endpoint. Expected Output: :example: response = client.list_tables( ExclusiveStartTableName='string', Limit=123 ) :type ExclusiveStartTableName: string :param ExclusiveStartTableName: The first table name that this operation will evaluate. Use the value that was returned for LastEvaluatedTableName in a previous operation, so that you can obtain the next page of results. :type Limit: integer :param Limit: A maximum number of table names to return. If this parameter is not specified, the limit is 100. :rtype: dict :return: { 'TableNames': [ 'string', ], 'LastEvaluatedTableName': 'string' } :returns: (string) -- """ pass
asr_evaluation-2.0.4
asr_evaluation-2.0.4//asr_evaluation/asr_evaluation.pyfile:/asr_evaluation/asr_evaluation.py:function:remove_tail_id/remove_tail_id
def remove_tail_id(ref, hyp): """Assumes that the ID is the final token of the string which is common in Sphinx but not in Kaldi.""" ref_id = ref[-1] hyp_id = hyp[-1] if ref_id != hyp_id: print( """Reference and hypothesis IDs do not match! ref="{}" hyp="{}" File lines in hyp file should match those in the ref file.""" .format(ref_id, hyp_id)) exit(-1) ref = ref[:-1] hyp = hyp[:-1] return ref, hyp
fake-bpy-module-2.78-20200428
fake-bpy-module-2.78-20200428//bpy/ops/marker.pyfile:/bpy/ops/marker.py:function:select_border/select_border
def select_border(gesture_mode: int=0, xmin: int=0, xmax: int=0, ymin: int= 0, ymax: int=0, extend: bool=True): """Select all time markers using border selection :param gesture_mode: Gesture Mode :type gesture_mode: int :param xmin: X Min :type xmin: int :param xmax: X Max :type xmax: int :param ymin: Y Min :type ymin: int :param ymax: Y Max :type ymax: int :param extend: Extend, Extend selection instead of deselecting everything first :type extend: bool """ pass
dropbox-10.1.2
dropbox-10.1.2//dropbox/team_log.pyclass:EventType/emm_refresh_auth_token
@classmethod def emm_refresh_auth_token(cls, val): """ Create an instance of this class set to the ``emm_refresh_auth_token`` tag with value ``val``. :param EmmRefreshAuthTokenType val: :rtype: EventType """ return cls('emm_refresh_auth_token', val)
spike_py-0.99.17
spike_py-0.99.17//spike/File/Apex.pyfile:/spike/File/Apex.py:function:read_param/read_param
def read_param(filename): """ Open the given file and retrieve all parameters written initially for apexAcquisition.method NC is written when no value for value is found structure : <param><name>C_MsmsE</name><value>0.0</value></param> read_param returns values in a dictionnary """ from xml.dom import minidom xmldoc = minidom.parse(filename) x = xmldoc.documentElement pp = {} children = x.childNodes for child in children: if child.nodeName == 'paramlist': params = child.childNodes for param in params: if param.nodeName == 'param': if 'name' in param.attributes.keys(): k = param.attributes['name'].value for element in param.childNodes: if element.nodeName == 'name': k = element.firstChild.toxml() elif element.nodeName == 'value': try: v = element.firstChild.toxml() except: v = 'NC' pp[k] = v return pp
pywwt-0.8.0
pywwt-0.8.0//setupbase.pyfile:/setupbase.py:function:update_package_data/update_package_data
def update_package_data(distribution): """update build_py options to get package_data changes""" build_py = distribution.get_command_obj('build_py') build_py.finalize_options()
python-ligo-lw-1.6.0
python-ligo-lw-1.6.0//ligo/lw/dbtables.pyfile:/ligo/lw/dbtables.py:function:idmap_create/idmap_create
def idmap_create(connection): """ Create the _idmap_ table. This table has columns "table_name", "old", and "new" mapping old IDs to new IDs for each table. The (table_name, old) column pair is a primary key (is indexed and must contain unique entries). The table is created as a temporary table, so it will be automatically dropped when the database connection is closed. This function is for internal use, it forms part of the code used to re-map row IDs when merging multiple documents. """ connection.cursor().execute( 'CREATE TEMPORARY TABLE _idmap_ (table_name TEXT NOT NULL, old INTEGER NOT NULL, new INTEGER NOT NULL, PRIMARY KEY (table_name, old))' )
neatbio
neatbio//alignments/alignments.pyfile:/alignments/alignments.py:function:print_matrix/print_matrix
def print_matrix(x, y, A): """Print the matrix with the (0,0) entry in the top left corner. Will label the rows by the sequence and add in the 0-row if appropriate.""" if len(x) == len(A): print('%5s' % ' '), else: print('{} {}'.format(' ', '*')), y = '*' + y for c in x: print('{}'.format(c)), for j in range(len(A[0])): print('{}'.format(y[j])), for i in range(len(A)): print('{}'.format(A[i][j])),
ufl
ufl//finiteelement/elementlist.pyfile:/finiteelement/elementlist.py:function:feec_element/feec_element
def feec_element(family, n, r, k): """Finite element exterior calculus notation n = topological dimension of domain r = polynomial order k = form_degree""" _feec_elements = {'P- Lambda': ((('P', r), ('DP', r - 1)), (('P', r), ( 'RTE', r), ('DP', r - 1)), (('P', r), ('N1E', r), ('N1F', r), ('DP', r - 1))), 'P Lambda': ((('P', r), ('DP', r)), (('P', r), ('BDME', r ), ('DP', r)), (('P', r), ('N2E', r), ('N2F', r), ('DP', r))), 'Q- Lambda': ((('Q', r), ('DQ', r - 1)), (('Q', r), ('RTCE', r), ( 'DQ', r - 1)), (('Q', r), ('NCE', r), ('NCF', r), ('DQ', r - 1))), 'S Lambda': ((('S', r), ('DPC', r)), (('S', r), ('BDMCE', r), ( 'DPC', r)), (('S', r), ('AAE', r), ('AAF', r), ('DPC', r)))} _feec_elements['P-'] = _feec_elements['P- Lambda'] _feec_elements['P'] = _feec_elements['P Lambda'] _feec_elements['Q-'] = _feec_elements['Q- Lambda'] _feec_elements['S'] = _feec_elements['S Lambda'] family, r = _feec_elements[family][n - 1][k] return family, r
ac-electricity-0.4.1
ac-electricity-0.4.1//acelectricity.pyclass:Component/get_reactance
@staticmethod def get_reactance(g, b): """g : conductance (S) b : susceptance (S) return reactance X (ohm) if not infinite""" if g == 0 and b == 0: return None return -b / (g * g + b * b)
taurus-4.6.1
taurus-4.6.1//lib/taurus/qt/qtgui/graphic/jdraw/jdraw_parser.pyfile:/lib/taurus/qt/qtgui/graphic/jdraw/jdraw_parser.py:function:p_parameter/p_parameter
def p_parameter(p): """parameter_list : parameter""" p[0] = p[1]
sonicprobe
sonicprobe//libs/xys.pyfile:/libs/xys.py:function:_maybe_int/_maybe_int
def _maybe_int(s): """Coerces to int if starts with a digit else return s""" if s and s[0] in '0123456789': return int(s) return s
segmentation_pipeline
segmentation_pipeline//impl/deeplab/extract_weigths.pyfile:/impl/deeplab/extract_weigths.py:function:get_mobilenetv2_filename/get_mobilenetv2_filename
def get_mobilenetv2_filename(key): """Rename tensor name to the corresponding Keras layer weight name. # Arguments key: tensor name in TF (determined by tf.variable_scope) """ filename = str(key) filename = filename.replace('/', '_') filename = filename.replace('MobilenetV2_', '') filename = filename.replace('BatchNorm', 'BN') if 'Momentum' in filename: return None filename = filename.replace('_weights', '_kernel') filename = filename.replace('_biases', '_bias') return filename + '.npy'
jukeboxmaya-3.3.2
jukeboxmaya-3.3.2//src/jukeboxmaya/common.pyfile:/src/jukeboxmaya/common.py:function:get_top_namespace/get_top_namespace
def get_top_namespace(node): """Return the top namespace of the given node If the node has not namespace (only root), ":" is returned. Else the top namespace (after root) is returned :param node: the node to query :type node: str :returns: The top level namespace. :rtype: str :raises: None """ name = node.rsplit('|', 1)[-1] name = name.lstrip(':') if ':' not in name: return ':' else: return name.partition(':')[0]
ugc-sentiment-0.0.9
ugc-sentiment-0.0.9//ugc_sentiment/utils/dataHelper.pyfile:/ugc_sentiment/utils/dataHelper.py:function:is_uchar/is_uchar
def is_uchar(uchar): """判断一个unicode是否是汉字""" return True if uchar >= u'一' and uchar <= u'龥' else False
mpeg1audio-0.5.2
mpeg1audio-0.5.2//src/mpeg1audio/headers.pyfile:/src/mpeg1audio/headers.py:function:get_vbr_bitrate/get_vbr_bitrate
def get_vbr_bitrate(mpeg_size, sample_count, sample_rate): """Get average bitrate of VBR file. :param mpeg_size: Size of MPEG in bytes. :type mpeg_size: number :param sample_count: Count of samples. :type sample_count: number :param sample_rate: Sample rate in Hz. :type sample_rate: number :return: Average bitrate in kilobits per second. :rtype: float """ bytes_per_sample = float(mpeg_size) / float(sample_count) bytes_per_second = bytes_per_sample * float(sample_rate) bits_per_second = bytes_per_second * 8 return bits_per_second / 1000
selenium_linux
selenium_linux//webdriver/common/utils.pyfile:/webdriver/common/utils.py:function:join_host_port/join_host_port
def join_host_port(host, port): """Joins a hostname and port together. This is a minimal implementation intended to cope with IPv6 literals. For example, _join_host_port('::1', 80) == '[::1]:80'. :Args: - host - A hostname. - port - An integer port. """ if ':' in host and not host.startswith('['): return '[%s]:%d' % (host, port) return '%s:%d' % (host, port)
ftw.simplelayout-2.5.13
ftw.simplelayout-2.5.13//ftw/simplelayout/interfaces.pyclass:IBlockModifier/modify
def modify(data): """Modifications based on data in the request"""
parsetabtolatex
parsetabtolatex//parsetabtolatex_lex.pyfile:/parsetabtolatex_lex.py:function:t_begin_grammar/t_begin_grammar
def t_begin_grammar(t): """_lr_productions\\ =\\ \\[""" t.lexer.push_state('grammar')
enable-4.8.1
enable-4.8.1//enable/savage/svg/document.pyfile:/enable/savage/svg/document.py:function:fractionalValue/fractionalValue
def fractionalValue(value): """ Parse a string consisting of a float in the range [0..1] or a percentage as a float number in the range [0..1]. """ if value.endswith('%'): return float(value[:-1]) / 100.0 else: return float(value)
d9t.gis-0.4
d9t.gis-0.4//d9t/gis/interfaces.pyclass:IDistanceCalculation/nearest
def nearest(coordinate, coordinate_list, limit): """ returns a list of nearest coordinates from coordinate_list to coordinate including distance. """
tiquations
tiquations//equations.pyfile:/equations.py:function:energy_photon/energy_photon
def energy_photon(frequency, wavelength): """Usage: Calculate the energy of a photon using frequency and wavelength """ equation = 6.62607004e-34 * 300000000.0 / wavelength
enocean-lib-1.0.0
enocean-lib-1.0.0//enocean/utils.pyfile:/enocean/utils.py:function:combine_hex/combine_hex
def combine_hex(data): """ Combine list of integer values to one big integer """ output = 0 for i, value in enumerate(reversed(data)): output |= value << i * 8 return output
pylexibank
pylexibank//util.pyfile:/util.py:function:iter_repl/iter_repl
def iter_repl(seq, subseq, repl): """ Replace sub-list `subseq` in `seq` with `repl`. """ seq, subseq, repl = list(seq), list(subseq), list(repl) subseq_len = len(subseq) rem = seq[:] while rem: if rem[:subseq_len] == subseq: for c in repl: yield c rem = rem[subseq_len:] else: yield rem.pop(0)
redhawk-1.2.3
redhawk-1.2.3//redhawk/utils/util.pyfile:/redhawk/utils/util.py:function:IndexInto/IndexInto
def IndexInto(li, indices): """ Index into a list (or list of lists) using the indices given. If the indices are out of bounds, or are too many in number, return None, instead of throwing an error. 0 is a special case.""" for i in indices: if type(li) != list and i == 0: return li if type(li) != list or i >= len(li): return None li = li[i] return li
fake-bpy-module-2.80-20200428
fake-bpy-module-2.80-20200428//bpy/ops/text.pyfile:/bpy/ops/text.py:function:start_find/start_find
def start_find(): """Start searching text """ pass
collatelogs
collatelogs//util.pyfile:/util.py:function:convert_timezone/convert_timezone
def convert_timezone(dt, tz_from, tz_to): """Convert dt from tz_from to tz_to""" return tz_from.localize(dt).astimezone(tz_to)
sistr
sistr//src/cgmlst/extras/centroid_cgmlst_alleles.pyfile:/src/cgmlst/extras/centroid_cgmlst_alleles.py:function:dm_subset/dm_subset
def dm_subset(dm_sq, idxs): """Get subset of distance matrix given list of indices Args: dm_sq (numpy.array): squareform distance matrix from pdist idxs (list of int): list of indices Returns: numpy.array: subset of `dm_sq` with `shape == (len(idxs), len(idxs))` """ return dm_sq[idxs][:, (idxs)]
stdplus-0.0.47
stdplus-0.0.47//stdplus/_defaultify.pyfile:/stdplus/_defaultify.py:function:defaultify/defaultify
def defaultify(value, default): """Return `default` if `value` is `None`. Otherwise, return `value`""" if None == value: return default else: return value
lowearthorbit
lowearthorbit//upload.pyfile:/upload.py:function:format_path/format_path
def format_path(**kwargs): """Creates a path type string""" objects = [] for key, value in kwargs.items(): objects.append(value) return '/'.join(objects)
graphql-example-0.4.4
graphql-example-0.4.4//vendor/pip/_vendor/distro.pyclass:LinuxDistribution/_parse_lsb_release_content
@staticmethod def _parse_lsb_release_content(lines): """ Parse the output of the lsb_release command. Parameters: * lines: Iterable through the lines of the lsb_release output. Each line must be a unicode string or a UTF-8 encoded byte string. Returns: A dictionary containing all information items. """ props = {} for line in lines: line = line.decode('utf-8') if isinstance(line, bytes) else line kv = line.strip('\n').split(':', 1) if len(kv) != 2: continue k, v = kv props.update({k.replace(' ', '_').lower(): v.strip()}) return props
mesma-1.0.7
mesma-1.0.7//mesma/external/qps/speclib/core.pyfile:/mesma/external/qps/speclib/core.py:function:findTypeFromString/findTypeFromString
def findTypeFromString(value: str): """ Returns a fitting basic python data type of a string value, i.e. :param value: string :return: type out of [str, int or float] """ for t in (int, float, str): try: _ = t(value) except ValueError: continue return t return str
enczipstream-1.1.5
enczipstream-1.1.5//enczipstream/zipencrypt3.pyclass:_ZipDecrypter/_GenerateCRCTable
def _GenerateCRCTable(): """Generate a CRC-32 table. ZIP encryption uses the CRC32 one-byte primitive for scrambling some internal keys. We noticed that a direct implementation is faster than relying on binascii.crc32(). """ poly = 3988292384 table = [0] * 256 for i in range(256): crc = i for j in range(8): if crc & 1: crc = crc >> 1 & 2147483647 ^ poly else: crc = crc >> 1 & 2147483647 table[i] = crc return table
tpdcclib-0.0.16
tpdcclib-0.0.16//tpDccLib/abstract/dcc.pyclass:AbstractDCC/get_progress_bar_class
@staticmethod def get_progress_bar_class(): """ Return class of progress bar :return: class """ from tpDccLib.abstract import progressbar return progressbar.AbstractProgressBar
nglview-2.7.5
nglview-2.7.5//versioneer.pyfile:/versioneer.py:function:scan_setup_py/scan_setup_py
def scan_setup_py(): """Validate the contents of setup.py against Versioneer's expectations.""" found = set() setters = False errors = 0 with open('setup.py', 'r') as f: for line in f.readlines(): if 'import versioneer' in line: found.add('import') if 'versioneer.get_cmdclass()' in line: found.add('cmdclass') if 'versioneer.get_version()' in line: found.add('get_version') if 'versioneer.VCS' in line: setters = True if 'versioneer.versionfile_source' in line: setters = True if len(found) != 3: print('') print('Your setup.py appears to be missing some important items') print('(but I might be wrong). Please make sure it has something') print('roughly like the following:') print('') print(' import versioneer') print(' setup( version=versioneer.get_version(),') print(' cmdclass=versioneer.get_cmdclass(), ...)') print('') errors += 1 if setters: print("You should remove lines like 'versioneer.VCS = ' and") print("'versioneer.versionfile_source = ' . This configuration") print('now lives in setup.cfg, and should be removed from setup.py') print('') errors += 1 return errors
watson-developer-cloud-2.10.1
watson-developer-cloud-2.10.1//examples/conversation_tone_analyzer_integration/tone_detection.pyfile:/examples/conversation_tone_analyzer_integration/tone_detection.py:function:initUser/initUser
def initUser(): """ initUser initializes a user object containing tone data (from the Watson Tone Analyzer) @returns user json object with the emotion, writing and social tones. The current tone identifies the tone for a specific conversation turn, and the history provides the conversation for all tones up to the current tone for a conversation instance with a user. """ return {'user': {'tone': {'emotion': {'current': None}, 'writing': { 'current': None}, 'social': {'current': None}}}}
fake-bpy-module-2.79-20200428
fake-bpy-module-2.79-20200428//bpy/ops/anim.pyfile:/bpy/ops/anim.py:function:keying_set_path_add/keying_set_path_add
def keying_set_path_add(): """Add empty path to active Keying Set """ pass
pyboto3-1.4.4
pyboto3-1.4.4//pyboto3/cloudhsm.pyfile:/pyboto3/cloudhsm.py:function:modify_hsm/modify_hsm
def modify_hsm(HsmArn=None, SubnetId=None, EniIp=None, IamRoleArn=None, ExternalId=None, SyslogIp=None): """ Modifies an HSM. See also: AWS API Documentation :example: response = client.modify_hsm( HsmArn='string', SubnetId='string', EniIp='string', IamRoleArn='string', ExternalId='string', SyslogIp='string' ) :type HsmArn: string :param HsmArn: [REQUIRED] The ARN of the HSM to modify. :type SubnetId: string :param SubnetId: The new identifier of the subnet that the HSM is in. The new subnet must be in the same Availability Zone as the current subnet. :type EniIp: string :param EniIp: The new IP address for the elastic network interface (ENI) attached to the HSM. If the HSM is moved to a different subnet, and an IP address is not specified, an IP address will be randomly chosen from the CIDR range of the new subnet. :type IamRoleArn: string :param IamRoleArn: The new IAM role ARN. :type ExternalId: string :param ExternalId: The new external ID. :type SyslogIp: string :param SyslogIp: The new IP address for the syslog monitoring server. The AWS CloudHSM service only supports one syslog monitoring server. :rtype: dict :return: { 'HsmArn': 'string' } """ pass
jira-bulk-loader-0.3.1
jira-bulk-loader-0.3.1//jirabulkloader/interface.pyfile:/jirabulkloader/interface.py:function:get_options/get_options
def get_options(args_list=None): """Create argparse structure and parse arguments""" import argparse parser = argparse.ArgumentParser(description= 'A command line tool for creating tasks in JIRA.', formatter_class= argparse.RawDescriptionHelpFormatter, epilog= """Thank you for using Jira Bulk Loader. Mailing list: <https://groups.google.com/d/forum/jura-bulk-loader> Bug tracker: <https://github.com/oktopuz/jira-bulk-loader/issues>""" ) parser.add_argument('template_file', help= 'a file containing issues definition') parser.add_argument('--dry', dest='dry_run', action='store_true', help= 'make a dry run. It checks everything but does not create issues', default=False) required = parser.add_argument_group('required arguments') required.add_argument('-H', '--host', required=True, help= 'JIRA hostname with http:// or https://') required.add_argument('-U', '--user', required=True, help='your username') required.add_argument('-P', dest='password', required=True, help= "your password. You'll be prompted for it if not specified") jattrs = parser.add_argument_group('JIRA attributes') jattrs.add_argument('-W', '--project', help='project key') jattrs.add_argument('-R', '--priority', help= "default task priority. 'Medium' if not specified", default='Medium') jattrs.add_argument('-D', '--duedate', help= 'default issue dueDate (YYYY-mm-DD)') return parser.parse_args(args_list)
optimeed
optimeed//core/myjson.pyfile:/core/myjson.py:function:_object_to_FQCN/_object_to_FQCN
def _object_to_FQCN(theobj): """Gets module path of object""" module = theobj.__class__.__module__ if module is None or module == str.__class__.__module__: return theobj.__class__.__qualname__ return module + '.' + theobj.__class__.__qualname__
claripy-8.20.1.7
claripy-8.20.1.7//claripy/fp.pyfile:/claripy/fp.py:function:fpMul/fpMul
def fpMul(_rm, a, b): """ Returns the multiplication of two floating point numbers, `a` and `b`. """ return a * b
zoosrv-0.1.3
zoosrv-0.1.3//zoosrv/components/receive.pyfile:/zoosrv/components/receive.py:function:receive/receive
def receive(data_length, es): """ Receive data from evaluation server and remove useless characters. :param data_length: length of the data received :param es: evaluation server :return: data received """ data_str = '' while True: data_tmp = es.recv(data_length).decode() stop = data_tmp.find('#') if stop > 0: data_tmp = data_tmp[0:stop] data_str += data_tmp break else: data_str += data_tmp if data_str[0] == '\n': data_str = data_str[1:] if data_str[-1] == '\n': data_str = data_str[:-1] return data_str
amitgroup-0.9.0
amitgroup-0.9.0//amitgroup/util/saveable.pyclass:Saveable/load_from_dict
@classmethod def load_from_dict(cls, d): """ Overload this function in your subclass. It takes a dictionary and should return a constructed object. When overloading, you have to decorate this function with ``@classmethod``. Parameters ---------- d : dict Dictionary representation of an instance of your class. Returns ------- obj : object Returns an object that has been constructed based on the dictionary. """ raise NotImplementedError( 'Must override load_from_dict for Saveable interface')
ask_sdk_model
ask_sdk_model//services/directive/directive.pyclass:Directive/get_real_child_model
@classmethod def get_real_child_model(cls, data): """Returns the real base class specified by the discriminator""" discriminator_value = data[cls.json_discriminator_key] return cls.discriminator_value_class_map.get(discriminator_value)
django-roughpages-1.0.0
django-roughpages-1.0.0//src/roughpages/utils.pyfile:/src/roughpages/utils.py:function:replace_dots_to_underscores_at_last/replace_dots_to_underscores_at_last
def replace_dots_to_underscores_at_last(path): """ Remove dot ('.') while a dot is treated as a special character in backends Args: path (str): A target path string Returns: str """ if path == '': return path bits = path.split('/') bits[-1] = bits[-1].replace('.', '_') return '/'.join(bits)
arpys-0.2.0
arpys-0.2.0//arpys/fit2d.pyfile:/arpys/fit2d.py:function:g11_alt/g11_alt
def g11_alt(k, E, sig, band, gap): """ Variation of :func: `g11 <arpys.2dfit.g11>` which takes precalculated values of `sig`, `band` and `gap`. *Parameters* ==== ====================================================================== k array of length 2; k vector (in-plane) at which to evaluate g11 E float; energy at which to evaluate g11 sig complex; value of the complex self-energy at E band float; value of the bare band at this k gap float; value of the gap at this k ==== ====================================================================== """ re_sig = sig.real e_diff = E - sig nominator = e_diff + band denominator = e_diff ** 2 - band ** 2 - gap * (1 - re_sig / E) return nominator / denominator
colour_hdri
colour_hdri//exposure/dsc.pyfile:/exposure/dsc.py:function:exposure_index_values/exposure_index_values
def exposure_index_values(H_a): """ Computes the exposure index values :math:`I_{EI}` from given focal plane exposure :math:`H_a`. Parameters ---------- H_a : array_like Focal plane exposure :math:`H_a`. Returns ------- ndarray Exposure index values :math:`I_{EI}`. References ---------- :cite:`ISO2006` Examples -------- >>> exposure_index_values(0.1628937086212269) # doctest: +ELLIPSIS 61.3897251... """ return 10 / H_a
sunpy-1.1.3
sunpy-1.1.3//sunpy/map/sources/rhessi.pyclass:RHESSIMap/is_datasource_for
@classmethod def is_datasource_for(cls, data, header, **kwargs): """Determines if header corresponds to an RHESSI image""" return header.get('instrume') == 'RHESSI'
bpy
bpy//ops/image.pyfile:/ops/image.py:function:view_zoom_border/view_zoom_border
def view_zoom_border(xmin: int=0, xmax: int=0, ymin: int=0, ymax: int=0, wait_for_input: bool=True, zoom_out: bool=False): """Zoom in the view to the nearest item contained in the border :param xmin: X Min :type xmin: int :param xmax: X Max :type xmax: int :param ymin: Y Min :type ymin: int :param ymax: Y Max :type ymax: int :param wait_for_input: Wait for Input :type wait_for_input: bool :param zoom_out: Zoom Out :type zoom_out: bool """ pass
pydash-4.7.6
pydash-4.7.6//src/pydash/arrays.pyfile:/src/pydash/arrays.py:function:iterintersperse/iterintersperse
def iterintersperse(iterable, separator): """Iteratively intersperse iterable.""" iterable = iter(iterable) yield next(iterable) for item in iterable: yield separator yield item
codimension-4.8.1
codimension-4.8.1//codimension/utils/md.pyfile:/codimension/utils/md.py:function:is_plant_uml/is_plant_uml
def is_plant_uml(text, lang): """True if it is a plant uml diagram""" if lang: return lang.lower() in ['plantuml', 'uml'] return text.lstrip().lower().startswith('@start')
ironic-15.0.0
ironic-15.0.0//ironic/conductor/steps.pyfile:/ironic/conductor/steps.py:function:is_equivalent/is_equivalent
def is_equivalent(step1, step2): """Compare steps, ignoring their priority.""" return step1.get('interface') == step2.get('interface') and step1.get( 'step') == step2.get('step')
fake-bpy-module-2.79-20200428
fake-bpy-module-2.79-20200428//bpy/ops/mesh.pyfile:/bpy/ops/mesh.py:function:edge_collapse/edge_collapse
def edge_collapse(): """Collapse selected edges """ pass
datesy
datesy//inspect.pyfile:/inspect.py:function:find_header_line/find_header_line
def find_header_line(data, header_keys): """ Find the header line in row_based data_structure NOT IMPLEMENTED YET: Version 0.9 feature Parameters ---------- data : list, pandas.DataFrame header_keys : str, list, set some key(s) to find in a row Returns ------- int the header_line """ raise NotImplemented
fake-bpy-module-2.78-20200428
fake-bpy-module-2.78-20200428//bpy/ops/wm.pyfile:/bpy/ops/wm.py:function:radial_control/radial_control
def radial_control(data_path_primary: str='', data_path_secondary: str='', use_secondary: str='', rotation_path: str='', color_path: str='', fill_color_path: str='', fill_color_override_path: str='', fill_color_override_test_path: str='', zoom_path: str='', image_id: str ='', secondary_tex: bool=False): """Set some size property (like e.g. brush size) with mouse wheel :param data_path_primary: Primary Data Path, Primary path of property to be set by the radial control :type data_path_primary: str :param data_path_secondary: Secondary Data Path, Secondary path of property to be set by the radial control :type data_path_secondary: str :param use_secondary: Use Secondary, Path of property to select between the primary and secondary data paths :type use_secondary: str :param rotation_path: Rotation Path, Path of property used to rotate the texture display :type rotation_path: str :param color_path: Color Path, Path of property used to set the color of the control :type color_path: str :param fill_color_path: Fill Color Path, Path of property used to set the fill color of the control :type fill_color_path: str :param fill_color_override_path: Fill Color Override Path :type fill_color_override_path: str :param fill_color_override_test_path: Fill Color Override Test :type fill_color_override_test_path: str :param zoom_path: Zoom Path, Path of property used to set the zoom level for the control :type zoom_path: str :param image_id: Image ID, Path of ID that is used to generate an image for the control :type image_id: str :param secondary_tex: Secondary Texture, Tweak brush secondary/mask texture :type secondary_tex: bool """ pass
captest
captest//capdata.pyfile:/capdata.py:function:perc_bounds/perc_bounds
def perc_bounds(percent_filter): """ Convert +/- percentage to decimals to be used to determine bounds. Parameters ---------- percent_filter : float or tuple, default None Percentage or tuple of percentages used to filter around reporting irradiance in the irr_rc_balanced function. Required argument when irr_bal is True. Returns ------- tuple Decimal versions of the percent irradiance filter. 0.8 and 1.2 would be returned when passing 20 to the input. """ if isinstance(percent_filter, tuple): perc_low = percent_filter[0] / 100 perc_high = percent_filter[1] / 100 else: perc_low = percent_filter / 100 perc_high = percent_filter / 100 low = 1 - perc_low high = 1 + perc_high return low, high
mallet
mallet//helpers.pyfile:/helpers.py:function:generic_summary_provider/generic_summary_provider
def generic_summary_provider(value_obj, internal_dict, class_synthetic_provider ): """ Checks value type and returns summary. :param lldb.SBValue value_obj: LLDB object. :param dict internal_dict: Internal LLDB dictionary. :param class class_synthetic_provider: Synthetic provider class. :return: Value summary. :rtype: str """ provider = class_synthetic_provider(value_obj, internal_dict) if provider is not None: return provider.summary() return 'Summary Unavailable'
contracts-0.1.0
contracts-0.1.0//contracts.pyfile:/contracts.py:function:__identity/__identity
def __identity(function): """ identify function just returns the same function """ return function
PySiddhi
PySiddhi//core/stream/input/InputHandler.pyclass:InputHandler/_fromInputHandlerProxy
@classmethod def _fromInputHandlerProxy(cls, input_handler_proxy): """ Internal Constructor to wrap around JAVA Class InputHandler :param input_handler_proxy: :return: """ instance = cls.__new__(cls) instance.input_handler_proxy = input_handler_proxy return instance
aiobitcoin
aiobitcoin//tools/encoding.pyfile:/tools/encoding.py:function:is_sec_compressed/is_sec_compressed
def is_sec_compressed(sec): """Return a boolean indicating if the sec represents a compressed public key.""" return sec[:1] in (b'\x02', b'\x03')
cleaning-scripts-0.2.19
cleaning-scripts-0.2.19//scripts/logic/binary_to_bool_2.pyfile:/scripts/logic/binary_to_bool_2.py:function:binary_to_bool_2/binary_to_bool_2
def binary_to_bool_2(raw_input): """Map (0,1) to (True, False)""" mapping = {'0': True, '1': False} if raw_input in mapping.keys(): return mapping[raw_input] else: return None
fmoo-audiotools-3.1beta1
fmoo-audiotools-3.1beta1//audiotools/au.pyclass:AuAudio/supports_from_pcm
@classmethod def supports_from_pcm(cls): """returns True if all necessary components are available to support the .from_pcm() classmethod""" return True
mallet
mallet//UIKit/UITableViewCell.pyclass:UITableViewCellSyntheticProvider/get_text_label_summary
@staticmethod def get_text_label_summary(provider): """ Text label summary. :param UILabel.UILabelSyntheticProvider provider: UILabel provider :return: Text label summary. :rtype: str """ value = provider.text_value if value is not None: return 'textLabel={}'.format(provider.text_value) return None
dgl_cu100-0.4.3.post2.data
dgl_cu100-0.4.3.post2.data//purelib/dgl/_ffi/_ctypes/function.pyfile:/purelib/dgl/_ffi/_ctypes/function.py:function:_set_class_module/_set_class_module
def _set_class_module(module_class): """Initialize the module.""" global _CLASS_MODULE _CLASS_MODULE = module_class
pyNastran
pyNastran//bdf/cards/coordinate_systems.pyfile:/bdf/cards/coordinate_systems.py:function:_primary_axes/_primary_axes
def _primary_axes(coord): """gets the i,j,k axes from the ???""" coord_transform = coord.beta() ex = coord_transform[(0), :] ey = coord_transform[(1), :] ez = coord_transform[(2), :] return ex, ey, ez