repo
stringlengths
1
29
path
stringlengths
24
332
code
stringlengths
39
579k
pyboto3-1.4.4
pyboto3-1.4.4//pyboto3/organizations.pyfile:/pyboto3/organizations.py:function:update_policy/update_policy
def update_policy(PolicyId=None, Name=None, Description=None, Content=None): """ Updates an existing policy with a new name, description, or content. If any parameter is not supplied, that value remains unchanged. Note that you cannot change a policy's type. This operation can be called only from the organization's master account. See also: AWS API Documentation :example: response = client.update_policy( PolicyId='string', Name='string', Description='string', Content='string' ) :type PolicyId: string :param PolicyId: [REQUIRED] The unique identifier (ID) of the policy that you want to update. The regex pattern for a policy ID string requires 'p-' followed by from 8 to 128 lower-case letters or digits. :type Name: string :param Name: If provided, the new name for the policy. The regex pattern that is used to validate this parameter is a string of any of the characters in the ASCII character range. :type Description: string :param Description: If provided, the new description for the policy. :type Content: string :param Content: If provided, the new content for the policy. The text must be correctly formatted JSON that complies with the syntax for the policy's type. For more information, see Service Control Policy Syntax in the AWS Organizations User Guide . :rtype: dict :return: { 'Policy': { 'PolicySummary': { 'Id': 'string', 'Arn': 'string', 'Name': 'string', 'Description': 'string', 'Type': 'SERVICE_CONTROL_POLICY', 'AwsManaged': True|False }, 'Content': 'string' } } """ pass
csirtg-enrichment-0.3
csirtg-enrichment-0.3//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
fake-bpy-module-2.79-20200428
fake-bpy-module-2.79-20200428//bpy/ops/mesh.pyfile:/bpy/ops/mesh.py:function:primitive_grid_add/primitive_grid_add
def primitive_grid_add(x_subdivisions: int=10, y_subdivisions: int=10, radius: float=1.0, calc_uvs: bool=False, view_align: bool=False, enter_editmode: bool=False, location: float=(0.0, 0.0, 0.0), rotation: float=(0.0, 0.0, 0.0), layers: bool=(False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False)): """Construct a grid mesh :param x_subdivisions: X Subdivisions :type x_subdivisions: int :param y_subdivisions: Y Subdivisions :type y_subdivisions: int :param radius: Radius :type radius: float :param calc_uvs: Generate UVs, Generate a default UV map :type calc_uvs: bool :param view_align: Align to View, Align the new object to the view :type view_align: bool :param enter_editmode: Enter Editmode, Enter editmode when adding this object :type enter_editmode: bool :param location: Location, Location for the newly added object :type location: float :param rotation: Rotation, Rotation for the newly added object :type rotation: float :param layers: Layer :type layers: bool """ pass
twisted
twisted//internet/interfaces.pyclass:IResolver/lookupMailExchange
def lookupMailExchange(name, timeout=None): """ Perform an MX record lookup. @type name: L{bytes} or L{str} @param name: DNS name to resolve. @type timeout: Sequence of C{int} @param timeout: Number of seconds after which to reissue the query. When the last timeout expires, the query is considered failed. @rtype: L{Deferred} @return: A L{Deferred} which fires with a three-tuple of lists of L{twisted.names.dns.RRHeader} instances. The first element of the tuple gives answers. The second element of the tuple gives authorities. The third element of the tuple gives additional information. The L{Deferred} may instead fail with one of the exceptions defined in L{twisted.names.error} or with C{NotImplementedError}. """
moviepy_patch-1.0.1
moviepy_patch-1.0.1//moviepy/config.pyfile:/moviepy/config.py:function:get_setting/get_setting
def get_setting(varname): """ Returns the value of a configuration variable. """ gl = globals() if varname not in gl.keys(): raise ValueError('Unknown setting %s' % varname) return gl[varname]
blockmodel-1.0.2
blockmodel-1.0.2//src/blockmodel/readers/png.pyfile:/src/blockmodel/readers/png.py:function:mycallersname/mycallersname
def mycallersname(): """Returns the name of the caller of the caller of this function (hence the name of the caller of the function in which "mycallersname()" textually appears). Returns None if this cannot be determined.""" import inspect frame = inspect.currentframe() if not frame: return None frame_, filename_, lineno_, funname, linelist_, listi_ = (inspect. getouterframes(frame)[2]) return funname
androguard
androguard//gui/helpers.pyfile:/gui/helpers.py:function:class2func/class2func
def class2func(path): """ Convert a path such as 'Landroid/support/v4/app/ActivityCompat;' into a method string 'CLASS_Landroid_support_v4_app_ActivityCompat' so we can call d.CLASS_Landroid_support_v4_app_ActivityCompat.get_source() """ func = 'CLASS_' + path.replace('/', '_').replace('$', '_').replace(';', '') return func
ansible-2.9.7
ansible-2.9.7//lib/ansible/modules/storage/purestorage/purefa_dsrole.pyfile:/lib/ansible/modules/storage/purestorage/purefa_dsrole.py:function:create_role/create_role
def create_role(module, array): """Create Directory Service Role""" changed = False try: array.set_directory_services_roles(names=[module.params['role']], group_base=module.params['group_base'], group=module.params[ 'group']) changed = True except Exception: module.fail_json(msg= 'Create Directory Service Role {0} failed: Check configuration' .format(module.params['role'])) module.exit_json(changed=changed)
autosolvepy-0.0.1
autosolvepy-0.0.1//venv/Lib/site-packages/urllib3/util/response.pyfile:/venv/Lib/site-packages/urllib3/util/response.py:function:is_fp_closed/is_fp_closed
def is_fp_closed(obj): """ Checks whether a given file-like object is closed. :param obj: The file-like object to check. """ try: return obj.isclosed() except AttributeError: pass try: return obj.closed except AttributeError: pass try: return obj.fp is None except AttributeError: pass raise ValueError('Unable to determine whether fp is closed.')
battleship
battleship//ui.pyfile:/ui.py:function:convert/convert
def convert(coord): """Converts coordinate as displayed coordinates to digit tuple eg: J9 -> (9,9); checks for possible human errors converts coordinate as digit tuple to displayed coordinates eg: (0,0) -> A0; should not have any errors. """ A2D = dict(zip('ABCDEFGHIJ', range(10))) D2A = dict(zip(range(10), 'ABCDEFGHIJ')) if isinstance(coord, str): try: coord = A2D[coord[0]], int(coord[1]) if 0 <= coord[1] < 10: return coord else: return None except KeyError: return None else: coord = D2A[coord[0]] + str(coord[1]) return coord
tkinterx
tkinterx//meta.pyfile:/meta.py:function:ask_window/ask_window
def ask_window(tk_root, window_type): """Pass information through a window :param tk_root: An instance of a Tk or an instance of its subclass :param window_type: WindowMeta or its subclasses """ window = window_type(tk_root) window.transient(tk_root) tk_root.wait_window(window) return window.table
Porm-0.0.28a0
Porm-0.0.28a0//src/porm/databases/api/mysql.pyclass:MyDBApi/_set_autocommit
@staticmethod def _set_autocommit(conn, auto): """ Get connection auto commit attribute :param conn: :param auto: :return: """ try: conn.autocommit(auto) except AttributeError: with conn.cursor() as cursor: cursor.execute('SET AUTOCOMMIT=%s;' % auto)
DateTime-4.3
DateTime-4.3//src/DateTime/interfaces.pyclass:IDateTime/isCurrentMinute
def isCurrentMinute(): """Return true if this object represents a date/time that falls within the current minute, in the context of this object's timezone representation"""
splash-3.4.1
splash-3.4.1//splash/jsutils.pyfile:/splash/jsutils.py:function:get_process_errors_js/get_process_errors_js
def get_process_errors_js(expression): """ Return JS code which evaluates an ``expression`` and returns ``{error: false, result: ...}`` if there is no exception or ``{error: true, errorType: ..., errorMessage: ..., errorRepr: ...}`` if expression raised an error when evaluating. """ return ( u""" (function () { try { return { error: false, result: %(expression)s, } } catch (e) { return { error: true, errorType: e.name, errorMessage: e.message, errorRepr: e.toString(), }; } })() """ % dict(expression=expression))
LaueTools
LaueTools//Lauehdf5.pyfile:/Lauehdf5.py:function:filterlist/filterlist
def filterlist(initlist, list_of_strings_to_add, list_of_fields): """ add elem of list_of_strings_to_add that are in list_of_fields in initlist and raise an error if elem is not in list_of_fields """ for elem in list_of_strings_to_add: if elem in list_of_fields: initlist += [elem] else: raise ValueError( 'tableallspots.fields : %s does not contain this requested field: %s ' % (list_of_fields, elem)) return initlist
riemann
riemann//utils.pyfile:/utils.py:function:i2be/i2be
def i2be(number: int) ->bytes: """ Convert int to big endian (b.e.) bytes Args: number: int value to convert to bytes in BE format Returns: bytes in BE format """ if number == 0: return b'\x00' return number.to_bytes((number.bit_length() + 7) // 8, 'big')
crispy
crispy//Utils.pyclass:Utils/bin_bkdist
@staticmethod def bin_bkdist(distance): """ Discretise genomic distances :param distance: float :return: """ if distance == -1: bin_distance = 'diff. chr.' elif distance == 0: bin_distance = '0' elif 1 < distance < 10000.0: bin_distance = '1-10 kb' elif 10000.0 < distance < 100000.0: bin_distance = '10-100 kb' elif 100000.0 < distance < 1000000.0: bin_distance = '0.1-1 Mb' elif 1000000.0 < distance < 10000000.0: bin_distance = '1-10 Mb' else: bin_distance = '>10 Mb' return bin_distance
pgpu-2.0.0
pgpu-2.0.0//pgpu/iter_utils.pyfile:/pgpu/iter_utils.py:function:replace_many/replace_many
def replace_many(s, d, inverse=False): """ Goes through dict @d's keys and replaces their occurences with their value. If @inverse is true, the values are replaced by the keys. NOTE: Results may vary from run to run and machine to machine because of Python's dictionary optimization, especially if @inverse is true and some keys have the same value. If a certain order is required, use a sorted dictionary for @d. If @inverse is true, there may be no empty string values, and if not, no empty string keys. >>> replace_many('quantum_junk10', {'1': '', '0': 'o', '_': ' '}) 'quantum junko' >>> replace_many('quantum_junk10', {'a': '0', 'b': '1'}, True) 'quantum_junkba' >>> replace_many('quantum_junk10', {'': '5'}) <TypeError traceback> AUTHORS: v0.2.0+ --> pydsigner """ if inverse: for k in d: s = s.replace(d[k], k) else: for k in d: s = s.replace(k, d[k]) return s
dadi
dadi//Triallele/integration.pyfile:/Triallele/integration.py:function:inject_simultaneous_muts/inject_simultaneous_muts
def inject_simultaneous_muts(phi, dt, x, dx, theta): """ simultaneous mutation model - see Hodgkinson and Eyre-Walker 2010, injected at (Delta,Delta) """ phi[1, 1] += 1.0 / x[1] / x[1] / dx[1] / dx[1] * dt * theta return phi
modelling-service-test-0.1.4
modelling-service-test-0.1.4//modellingService/Utils.pyfile:/modellingService/Utils.py:function:reshapeParams/reshapeParams
def reshapeParams(hyperparams, reshaper): """ A utility function that takes a dictionary of transformations for valid hyperparameters and filters out invalid params Testing the function: print reshapeParams({'regParam': 'invalid', 'elasticNetParam': 0.1, 'maxDepth': 0.1}, {'regParam': float, 'elasticNetParam': float, 'threshold': float}) # Expect: {'elasticNetParam': 0.1} :param hyperparams: the dirty dictionary :param reshaper: the transformations :return: the clean dictionary """ d = {} for k, v in hyperparams.items(): if reshaper.has_key(k): f = reshaper[k] if isinstance(v, str): if v.replace('.', '', 1).isdigit(): d[k] = f(v) else: continue elif isinstance(v, float): d[k] = f(v) elif isinstance(v, int): d[k] = f(v) else: continue else: continue return d
p4p-3.4.2
p4p-3.4.2//src/p4p/asLib/lex.pyfile:/src/p4p/asLib/lex.py:function:t_KW/t_KW
def t_KW(t): """UAG|HAG|ASG|RULE|CALC""" t.type = t.value return t
huskar_sdk_v2
huskar_sdk_v2//utils/format.pyfile:/utils/format.py:function:char_encoding/char_encoding
def char_encoding(value): """ Encode unicode into 'UTF-8' string. :param value: :return: """ if not isinstance(value, bytes): return value.encode('utf-8') return value
ais-dom-0.108.9
ais-dom-0.108.9//homeassistant/components/viaggiatreno/sensor.pyclass:ViaggiaTrenoSensor/is_cancelled
@staticmethod def is_cancelled(data): """Check if the train is cancelled.""" if data['tipoTreno'] == 'ST' and data['provvedimento'] == 1: return True return False
networking-fujitsu-8.0.0
networking-fujitsu-8.0.0//networking_fujitsu/ml2/common/utils.pyfile:/networking_fujitsu/ml2/common/utils.py:function:is_lag/is_lag
def is_lag(local_link_information): """Judge a specified port param is for LAG(linkaggregation) or not. :param local_link_information: physical connectivity information :type local_link_information: list of dict :returns: True(mode is LAG) or False(otherwise) :rtype: boolean """ return len(local_link_information) > 1
profab-0.5.1
profab-0.5.1//profab/server.pyclass:Server/get_role_adders
@classmethod def get_role_adders(cls, *roles): """Convert the arguments into a list of commands or options and values. """ role_adders = [] for role_argument in roles: if type(role_argument) == tuple: role, parameter = role_argument else: role, parameter = role_argument, None import_names = ['AddRole', 'Configure'] try: module = __import__(role, globals(), locals(), import_names) except ImportError: try: module = __import__('profab.role.%s' % role, globals(), locals(), import_names) except ImportError: raise ImportError('Could not import %s or profab.role.%s' % (role, role)) if parameter: role_adders.append(module.Configure(parameter)) else: role_adders.append(module.AddRole()) return role_adders
dask
dask//diagnostics/profile_visualize.pyfile:/diagnostics/profile_visualize.py:function:fix_bounds/fix_bounds
def fix_bounds(start, end, min_span): """Adjust end point to ensure span of at least `min_span`""" return start, max(end, start + min_span)
dropbox-10.1.2
dropbox-10.1.2//dropbox/team_log.pyclass:EventDetails/device_approvals_change_mobile_policy_details
@classmethod def device_approvals_change_mobile_policy_details(cls, val): """ Create an instance of this class set to the ``device_approvals_change_mobile_policy_details`` tag with value ``val``. :param DeviceApprovalsChangeMobilePolicyDetails val: :rtype: EventDetails """ return cls('device_approvals_change_mobile_policy_details', val)
PySPH-1.0a6
PySPH-1.0a6//pysph/tools/geometry.pyfile:/pysph/tools/geometry.py:function:show_2d/show_2d
def show_2d(points, **kw): """Show two-dimensional geometry data. The `points` are a tuple of x, y, z values, the extra keyword arguments are passed along to the scatter function. """ import matplotlib.pyplot as plt plt.scatter(points[0], points[1], **kw) plt.xlabel('X') plt.ylabel('Y')
UFL-2017.1.0
UFL-2017.1.0//ufl/utils/formatting.pyfile:/ufl/utils/formatting.py:function:istr/istr
def istr(o): """Format object as string, inserting ? for None.""" if o is None: return '?' else: return str(o)
zqy-1.0.5
zqy-1.0.5//zqy/zqy.pyfile:/zqy/zqy.py:function:sqlinsert/sqlinsert
def sqlinsert(df, tablename): """输入一个df,返回插入此df的sql原生语言""" oo = '' for index, row in df.iterrows(): o = '(' for i in range(len(row)): ii = row[i] if i == 0: o = o + "'%s'" % ii + ',' else: o = o + '%s' % ii + ',' o = o.strip(',') o = o + ')' oo = oo + o + ',' oo = oo.strip(',') sql = 'insert into %s values %s' % (tablename, oo) return sql
bpy
bpy//ops/poselib.pyfile:/ops/poselib.py:function:apply_pose/apply_pose
def apply_pose(pose_index: int=-1): """Apply specified Pose Library pose to the rig :param pose_index: Pose, Index of the pose to apply (-2 for no change to pose, -1 for poselib active pose) :type pose_index: int """ pass
diplomacy-1.1.2
diplomacy-1.1.2//diplomacy/client/notification_managers.pyfile:/diplomacy/client/notification_managers.py:function:_get_game_to_notify/_get_game_to_notify
def _get_game_to_notify(connection, notification): """ Get notified game from connection using notification parameters. :param connection: connection that receives the notification. :param notification: notification received. :return: a NetworkGame instance, or None if no game found. :type connection: diplomacy.Connection :type notification: diplomacy.communication.notifications._GameNotification """ channel = connection.channels.get(notification.token, None) if channel and notification.game_id in channel.game_id_to_instances: return channel.game_id_to_instances[notification.game_id].get( notification.game_role) return None
bigmler-3.26.3
bigmler-3.26.3//bigmler/options/topicmodel.pyfile:/bigmler/options/topicmodel.py:function:get_topic_model_options/get_topic_model_options
def get_topic_model_options(defaults=None): """Adding arguments for the topic model subcommand """ if defaults is None: defaults = {} options = {'--topic-fields': {'action': 'store', 'dest': 'topic_fields', 'default': defaults.get('topic_fields', None), 'help': 'Comma-separated list of input fields (predictors) to create the topic model.' }, '--topic-model': {'action': 'store', 'dest': 'topic_model', 'default': defaults.get('topic_model', None), 'help': 'BigML topic model Id.'}, '--topic-models': {'action': 'store', 'dest': 'topic_models', 'default': defaults.get('topic_models', None), 'help': 'Path to a file containing topicmodel/ids. One topicmodel per line (e.g., topicmodel/50a206a8035d0706dc000376).' }, '--topic-model-file': {'action': 'store', 'dest': 'topic_model_file', 'default': defaults.get('topic_model_file', None), 'help': 'BigML topic model JSON structure file.'}, '--bigrams': {'action': 'store_true', 'dest': 'bigrams', 'default': defaults.get('bigrams', False), 'help': 'Whether to include a contiguous sequence of two items from a given sequence of text.' }, '--case-sensitive': {'action': 'store_true', 'dest': 'case_sensitive', 'default': defaults.get('case_sensitive', False), 'help': 'Whether the analysis is case-sensitive or not.'}, '--excluded-terms': {'action': 'store', 'dest': 'excluded_terms', 'default': defaults.get('excluded_terms', None), 'help': 'Comma-separated list of terms to be excluded from text analysis.'}, '--number-of-topics': {'action': 'store', 'dest': 'number_of_topics', 'type': int, 'default': defaults.get( 'number_of_topics', None), 'help': 'Number of topics to be generated for the model.'}, '--minimum-name-terms': {'action': 'store', 'dest': 'minimum_name_terms', 'type': int, 'default': defaults.get( 'minimum_name_terms', None), 'help': 'Number of terms to be used to name the topic.'}, '--term-limit': { 'action': 'store', 'dest': 'term_limit', 'type': int, 'default': defaults.get('term_limit', 4096), 'help': 'The maximum number of terms used for the topic model vocabulary.'}, '--top-n-terms': {'action': 'store', 'dest': 'top_n_terms', 'type': int, 'default': defaults.get('top_n_terms', 10), 'help': 'The size of the most influential terms recorded.'}, '--use-stopwords': {'action': 'store_true', 'dest': 'use_stopwords', 'default': defaults.get('use_stopwords', False), 'help': 'Whether to use stop words.'}, '--no-topic-model': {'action': 'store_true', 'dest': 'no_topic_model', 'default': defaults.get( 'no_topic_model', False), 'help': 'Do not create a topic model.'}, '--no-no-topic-model': {'action': 'store_false', 'dest': 'no_topic_model', 'default': defaults.get('no_topic_model', False), 'help': 'Create a topic model.'}, '--topic-model-attributes': { 'action': 'store', 'dest': 'topic_model_attributes', 'default': defaults.get('topic_model_attributes', None), 'help': 'Path to a json file describing topic model attributes.'}} return options
slam
slam//parallel.pyfile:/parallel.py:function:print_time_cost/print_time_cost
def print_time_cost(dtime, unit_max='hour'): """ return string for delta_time """ if dtime <= 60 * 1.5: dtime_str = '{:.3f} sec'.format(dtime) elif dtime <= 60 * 60 * 1.5: dtime_str = '{:.3f} min'.format(dtime / 60.0) elif dtime <= 60 * 60 * 24 * 3: dtime_str = '{:.3f} hours'.format(dtime / 3600.0) elif unit_max == 'hour': dtime <= 60 * 60 * 24 * 3 dtime_str = '{:.3f} hours'.format(dtime / 3600.0) else: dtime_str = '{:.3f} days'.format(dtime / 86400.0) return dtime_str
hedgehog-pyvisa-2.0.0
hedgehog-pyvisa-2.0.0//pyvisa/ctwrapper/functions.pyfile:/pyvisa/ctwrapper/functions.py:function:map_trigger/map_trigger
def map_trigger(library, session, trigger_source, trigger_destination, mode): """Map the specified trigger source line to the specified destination line. Corresponds to viMapTrigger function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param trigger_source: Source line from which to map. (Constants.TRIG*) :param trigger_destination: Destination line to which to map. (Constants.TRIG*) :param mode: :return: return value of the library call. :rtype: :class:`pyvisa.constants.StatusCode` """ return library.viMapTrigger(session, trigger_source, trigger_destination, mode)
neatbio
neatbio//sequtils/sequtils.pyfile:/sequtils/sequtils.py:function:get_kmers/get_kmers
def get_kmers(seq, k=2): """Get the K-mers of A Sequence where k is the number >>> get_kmers(seq1,3) """ pair_list = [] for i in range(0, len(seq), k): pair_list.append(str(seq)[i:i + k]) return pair_list
securefile-1.0.1
securefile-1.0.1//securefile/aes_algorithm.pyclass:AES/RotWord
@staticmethod def RotWord(word): """ Takes a word [a0, a1, a2, a3] as input and perform a cyclic permutation that returns the word [a1, a2, a3, a0]. :param str word: Row within State Matrix :return: Circular byte left shift """ return int(word[2:] + word[0:2], 16)
superset-dywx-0.26.3
superset-dywx-0.26.3//superset/dataframe.pyfile:/superset/dataframe.py:function:dedup/dedup
def dedup(l, suffix='__'): """De-duplicates a list of string by suffixing a counter Always returns the same number of entries as provided, and always returns unique values. >>> print(','.join(dedup(['foo', 'bar', 'bar', 'bar']))) foo,bar,bar__1,bar__2 """ new_l = [] seen = {} for s in l: if s in seen: seen[s] += 1 s += suffix + str(seen[s]) else: seen[s] = 0 new_l.append(s) return new_l
qibuild-3.14.1
qibuild-3.14.1//python/qisys/sh.pyfile:/python/qisys/sh.py:function:is_binary/is_binary
def is_binary(file_path): """ Returns True if the file is binary """ with open(file_path, 'rb') as fp: data = fp.read(1024) if not data: return False if b'\x00' in data: return True return False
Products.Forum-1.1.7
Products.Forum-1.1.7//src/Products/Forum/setuphandlers.pyfile:/src/Products/Forum/setuphandlers.py:function:post_install/post_install
def post_install(context): """Post install script"""
fake-blender-api-2.79-0.3.1
fake-blender-api-2.79-0.3.1//bpy/ops/uv.pyfile:/bpy/ops/uv.py:function:pack_islands/pack_islands
def pack_islands(rotate: bool=True, margin: float=0.001): """Transform all islands so that they fill up the UV space as much as possible :param rotate: Rotate, Rotate islands for best fit :type rotate: bool :param margin: Margin, Space between islands :type margin: float """ pass
microcosm-sqlite-0.23.0
microcosm-sqlite-0.23.0//microcosm_sqlite/dataset.pyclass:DataSet/drop_all
@classmethod def drop_all(cls, graph): """ Drop schemas for all declared types of this data set. If multiple types are declared for the same declarative base class, all related schemas will be created. """ name = cls.resolve().__name__ engine, _ = graph.sqlite(name) cls.metadata.drop_all(bind=engine)
twisted
twisted//internet/interfaces.pyclass:IResolver/lookupNull
def lookupNull(name, timeout=None): """ Perform a NULL record lookup. @type name: L{bytes} or L{str} @param name: DNS name to resolve. @type timeout: Sequence of C{int} @param timeout: Number of seconds after which to reissue the query. When the last timeout expires, the query is considered failed. @rtype: L{Deferred} @return: A L{Deferred} which fires with a three-tuple of lists of L{twisted.names.dns.RRHeader} instances. The first element of the tuple gives answers. The second element of the tuple gives authorities. The third element of the tuple gives additional information. The L{Deferred} may instead fail with one of the exceptions defined in L{twisted.names.error} or with C{NotImplementedError}. """
finex
finex//ratios.pyfile:/ratios.py:function:days_of_sales_outstanding/days_of_sales_outstanding
def days_of_sales_outstanding(number_of_days, receivables_turnover): """Computes days of sales outstanding. @params ------- number_of_days: number of days in period receivables_turnover: receivables_turnover returns ------- Days of sales outstanding, int or float explanation ----------- """ return number_of_days / receivables_turnover
_TFL
_TFL//predicate.pyfile:/predicate.py:function:plural_of/plural_of
def plural_of(noun): """Returns the plural from of the (english) `noun`. >>> print (plural_of ("house")) houses >>> print (plural_of ("address")) addresses >>> print (plural_of ("enemy")) enemies """ result = noun if result.endswith('s'): result += 'es' elif result.endswith('y'): result = result[:-1] + 'ies' else: result += 's' return result
hickle
hickle//helpers.pyfile:/helpers.py:function:get_type/get_type
def get_type(h_node): """ Helper function to return the py_type for a HDF node """ py_type = h_node.attrs['type'][0] return py_type
guillotina
guillotina//component/interfaces.pyclass:IComponentArchitecture/handle
def handle(*objects): """Call all of the handlers for the given objects Handlers are subscription adapter factories that don't produce anything. They do all of their work when called. Handlers are typically used to handle events. """
pyepbd-6.1
pyepbd-6.1//pyepbd/inputoutput.pyfile:/pyepbd/inputoutput.py:function:ep2dict/ep2dict
def ep2dict(EP, area=1.0): """Format energy efficiency indicators as dict from primary energy data In the context of the CTE regulations, this refers to primary energy values. """ areafactor = 1.0 / area eparen = areafactor * EP['EPpasoA']['ren'] epanren = areafactor * EP['EPpasoA']['nren'] epatotal = eparen + epanren eparer = eparen / epatotal if epatotal else 0.0 epren = areafactor * EP['EP']['ren'] epnren = areafactor * EP['EP']['nren'] eptotal = epren + epnren eprer = epren / eptotal if eptotal else 0.0 epdict = {'EPAren': eparen, 'EPAnren': epanren, 'EPAtotal': epatotal, 'EPArer': eparer, 'EPren': epren, 'EPnren': epnren, 'EPtotal': eptotal, 'EPrer': eprer} return epdict
LaueTools-3.0.0.34
LaueTools-3.0.0.34//LaueTools/indexingAnglesLUT.pyfile:/LaueTools/indexingAnglesLUT.py:function:find_key/find_key
def find_key(mydict, num): """ only for single value (if value is a list : type if num in mydict[k] ) """ for k in list(mydict.keys()): if num == mydict[k]: return k
dgl_cu101-0.4.3.post2.data
dgl_cu101-0.4.3.post2.data//purelib/dgl/backend/backend.pyfile:/purelib/dgl/backend/backend.py:function:sync/sync
def sync(): """Synchronize computation. In DL frameworks such as MXNet and TensorFlow, the computation in operators are done asynchronously. This is to synchronize computation and makes sure that all computation is complete after this function call. """ pass
amntftp
amntftp//client.pyfile:/client.py:function:get_string/get_string
def get_string(data): """Returns a null-trimmed string from the provided value""" try: idx = str(data).index('\x00') except Exception: return None return data[0:idx]
cinder
cinder//api/urlmap.pyfile:/api/urlmap.py:function:unquote_header_value/unquote_header_value
def unquote_header_value(value): """Unquotes a header value. This does not use the real unquoting but what browsers are actually using for quoting. :param value: the header value to unquote. """ if value and value[0] == value[-1] == '"': value = value[1:-1] return value
fulfil_client-1.0.0
fulfil_client-1.0.0//fulfil_client/model.pyclass:Model/from_ids
@classmethod def from_ids(cls, ids): """ Create multiple active resources at once """ return list(map(cls, cls.rpc.read(ids, tuple(cls._eager_fields))))
xenon
xenon//core.pyfile:/core.py:function:av/av
def av(n, m): """Compute n/m if ``m != 0`` or otherwise return 0.""" return n / m if m != 0 else 0
throttle_client-0.3.6
throttle_client-0.3.6//throttle_client/status_code.pyfile:/throttle_client/status_code.py:function:is_recoverable_error/is_recoverable_error
def is_recoverable_error(status_code: int) ->bool: """ True if the passed status_code hints at a recoverable server error. I.e. The same request might be successful at a later point in time. """ if status_code < 400: return False if status_code // 100 == 4: if status_code in [408, 444, 499]: return True else: return False elif status_code // 100 == 5: if status_code in [501, 505, 506, 507, 508, 510, 511]: return False else: return True else: raise ValueError( f'Not an Http status code indicating an error: {status_code}')
stomper
stomper//stomp_11.pyfile:/stomp_11.py:function:send/send
def send(dest, msg, transactionid=None, content_type='text/plain'): """STOMP send command. dest: This is the channel we wish to subscribe to msg: This is the message body to be sent. transactionid: This is an optional field and is not needed by default. """ transheader = '' if transactionid: transheader = 'transaction:%s\n' % transactionid return 'SEND\ndestination:%s\ncontent-type:%s\n%s\n%s\x00\n' % (dest, content_type, transheader, msg)
toolkit_bert_ner
toolkit_bert_ner//bert/run_squad.pyfile:/bert/run_squad.py:function:_check_is_max_context/_check_is_max_context
def _check_is_max_context(doc_spans, cur_span_index, position): """Check if this is the 'max context' doc span for the token.""" best_score = None best_span_index = None for span_index, doc_span in enumerate(doc_spans): end = doc_span.start + doc_span.length - 1 if position < doc_span.start: continue if position > end: continue num_left_context = position - doc_span.start num_right_context = end - position score = min(num_left_context, num_right_context ) + 0.01 * doc_span.length if best_score is None or score > best_score: best_score = score best_span_index = span_index return cur_span_index == best_span_index
eric-ide-20.5
eric-ide-20.5//eric6/DebugClients/Python/coverage/disposition.pyfile:/eric6/DebugClients/Python/coverage/disposition.py:function:disposition_init/disposition_init
def disposition_init(cls, original_filename): """Construct and initialize a new FileDisposition object.""" disp = cls() disp.original_filename = original_filename disp.canonical_filename = original_filename disp.source_filename = None disp.trace = False disp.reason = '' disp.file_tracer = None disp.has_dynamic_filename = False return disp
histogrammar
histogrammar//hgawk_grammar.pyfile:/hgawk_grammar.py:function:p_dotted_as_names_star_1/p_dotted_as_names_star_1
def p_dotted_as_names_star_1(p): """dotted_as_names_star : COMMA dotted_as_name""" p[0] = [p[2]]
uio-0.1.0.6
uio-0.1.0.6//uio/uio.pyfile:/uio/uio.py:function:parse_git_path/parse_git_path
def parse_git_path(git_path): """ Returns tuple (repo_url, git_ref, code_path) """ git_ref = 'master' repo_url, code_path = git_path.replace('git://', '').split('//') if '#' in repo_url: repo_url, git_ref = repo_url.split('#') repo_url = repo_url.rstrip('.git') if not code_path: code_path = '/' return repo_url, git_ref, code_path
pyretis
pyretis//inout/formats/gromacs.pyfile:/inout/formats/gromacs.py:function:_get_chunks/_get_chunks
def _get_chunks(start, end, size): """Yield chunks between start and end of the given size.""" while start < end: new_size = min(size, end - start) start += new_size yield start, new_size
iotcaspy-0.1.0
iotcaspy-0.1.0//iotcaspy/FileUtils.pyfile:/iotcaspy/FileUtils.py:function:get_bytesize_from_str/get_bytesize_from_str
def get_bytesize_from_str(size_str): """ 将字符串表示的文件大小转换成以B为单位的数值 输入示例:3.45KB """ size_str = size_str.upper() unit_mapping = {'TB': 1024 ** 4, 'GB': 1024 ** 3, 'MB': 1024 ** 2, 'KB': 1024 ** 1, 'B': 1} for unit in unit_mapping: if unit in size_str: val = float(size_str.rsplit(unit, 1)[0].strip()) val = int(val * unit_mapping[unit]) break return val
layabase
layabase//_database_mongo.pyclass:_CRUDModel/_get_counter
@classmethod def _get_counter(cls, counter_name: str, counter_category: str=None) ->int: """ Get current counter value. :param counter_name: Name of the counter to retrieve. :param counter_category: Category storing those counters. Default to model table name. :return: Counter value or 0 if not existing. """ counter_key = {'_id': counter_category if counter_category else cls. __collection__.name} counter_element = cls.__counters__.find_one(counter_key) return counter_element[counter_name]['counter'] if counter_element else 0
vumi_message_store
vumi_message_store//interfaces.pyclass:IOperationalMessageStore/get_tag_info
def get_tag_info(tag): """ Get tag information from the message store. :param tag: A tag identifier, either in tuple format or a flattened string. :returns: A CurrentTag model object. If async, a Deferred is returned instead. """
pyramid-1.10.4
pyramid-1.10.4//src/pyramid/interfaces.pyclass:IResponse/md5_etag
def md5_etag(body=None, set_content_md5=False): """ Generate an etag for the response object using an MD5 hash of the body (the body parameter, or self.body if not given). Sets self.etag. If set_content_md5 is True sets self.content_md5 as well """
Keras-2.3.1
Keras-2.3.1//keras/utils/conv_utils.pyfile:/keras/utils/conv_utils.py:function:conv_output_length/conv_output_length
def conv_output_length(input_length, filter_size, padding, stride, dilation=1): """Determines output length of a convolution given input length. # Arguments input_length: integer. filter_size: integer. padding: one of `"same"`, `"valid"`, `"full"`. stride: integer. dilation: dilation rate, integer. # Returns The output length (integer). """ if input_length is None: return None assert padding in {'same', 'valid', 'full', 'causal'} dilated_filter_size = (filter_size - 1) * dilation + 1 if padding == 'same': output_length = input_length elif padding == 'valid': output_length = input_length - dilated_filter_size + 1 elif padding == 'causal': output_length = input_length elif padding == 'full': output_length = input_length + dilated_filter_size - 1 return (output_length + stride - 1) // stride
cds-sorenson-0.1.8
cds-sorenson-0.1.8//cds_sorenson/utils.pyfile:/cds_sorenson/utils.py:function:name_generator/name_generator
def name_generator(master_name, preset): """Generate the output name for slave file. :param master_name: string with the name of the master file. :param preset: dictionary with the preset information. :returns: string with the slave name for this preset. """ return ( '{master_name}-{video_bitrate}-kbps-{width}x{height}-audio-{audio_bitrate}-kbps-stereo.mp4' .format(master_name='master_name', **preset))
luda-0.5.0
luda-0.5.0//luda/luda.pyfile:/luda/luda.py:function:parse_tuple/parse_tuple
def parse_tuple(tuple_string): """ strip any whitespace then outter characters. """ return tuple_string.strip().strip('"[]')
amp-atomistics-0.6.1
amp-atomistics-0.6.1//amp/utilities.pyfile:/amp/utilities.py:function:string2dict/string2dict
def string2dict(text): """Converts a string into a dictionary. Basically just calls `eval` on it, but supplies words like OrderedDict and matrix. """ try: dictionary = eval(text) except NameError: from collections import OrderedDict from numpy import array, matrix dictionary = eval(text) return dictionary
fake-bpy-module-2.79-20200428
fake-bpy-module-2.79-20200428//bpy/ops/console.pyfile:/bpy/ops/console.py:function:execute/execute
def execute(interactive: bool=False): """Execute the current console line as a python expression :param interactive: interactive :type interactive: bool """ pass
BTrees
BTrees//Interfaces.pyclass:IKeyed/keys
def keys(min=None, max=None, excludemin=False, excludemax=False): """Return an :class:`~BTrees.Interfaces.IReadSequence` containing the keys in the collection. The type of the :class:`~BTrees.Interfaces.IReadSequence` is not specified. It could be a list or a tuple or some other type. All arguments are optional, and may be specified as keyword arguments, or by position. If a min is specified, then output is constrained to keys greater than or equal to the given min, and, if excludemin is specified and true, is further constrained to keys strictly greater than min. A min value of None is ignored. If min is None or not specified, and excludemin is true, the smallest key is excluded. If a max is specified, then output is constrained to keys less than or equal to the given max, and, if excludemax is specified and true, is further constrained to keys strictly less than max. A max value of None is ignored. If max is None or not specified, and excludemax is true, the largest key is excluded. """
openpyxl
openpyxl//descriptors/base.pyfile:/descriptors/base.py:function:_convert/_convert
def _convert(expected_type, value): """ Check value is of or can be converted to expected type. """ if not isinstance(value, expected_type): try: value = expected_type(value) except: raise TypeError('expected ' + str(expected_type)) return value
matplotlib
matplotlib//dviread.pyfile:/dviread.py:function:_arg/_arg
def _arg(bytes, signed, dvi, _): """Read *bytes* bytes, returning the bytes interpreted as a signed integer if *signed* is true, unsigned otherwise.""" return dvi._arg(bytes, signed)
dgllife-0.2.2
dgllife-0.2.2//dgllife/utils/featurizers.pyfile:/dgllife/utils/featurizers.py:function:atomic_number/atomic_number
def atomic_number(atom): """Get the atomic number for an atom. Parameters ---------- atom : rdkit.Chem.rdchem.Atom RDKit atom instance. Returns ------- list List containing one int only. See Also -------- atomic_number_one_hot atom_type_one_hot """ return [atom.GetAtomicNum()]
wptools_clone-0.4.19
wptools_clone-0.4.19//scripts/wptool.pyfile:/scripts/wptool.py:function:_image/_image
def _image(page): """ returns (preferred) image from wptools object """ pageimage = page.images(token='pageimage') if pageimage: return pageimage[0]['url']
pshtt
pshtt//pshtt.pyfile:/pshtt.py:function:is_bad_hostname/is_bad_hostname
def is_bad_hostname(domain): """ Domain has a bad hostname if its canonical https endpoint fails hostname validation """ canonical, https, httpswww = (domain.canonical, domain.https, domain. httpswww) if canonical.host == 'www': canonical_https = httpswww else: canonical_https = https return canonical_https.https_bad_hostname
dgl_cu90-0.4.3.post2.data
dgl_cu90-0.4.3.post2.data//purelib/dgl/backend/backend.pyfile:/purelib/dgl/backend/backend.py:function:nonzero_1d/nonzero_1d
def nonzero_1d(input): """Return the nonzero index of the given 1D input. Parameters ---------- input : Tensor Must be a 1D tensor. Returns ------- Tensor A 1D integer tensor containing the nonzero indices. """ pass
SPLAT-library-0.4.4
SPLAT-library-0.4.4//splat/Util.pyfile:/splat/Util.py:function:typify/typify
def typify(tokens): """ Returns a dictionary of unique types with their frequencies. :param tokens:a list of tokens :type tokens:list :return:a dictionary of unique types with their frequencies. :rtype:dict """ temp_types = {} for word in tokens: if word not in temp_types.keys(): temp_types[word] = 1 else: temp_types[word] += 1 return sorted(temp_types.items())
googlemaps-4.3.1
googlemaps-4.3.1//googlemaps/convert.pyfile:/googlemaps/convert.py:function:format_float/format_float
def format_float(arg): """Formats a float value to be as short as possible. Truncates float to 8 decimal places and trims extraneous trailing zeros and period to give API args the best possible chance of fitting within 2000 char URL length restrictions. For example: format_float(40) -> "40" format_float(40.0) -> "40" format_float(40.1) -> "40.1" format_float(40.001) -> "40.001" format_float(40.0010) -> "40.001" format_float(40.000000001) -> "40" format_float(40.000000009) -> "40.00000001" :param arg: The lat or lng float. :type arg: float :rtype: string """ return ('%.8f' % float(arg)).rstrip('0').rstrip('.')
toggl
toggl//api/base.pyclass:TogglEntity/deserialize
@classmethod def deserialize(cls, config=None, **kwargs): """ Method which takes kwargs as dict representing the Entity's data and return actuall instance of the Entity. """ try: kwargs.pop('at') except KeyError: pass instance = cls.__new__(cls) instance._config = config instance.__change_dict__ = {} for key, field in instance.__fields__.items(): try: value = kwargs[key] except KeyError: try: value = kwargs[field.mapped_field] except (KeyError, AttributeError): continue field.init(instance, value) return instance
dsnet
dsnet//base.pyfile:/base.py:function:_common_parser/_common_parser
def _common_parser(): """Returns a parser with common command-line options for all the scripts in the fortpy suite. """ import argparse parser = argparse.ArgumentParser(add_help=False) parser.add_argument('-examples', action='store_true', help= 'See detailed help and examples for this script.') parser.add_argument('-verbose', action='store_true', help= 'See verbose output as the script runs.') parser.add_argument('-action', nargs=1, choices=['save', 'print'], default='print', help= 'Specify what to do with the output (print or save)') parser.add_argument('-debug', action='store_true', help= 'Print verbose calculation information for debugging.') return parser
dozer
dozer//profile.pyfile:/profile.py:function:setup_time/setup_time
def setup_time(t): """Takes a time generally assumed to be quite small and blows it up into millisecond time. For example: 0.004 seconds -> 4 ms 0.00025 seconds -> 0.25 ms The result is returned as a string. """ t = t * 1000 t = '%0.2f' % t return t
RelStorage-3.0.1
RelStorage-3.0.1//src/relstorage/adapters/interfaces.pyclass:IObjectMover/replace_temps
def replace_temps(cursor, state_oid_tid_iter): """ Replace all objects in the temporary table with new data from *state_oid_tid_iter*. This happens after conflict resolution. The param is as for ``store_temps``. Implementations should try to perform this in as few database operations as possible. """
clfsload
clfsload//stypes.pyclass:CommandArgs/_worker_thread_count_effective
@classmethod def _worker_thread_count_effective(cls, count): """ Given a worker thread count, adjust it to our global bounds. """ return min(max(count, cls._WORKER_THREAD_COUNT_MIN), cls. _WORKER_THREAD_COUNT_MAX)
fake-bpy-module-2.80-20200428
fake-bpy-module-2.80-20200428//bpy/ops/view3d.pyfile:/bpy/ops/view3d.py:function:snap_selected_to_grid/snap_selected_to_grid
def snap_selected_to_grid(): """Snap selected item(s) to their nearest grid division """ pass
PROPKA-3.1.0
PROPKA-3.1.0//propka/iterative.pyfile:/propka/iterative.py:function:addIterativeAcidPair/addIterativeAcidPair
def addIterativeAcidPair(object1, object2, interaction): """ Adding the Coulomb 'iterative' interaction (an acid pair): the higher pKa is raised with QQ+HB the lower pKa is lowered with HB """ values = interaction[1] annihilation = interaction[2] hbond_value = values[0] coulomb_value = values[1] diff = coulomb_value + 2 * hbond_value comp1 = object1.pKa_old + annihilation[0] + diff comp2 = object2.pKa_old + annihilation[1] + diff annihilation[0] = 0.0 annihilation[1] = 0.0 if comp1 > comp2: determinant = [object2, hbond_value] object1.determinants['sidechain'].append(determinant) determinant = [object1, -hbond_value] object2.determinants['sidechain'].append(determinant) determinant = [object2, coulomb_value] object1.determinants['coulomb'].append(determinant) annihilation[0] = -diff else: determinant = [object1, hbond_value] object2.determinants['sidechain'].append(determinant) determinant = [object2, -hbond_value] object1.determinants['sidechain'].append(determinant) determinant = [object1, coulomb_value] object2.determinants['coulomb'].append(determinant) annihilation[1] = -diff
formasaurus
formasaurus//html.pyfile:/html.py:function:remove_by_xpath/remove_by_xpath
def remove_by_xpath(tree, xpath): """ Remove all HTML elements which match a given XPath expression. """ for bad in tree.xpath(xpath): bad.getparent().remove(bad)
checkbox-support-0.39.0
checkbox-support-0.39.0//checkbox_support/dbus/udisks2.pyfile:/checkbox_support/dbus/udisks2.py:function:map_udisks1_connection_bus/map_udisks1_connection_bus
def map_udisks1_connection_bus(udisks1_connection_bus): """ Map the value of udisks1 ConnectionBus property to the corresponding values in udisks2. This a lossy function as some values are no longer supported. Incorrect values raise LookupError """ return {'ata_serial_esata': '', 'firewire': 'ieee1394', 'scsi': '', 'sdio': 'sdio', 'usb': 'usb'}[udisks1_connection_bus]
clustergrammer_widget2-0.6.3
clustergrammer_widget2-0.6.3//clustergrammer_widget2/clustergrammer/categories.pyfile:/clustergrammer_widget2/clustergrammer/categories.py:function:check_categories/check_categories
def check_categories(lines): """ find out how many row and col categories are available """ rcat_line = lines[0].split('\t') num_rc = 0 found_end = False for inst_string in rcat_line[1:]: if inst_string == '': if found_end is False: num_rc = num_rc + 1 else: found_end = True max_rcat = 15 if max_rcat > len(lines): max_rcat = len(lines) - 1 num_cc = 0 for i in range(max_rcat): ccat_line = lines[i + 1].split('\t') if ccat_line[0] == '' and len(ccat_line) > 1: num_cc = num_cc + 1 num_labels = {} num_labels['row'] = num_rc + 1 num_labels['col'] = num_cc + 1 return num_labels
enablebanking
enablebanking//models/transaction.pyclass:Transaction/__ne__
def __ne__(A, other): """Returns true if both objects are not equal""" return not A == other
Pytzer-0.4.3
Pytzer-0.4.3//pytzer/parameters.pyfile:/pytzer/parameters.py:function:bC_Na_B4O5OH4_FW86/bC_Na_B4O5OH4_FW86
def bC_Na_B4O5OH4_FW86(T, P): """c-a: sodium tetraborate [FW86].""" b0 = -0.11 b1 = -0.4 b2 = 0 C0 = 0 C1 = 0 alph1 = 2 alph2 = -9 omega = -9 valid = T == 298.15 return b0, b1, b2, C0, C1, alph1, alph2, omega, valid
sage_flatsurf-0.3
sage_flatsurf-0.3//flatsurf/geometry/mega_wollmilchsau.pyclass:MegaWollmilchsauGroupElement/quat_to_tuple
@staticmethod def quat_to_tuple(r): """Convert an element in the quaternion algebra to a quadruple""" if type(r) == type(1): return r, 0, 0, 0 else: return r[0], r[1], r[2], r[3]
pyxsim-2.2.0
pyxsim-2.2.0//versioneer.pyfile:/versioneer.py:function:render_git_describe_long/render_git_describe_long
def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces['closest-tag']: rendered = pieces['closest-tag'] rendered += '-%d-g%s' % (pieces['distance'], pieces['short']) else: rendered = pieces['short'] if pieces['dirty']: rendered += '-dirty' return rendered
flywheel
flywheel//models/session_jobs_output.pyclass:SessionJobsOutput/positional_to_model
@staticmethod def positional_to_model(value): """Converts a positional argument to a model value""" return value
bpy
bpy//ops/paint.pyfile:/ops/paint.py:function:vertex_color_levels/vertex_color_levels
def vertex_color_levels(offset: float=0.0, gain: float=1.0): """Adjust levels of vertex colors :param offset: Offset, Value to add to colors :type offset: float :param gain: Gain, Value to multiply colors by :type gain: float """ pass
fake-blender-api-2.79-0.3.1
fake-blender-api-2.79-0.3.1//bpy/ops/ui.pyfile:/bpy/ops/ui.py:function:reports_to_textblock/reports_to_textblock
def reports_to_textblock(): """Write the reports """ pass
nldsl
nldsl//core/codegen.pyclass:CodeMap/_convert_name
@classmethod def _convert_name(cls, name): """Convert the `name` to a proper function name. Args: name (str): The name to be converted Returns: (tuple) The converted name and the number of tokens """ if name == '': return cls.dynamic_prefix + '_', 0 tokens = name.split() prefix = '' if tokens[0].startswith('_') else '_' return cls.dynamic_prefix + prefix + '_'.join(tokens), len(tokens)
nmmn
nmmn//misc.pyfile:/misc.py:function:findPATH/findPATH
def findPATH(filename, envVar='PYTHONPATH'): """ Given a PATH or PYTHONPATH environment variable, find the full path of a file among different options. From https://stackoverflow.com/a/1124851/793218 :param filename: file for which full path is desired :param envVar: environment variable with path to be searched :returns: string with full path to file Example: >>> fullpath=findPATH("fastregrid.cl") """ import os for p in os.environ[envVar].split(':'): for r, d, f in os.walk(p): for files in f: if files == filename: return os.path.join(r, files)
biocircuits-0.0.16
biocircuits-0.0.16//biocircuits/reg.pyfile:/biocircuits/reg.py:function:ar_and/ar_and
def ar_and(x, y, nx, ny): """Dimensionless production rate for a gene regulated by one activator and one repressor with AND logic in the absence of leakage. Parameters ---------- x : float or NumPy array Concentration of activator. y : float or NumPy array Concentration of repressor. nx : float Hill coefficient for activator. ny : float Hill coefficient for repressor. Returns ------- output : NumPy array or float x**nx / (1 + x**nx + y**ny) """ return x ** nx / (1 + x ** nx + y ** ny)
qal-0.6
qal-0.6//qal/sql/json.pyclass:SQLJSON/json_get_allowed_value
def json_get_allowed_value(_value, _type): """Check if a value is allowed in a certain JSON node""" if _value in _type[1] or _value == '': return _value elif _value[0:8].lower() == 'varchar(' and _value[8:len(_value) - 1 ].isnumeric() and _value[len(_value) - 1] == ')': return _value else: raise Exception('json_get_allowed_value: ' + str(_value) + ' is not a valid value in a ' + _type[0])