repo
stringlengths
1
29
path
stringlengths
24
332
code
stringlengths
39
579k
ipread-0.2.1
ipread-0.2.1//ipread.pyfile:/ipread.py:function:readimg/readimg
def readimg(filename, rows, cols): """ Attempts to read the .img file filename (with or without '.img') assuming it was read with rows rows and cols cols. """ import numpy as np dt = np.dtype(np.uint16) dt = dt.newbyteorder('>') filename = filename if filename.endswith('.img') else filename + '.img' with open(filename, 'rb') as f: ret = np.reshape(np.fromfile(f, dtype=dt), (rows, cols)) return np.array(ret, dtype=np.float64)
pyboto3-1.4.4
pyboto3-1.4.4//pyboto3/ec2.pyfile:/pyboto3/ec2.py:function:describe_key_pairs/describe_key_pairs
def describe_key_pairs(DryRun=None, KeyNames=None, Filters=None): """ Describes one or more of your key pairs. For more information about key pairs, see Key Pairs in the Amazon Elastic Compute Cloud User Guide . See also: AWS API Documentation Examples This example displays the fingerprint for the specified key. Expected Output: :example: response = client.describe_key_pairs( DryRun=True|False, KeyNames=[ 'string', ], Filters=[ { 'Name': 'string', 'Values': [ 'string', ] }, ] ) :type DryRun: boolean :param DryRun: Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . :type KeyNames: list :param KeyNames: One or more key pair names. Default: Describes all your key pairs. (string) -- :type Filters: list :param Filters: One or more filters. fingerprint - The fingerprint of the key pair. key-name - The name of the key pair. (dict) --A filter name and value pair that is used to return a more specific list of results. Filters can be used to match a set of resources by various criteria, such as tags, attributes, or IDs. Name (string) --The name of the filter. Filter names are case-sensitive. Values (list) --One or more filter values. Filter values are case-sensitive. (string) -- :rtype: dict :return: { 'KeyPairs': [ { 'KeyName': 'string', 'KeyFingerprint': 'string' }, ] } """ pass
bitcoincash-0.1.5
bitcoincash-0.1.5//bitcoincash/base58.pyclass:CBase58Data/from_bytes
@classmethod def from_bytes(cls, data, nVersion): """Instantiate from data and nVersion""" if not 0 <= nVersion <= 255: raise ValueError( 'nVersion must be in range 0 to 255 inclusive; got %d' % nVersion) self = bytes.__new__(cls, data) self.nVersion = nVersion return self
matplotlib2tikz
matplotlib2tikz//axes.pyfile:/axes.py:function:_linear_interpolation/_linear_interpolation
def _linear_interpolation(x, X, Y): """Given two data points [X,Y], linearly interpolate those at x. """ return (Y[1] * (x - X[0]) + Y[0] * (X[1] - x)) / (X[1] - X[0])
igraph
igraph//drawing/shapes.pyclass:ShapeDrawer/draw_path
@staticmethod def draw_path(ctx, center_x, center_y, width, height=None): """Draws the path of the shape on the given Cairo context, without stroking or filling it. This method must be overridden in derived classes implementing custom shapes and declared as a static method using C{staticmethod(...)}. @param ctx: the context to draw on @param center_x: the X coordinate of the center of the object @param center_y: the Y coordinate of the center of the object @param width: the width of the object @param height: the height of the object. If C{None}, equals to the width. """ raise NotImplementedError('abstract class')
python-stacktaskclient-0.1.6
python-stacktaskclient-0.1.6//stacktaskclient/openstack/common/cliutils.pyfile:/stacktaskclient/openstack/common/cliutils.py:function:isunauthenticated/isunauthenticated
def isunauthenticated(func): """Checks if the function does not require authentication. Mark such functions with the `@unauthenticated` decorator. :returns: bool """ return getattr(func, 'unauthenticated', False)
fa_convnav
fa_convnav//core.pyfile:/core.py:function:get_row/get_row
def get_row(l, m): """Construct dataframe row from `l` (Learner.named_modules() module) and `m` (model_type)""" lyr_name = l[0] lyr_obj = l[1] ln_split = str(lyr_name).split('.', 4) ln_n_splits = len(ln_split) lyr_str = str(lyr_obj) tch_cls_str = str(type(lyr_obj)) tch_cls_substr = tch_cls_str[tch_cls_str.find('<class') + 8:tch_cls_str .find('>') - 1] tch_cls = tch_cls_substr.split('.')[-1] div = tch_cls if lyr_name == '0' or lyr_name == '1' else '' mod = tch_cls if ln_n_splits == 2 else '' blk = tch_cls if ln_n_splits == 3 and not lyr_name.startswith('1') else '' lyr = lyr_str[:90] if m == 'vgg' or m == 'alexnet': if ln_n_splits > 2: ln_split[2] = '' blk = '' elif m == 'squeezenet': blk = tch_cls if ln_n_splits == 3 and tch_cls == 'Fire' else '' if blk == 'Fire': lyr = '' elif m == 'resnet': if blk == 'BasicBlock' or blk == 'Bottleneck': lyr = '' else: if ln_n_splits > 4: lyr = f'. . {lyr_str[:86]}' if ln_n_splits == 4 and ln_split[3] == 'downsample': lyr = f'Container{tch_cls}' elif m == 'densenet': lyr_name = lyr_name.replace('denseblock', '').replace('denselayer', '') ln_split = str(lyr_name).split('.', 5) if len(ln_split) > 1 and ln_split[0] != '1': del ln_split[1] ln_n_splits = len(ln_split) mod = tch_cls if lyr_name.startswith('0' ) and ln_n_splits == 2 or lyr_name.startswith('1' ) and ln_n_splits == 2 else '' blk = tch_cls if ln_n_splits == 3 and tch_cls == '_DenseLayer' else '' if (mod == '_DenseBlock' or mod == '_Transition' or blk == '_DenseLayer'): lyr = '' else: if lyr_name == '0' or lyr_name == '1': div = tch_cls if lyr_name == '0.0': div = f'. . {tch_cls}' elif m == 'xresnet': blk = tch_cls if ln_n_splits == 3 and tch_cls == 'ResBlock' else '' if mod == 'ConvLayer' or blk == 'ResBlock': lyr = '' elif ln_n_splits < 4: lyr = lyr_str[:90] elif ln_n_splits == 4 and tch_cls == 'Sequential': lyr = f'Container{tch_cls}' elif ln_n_splits == 4 and tch_cls == 'ReLU': lyr = lyr_str[:90] elif ln_n_splits == 5 and tch_cls == 'ConvLayer': lyr = f'. . Container{tch_cls}' else: lyr = f'. . . . {lyr_str[:32]}' else: raise Exception('Model type not recognised') return {'Module_name': lyr_name, 'Model': tch_cls if lyr_name == '' else '', 'Division': div, 'Container_child': mod, 'Container_block': blk, 'Layer_description': lyr, 'Torch_class': tch_cls_substr, 'Output_dimensions': '', 'Parameters': '', 'Trainable': '', 'Currently': '', 'div_id': ln_split[0] if ln_n_splits > 0 else '', 'chd_id': ln_split[1] if ln_n_splits > 1 else '', 'blk_id': ln_split[2] if ln_n_splits > 2 else '', 'lyr_id': ln_split[3] if ln_n_splits > 3 else '', 'tch_cls': tch_cls, 'out_dim': '', 'current': '', 'lyr_blk': '', 'lyr_chd': '', 'blk_chd': '', 'lyr_obj': lyr_obj}
typing_inspect_lib
typing_inspect_lib//core/helpers/helpers.pyfile:/core/helpers/helpers.py:function:safe_getattr_tuple/safe_getattr_tuple
def safe_getattr_tuple(type_, key): """Get attribute from type, defaulting to empty tuple.""" try: return tuple(getattr(type_, key, None) or []) except TypeError: return ()
reproman-0.2.1
reproman-0.2.1//reproman/utils.pyfile:/reproman/utils.py:function:assure_list/assure_list
def assure_list(s): """Given not a list, would place it into a list. If None - empty list is returned Parameters ---------- s: list or anything """ if isinstance(s, list): return s elif s is None: return [] else: return [s]
karaage-6.1.1
karaage-6.1.1//karaage/common/trace.pyfile:/karaage/common/trace.py:function:_formatter_class/_formatter_class
def _formatter_class(name, value): """Format the "klass" variable and value on class methods. """ __mname = value.__module__ if __mname != '__main__': return "%s = <type '%s.%s'>" % (name, __mname, value.__name__) else: return "%s = <type '%s'>" % (name, value.__name__)
nbsite-0.6.7
nbsite-0.6.7//examples/sites/holoviews/holoviews/ipython/preprocessors.pyfile:/examples/sites/holoviews/holoviews/ipython/preprocessors.py:function:replace_line_magic/replace_line_magic
def replace_line_magic(source, magic, template='{line}'): """ Given a cell's source, replace line magics using a formatting template, where {line} is the string that follows the magic. """ filtered = [] for line in source.splitlines(): if line.strip().startswith(magic): substitution = template.format(line=line.replace(magic, '')) filtered.append(substitution) else: filtered.append(line) return '\n'.join(filtered)
epsagon-1.45.2
epsagon-1.45.2//epsagon/modules/urllib3.pyfile:/epsagon/modules/urllib3.py:function:_get_headers_from_args/_get_headers_from_args
def _get_headers_from_args(method=None, url=None, body=None, headers=None, retries=None, redirect=None, assert_same_host=True, timeout=None, pool_timeout=None, release_conn=None, chunked=False, body_pos=None, ** response_kw): """ extract headers from arguments """ return headers
lifelib-0.0.14
lifelib-0.0.14//lifelib/projects/nestedlife/projection.pyfile:/lifelib/projects/nestedlife/projection.py:function:PolsAnnuity/PolsAnnuity
def PolsAnnuity(t): """Number of policies: Annuity""" return 0
cachingproxy-0.1
cachingproxy-0.1//cachingproxy.pyclass:CachingProxy/set_repr_mode
@classmethod def set_repr_mode(cls, mode): """ Set __repr__() mode. There are two modes: REPR_REAL - show real repr() on all CachingProxy instances REPR_FAKE - show the repr() of wrapped object By default, REPR_REAL is used so each cached object will be easily identifieable as such. """ cls.repr_mode = True
vitu-1.1.0
vitu-1.1.0//vitu/utils/trade_utils.pyfile:/vitu/utils/trade_utils.py:function:trade_update_position/trade_update_position
def trade_update_position(current_position, symbol, trade): """ 产生Trade更新对应Postion """ base_currency = symbol.split('/')[0].lower() quote_currency = symbol.split('/')[1].lower() current_position[base_currency].trade_update('base', trade) current_position[quote_currency].trade_update('quote', trade) current_position[base_currency].trade_update_cost('base', trade, current_position[quote_currency]) current_position[quote_currency].trade_update_cost('quote', trade, current_position[base_currency])
tikzplotlib
tikzplotlib//axes.pyfile:/axes.py:function:_try_f2i/_try_f2i
def _try_f2i(x): """If possible, convert float to int without rounding. Used for log base: if not used, base for log scale can be "10.0" (and then printed as such by pgfplots). """ return int(x) if int(x) == x else x
PartSegCore
PartSegCore//io_utils.pyclass:LoadBase/number_of_files
@classmethod def number_of_files(cls): """Number of files required for load method""" return 1
collective.embeddedpage-2.1.1
collective.embeddedpage-2.1.1//src/collective/embeddedpage/setuphandlers.pyfile:/src/collective/embeddedpage/setuphandlers.py:function:post_install/post_install
def post_install(context): """Post install script"""
bpy_nibbler-0.1
bpy_nibbler-0.1//bpy_lambda/2.78/scripts/addons/rigify/legacy/rigs/palm.pyfile:/bpy_lambda/2.78/scripts/addons/rigify/legacy/rigs/palm.py:function:bone_siblings/bone_siblings
def bone_siblings(obj, bone): """ Returns a list of the siblings of the given bone. This requires that the bones has a parent. """ parent = obj.data.bones[bone].parent if parent is None: return [] bones = [] for b in parent.children: if b.name != bone: bones += [b.name] return bones
fake-bpy-module-2.80-20200428
fake-bpy-module-2.80-20200428//bpy/ops/view3d.pyfile:/bpy/ops/view3d.py:function:navigate/navigate
def navigate(): """Interactively navigate around the scene (uses the mode (walk/fly) preference) """ pass
Products.ATSchemaEditorNG-0.6
Products.ATSchemaEditorNG-0.6//Products/ATSchemaEditorNG/interfaces.pyclass:ISchemaEditor/atse_delSchemata
def atse_delSchemata(schema_id, schema_template, name, RESPONSE=None): """ delete a schemata """
pycointools-0.0.1
pycointools-0.0.1//cryptos/electrumx_client/jsonrpc.pyclass:JSONRPCv2/notification_payload
@classmethod def notification_payload(cls, method, params=None): """JSON v2 notification payload. There must be no id.""" payload = {'jsonrpc': '2.0', 'method': method} if params: payload['params'] = params return payload
dolosse
dolosse//hardware/xia/pixie16/list_mode_data_mask.pyclass:ListModeDataMask/header_length
@staticmethod def header_length(): """ Provides the mask needed to decode the header_length from Word 0 """ return 126976, 12
decisiveml
decisiveml//indicators.pyfile:/indicators.py:function:indicator_atr/indicator_atr
def indicator_atr(df, lookback=20): """Creates average true range Args: df (pd.DataFrame): OHLCV intraday dataframe, only needs high, low, close lookback (:obj:int, optional): rolling window. Default is 20 Returns: pd.DataFrame: columns with true_range and atr Example: """ df = df[['high', 'low', 'close']].copy() df['highlow'] = abs(df['high'] - df['low']) df['highclose'] = abs(df['high'] - df['close'].shift(1)) df['lowclose'] = abs(df['low'] - df['close'].shift(1)) df['true_range'] = df[['highlow', 'highclose', 'lowclose']].max(axis=1) df['atr'] = df['true_range'].rolling(lookback).mean() return df[['atr', 'true_range']]
lander
lander//renderer.pyfile:/renderer.py:function:filter_simple_date/filter_simple_date
def filter_simple_date(value): """Filter a `datetime.datetime` into a 'YYYY-MM-DD' string.""" return value.strftime('%Y-%m-%d')
solver-0.0.4
solver-0.0.4//solver/parsing/parser.pyfile:/solver/parsing/parser.py:function:format_fields/format_fields
def format_fields(fields): """ :param fields: list of numbers and operations as strings :return a list of formatted fields, with numbers cast into integers """ leading_sign = '' formatted_fields = [] for field in fields: try: result = int(leading_sign + field) except ValueError: leading_sign = '' if len(field) == 1: result = field elif len(field) == 2: if field == '**': result = field elif field[1] in '+-': result, leading_sign = field else: raise Exception('Invalid operation') elif len(field) == 3: if field[:2] == '**': if field[2] in '+-': result, leading_sign = field[:2], field[2] else: raise Exception('Unsupported operation') formatted_fields.append(result) return formatted_fields
xmsinterp
xmsinterp//interpolate/interp_linear.pyclass:InterpLinear/_check_activity
@staticmethod def _check_activity(activity, _length, _type): """ Verifies that the activity is valid. Args: activity (iterable): Array of activity _length (int): Count of all points _type (string): 'points' or 'triangles' """ if len(activity) != _length: raise ValueError( 'Length of activity must be equal to the length of {}.'.format( _type))
riemann-zeta-6.0.0
riemann-zeta-6.0.0//zeta/utils.pyfile:/zeta/utils.py:function:reverse_hex/reverse_hex
def reverse_hex(h: str): """Reverses a hex-serialized bytestring""" return bytes.fromhex(h)[::-1].hex()
histomicstk
histomicstk//annotations_and_masks/annotation_and_mask_utils.pyfile:/annotations_and_masks/annotation_and_mask_utils.py:function:_get_idxs_for_all_rois/_get_idxs_for_all_rois
def _get_idxs_for_all_rois(GTCodes, element_infos): """Get indices of ROIs within the element_infos dataframe. (Internal) """ roi_labels = list(GTCodes.loc[GTCodes.loc[:, ('is_roi')] == 1, 'group']) idxs_for_all_rois = [] for idx, elinfo in element_infos.iterrows(): if elinfo.group in roi_labels: idxs_for_all_rois.append(idx) return idxs_for_all_rois
RO-3.6.9
RO-3.6.9//python/RO/StringUtil.pyfile:/python/RO/StringUtil.py:function:plural/plural
def plural(num, singStr, plStr): """Return singStr or plStr depending if num == 1 or not. A minor convenience for formatting messages (in lieu of ?: notation) """ if num == 1: return singStr return plStr
knot_pull-0.4.1
knot_pull-0.4.1//knot_pull/dowker_code_new.pyfile:/knot_pull/dowker_code_new.py:function:index/index
def index(lista, co): """.index with on absolute values""" for i in range(len(lista)): if abs(lista[i]) == co: return i else: raise IndexError
emirdrp
emirdrp//processing/bardetect.pyfile:/processing/bardetect.py:function:overlap/overlap
def overlap(intv1, intv2): """Overlaping of two intervals""" return max(0, min(intv1[1], intv2[1]) - max(intv1[0], intv2[0]))
django-actions-logger-0.3.1
django-actions-logger-0.3.1//actionslog/diff.pyfile:/actionslog/diff.py:function:track_field/track_field
def track_field(field): """ Returns whether the given field should be tracked by Actionslog. Untracked fields are many-to-many relations and relations to the Actionslog LogAction model. :param field: The field to check. :type field: Field :return: Whether the given field should be tracked. :rtype: bool """ from actionslog.models import LogAction if field.many_to_many: return False if getattr(field, 'rel', None) is not None and field.rel.to == LogAction: return False return True
sklearn
sklearn//feature_extraction/_hash.pyfile:/feature_extraction/_hash.py:function:_iteritems/_iteritems
def _iteritems(d): """Like d.iteritems, but accepts any collections.Mapping.""" return d.iteritems() if hasattr(d, 'iteritems') else d.items()
audio.wave-4.0.2
audio.wave-4.0.2//.lib/pkg_resources.pyclass:IResourceProvider/resource_isdir
def resource_isdir(resource_name): """Is the named resource a directory? (like ``os.path.isdir()``)"""
yasfb-0.8.0
yasfb-0.8.0//yasfb/formatter.pyfile:/yasfb/formatter.py:function:_atomise_link/_atomise_link
def _atomise_link(link, rel=None): """Return a link in a suitable format for atom""" if type(link) is dict: if 'type' not in link: link['type'] = 'text/html' if rel and 'rel' not in link: link['rel'] = rel return link else: result = {'href': link, 'type': 'text/html'} if rel: result['rel'] = rel return result
tpDcc-core-0.0.11
tpDcc-core-0.0.11//tpDcc/abstract/dcc.pyclass:AbstractDCC/get_dockable_window_class
@staticmethod def get_dockable_window_class(): """ Returns class that should be used to instance an ew dockable DCC window :return: class """ try: from tpDcc.libs.qt.core import window return window.MainWindow except Exception: pass return None
fake-bpy-module-2.80-20200428
fake-bpy-module-2.80-20200428//bpy/ops/outliner.pyfile:/bpy/ops/outliner.py:function:collection_holdout_set/collection_holdout_set
def collection_holdout_set(): """Mask collection in the active view layer """ pass
utilities-package-0.0.8
utilities-package-0.0.8//utilitiespackage/standard/list_.pyfile:/utilitiespackage/standard/list_.py:function:iterate_items/iterate_items
def iterate_items(dictish): """ Return a consistent (key, value) iterable on dict-like objects, including lists of tuple pairs. Example: >>> list(iterate_items({'a': 1})) [('a', 1)] >>> list(iterate_items([('a', 1), ('b', 2)])) [('a', 1), ('b', 2)] """ if hasattr(dictish, 'iteritems'): return dictish.iteritems() if hasattr(dictish, 'items'): return dictish.items() return dictish
dns-lexicon-3.3.22
dns-lexicon-3.3.22//lexicon/providers/namecheap.pyfile:/lexicon/providers/namecheap.py:function:provider_parser/provider_parser
def provider_parser(subparser): """Configure provider parser for Namecheap""" subparser.add_argument('--auth-token', help= 'specify api token for authentication') subparser.add_argument('--auth-username', help= 'specify username for authentication') subparser.add_argument('--auth-client-ip', help= 'Client IP address to send to Namecheap API calls', default='127.0.0.1' ) subparser.add_argument('--auth-sandbox', help= 'Whether to use the sandbox server', action='store_true')
mezzanine-references-0.1.5
mezzanine-references-0.1.5//mezzanine_references/.ropeproject/config.pyfile:/mezzanine_references/.ropeproject/config.py:function:set_prefs/set_prefs
def set_prefs(prefs): """This function is called before opening the project""" prefs['ignored_resources'] = ['*.pyc', '*~', '.ropeproject', '.hg', '.svn', '_svn', '.git'] prefs['save_objectdb'] = True prefs['compress_objectdb'] = False prefs['automatic_soa'] = True prefs['soa_followed_calls'] = 0 prefs['perform_doa'] = True prefs['validate_objectdb'] = True prefs['max_history_items'] = 32 prefs['save_history'] = True prefs['compress_history'] = False prefs['indent_size'] = 4 prefs['extension_modules'] = [] prefs['import_dynload_stdmods'] = True prefs['ignore_syntax_errors'] = False prefs['ignore_bad_imports'] = False
dgl-0.4.3.post2.data
dgl-0.4.3.post2.data//purelib/dgl/backend/backend.pyfile:/purelib/dgl/backend/backend.py:function:swapaxes/swapaxes
def swapaxes(input, axis1, axis2): """Interchange the two given axes of a tensor. Parameters ---------- input : Tensor The input tensor. axis1, axis2 : int The two axes. Returns ------- Tensor The transposed tensor. """ pass
cc-agency-9.1.0
cc-agency-9.1.0//cc_agency/controller/docker.pyclass:ClientProxy/_get_image_url
@staticmethod def _get_image_url(experiment): """ Gets the url of the docker image for the given experiment :param experiment: The experiment whose docker image url is returned :type experiment: Dict :return: The url of the docker image for the given experiment """ return experiment['container']['settings']['image']['url']
ocw-1.3.0
ocw-1.3.0//ocw/utils.pyfile:/ocw/utils.py:function:reshape_monthly_to_annually/reshape_monthly_to_annually
def reshape_monthly_to_annually(dataset): """ Reshape monthly binned dataset to annual bins. Reshape a monthly binned dataset's 3D value array with shape (num_months, num_lats, num_lons) to a 4D array with shape (num_years, 12, num_lats, num_lons). This causes the data to be binned annually while retaining its original shape. It is assumed that the number of months in the dataset is evenly divisible by 12. If it is not you will receive error due to an invalid shape. Example change of a dataset's shape: (24, 90, 180) -> (2, 12, 90, 180) :param dataset: Dataset object with full-year format :type dataset: :class:`dataset.Dataset` :returns: Dataset values array with shape (num_year, 12, num_lat, num_lon) """ values = dataset.values[:] data_shape = values.shape num_total_month = data_shape[0] num_year = num_total_month // 12 if num_total_month % 12 != 0: raise ValueError( 'Number of months in dataset ({}) does not divide evenly into {} year(s).' .format(num_total_month, num_year)) num_month = 12 year_month_shape = num_year, num_month lat_lon_shape = data_shape[1:] new_shape = tuple(year_month_shape + lat_lon_shape) values.shape = new_shape return values
dropbox-10.1.2
dropbox-10.1.2//dropbox/team_log.pyclass:EventDetails/binder_reorder_page_details
@classmethod def binder_reorder_page_details(cls, val): """ Create an instance of this class set to the ``binder_reorder_page_details`` tag with value ``val``. :param BinderReorderPageDetails val: :rtype: EventDetails """ return cls('binder_reorder_page_details', val)
geosoft
geosoft//gxpy/utility.pyfile:/gxpy/utility.py:function:_temp_dict_file_name/_temp_dict_file_name
def _temp_dict_file_name(): """Name of the expected python dictionary as a json file from run_external_python(). .. versionadded:: 9.1 """ return '__shared_dictionary__'
lazyxml
lazyxml//parser.pyclass:Parser/parse
@classmethod def parse(cls, element): """Parse xml element. :param element: an :class:`~xml.etree.ElementTree.Element` instance :rtype: dict """ values = {} for child in element: node = cls.get_node(child) subs = cls.parse(child) value = subs or node['value'] if node['tag'] not in values: values[node['tag']] = value else: if not isinstance(values[node['tag']], list): values[node['tag']] = [values.pop(node['tag'])] values[node['tag']].append(value) return values
arkid_client
arkid_client//base.pyfile:/base.py:function:slash_join/slash_join
def slash_join(base: str, path: str): """ Join a and b with a single slash, regardless of whether they already contain a trailing/leading slash or neither. :param base: base_url :param path: path """ if not path: return base path = path if path.endswith('/') else '{}/'.format(path) if base.endswith('/'): if path.startswith('/'): return base[:-1] + path return base + path if path.startswith('/'): return base + path return base + '/' + path
django-wikidata-api-0.0.11
django-wikidata-api-0.0.11//django_wikidata_api/utils.pyfile:/django_wikidata_api/utils.py:function:is_private_name/is_private_name
def is_private_name(name_string): """ Check if this string is written in a private/protected reference python convention Args: name_string (str): Returns (Bool): True if variable begins with "_", False otherwise Examples: >>> is_private_name("_some_var_name") True >>> is_private_name("some_var_name") False """ return name_string.startswith('_')
tipboard2.0-2.0.6
tipboard2.0-2.0.6//src/tipboard/app/utils.pyfile:/src/tipboard/app/utils.py:function:validate_post_request/validate_post_request
def validate_post_request(post_field, allowed_fields): """ Validators returning None if everything is OK - otherwise suitable HTTP status and message is set. """ error_msg = None dict_diff = list(set(post_field) - set(allowed_fields)) if dict_diff: error_msg = 'There are fields not allowed in your request.' for field in allowed_fields: if field not in post_field.keys(): error_msg = "There is no '{}' field in your request.".format(field) break return error_msg
databroker
databroker//utils.pyfile:/utils.py:function:catalog_search_path/catalog_search_path
def catalog_search_path(): """ List directories that will be searched for catalog YAML files. This is a convenience wrapper around functions used by intake to determine its search path. Returns ------- directories: tuple """ from intake.catalog.default import user_data_dir, global_data_dir return user_data_dir(), global_data_dir()
steuer-0.2.2
steuer-0.2.2//src/steuer/examples/moveblock_poll/example_poll.pyfile:/src/steuer/examples/moveblock_poll/example_poll.py:function:on_start_configuration/on_start_configuration
@classmethod def on_start_configuration(cls): """ Callback function that is triggered, when the configuration of all undetected controllers starts """ print('EVENT:' + 'Start configuration of unknown controller types')
fake-bpy-module-2.80-20200428
fake-bpy-module-2.80-20200428//bgl.pyfile:/bgl.py:function:glLineWidth/glLineWidth
def glLineWidth(width: float): """Specify the width of rasterized lines. :param width: Specifies the width of rasterized lines. The initial value is 1. :type width: float """ pass
python-docx-docm-0.1.0
python-docx-docm-0.1.0//docx/image/jpeg.pyclass:_SofMarker/from_stream
@classmethod def from_stream(cls, stream, marker_code, offset): """ Return an |_SofMarker| instance for the SOFn marker at *offset* in stream. """ segment_length = stream.read_short(offset) px_height = stream.read_short(offset, 3) px_width = stream.read_short(offset, 5) return cls(marker_code, offset, segment_length, px_width, px_height)
xraylarch-0.9.47
xraylarch-0.9.47//larch/xafs/mback.pyfile:/larch/xafs/mback.py:function:f2norm/f2norm
def f2norm(params, en=1, mu=1, f2=1, weights=1): """ Objective function for matching mu(E) data to tabulated f''(E) """ p = params.valuesdict() model = (p['offset'] + p['slope'] * en + f2) * p['scale'] return weights * (model - mu)
anafit
anafit//utilities.pyfile:/utilities.py:function:str_line/str_line
def str_line(lin): """ Returns a string in the form 'marker' + 'linestyle' from a matplotlib.lines.line2D object Parameters ---------- lin : matplotlib.lines.line2D object Returns ---------- strlin: str string in the form 'marker' + 'linestyle' """ strlin = '' if lin.get_marker() is not 'None': strlin = strlin + lin.get_marker() if lin.get_linestyle() is not 'None': strlin = strlin + lin.get_linestyle() return strlin
pluggdapps-0.43dev
pluggdapps-0.43dev//pluggdapps/interfaces.pyclass:IScaffold/printhelp
def printhelp(): """If executed in command line, provide a meaning full description about this scaffolding plugin and variables that can be defined."""
markdownx
markdownx//utils.pyfile:/utils.py:function:_crop/_crop
def _crop(im, target_x, target_y): """ Crops the image to the given specifications. :param im: Instance of the image. :type im: PIL Image :param target_x: New x-axis. :type target_x: int :param target_y: New y-axis :type target_y: int :return: Cropped image. :rtype: PIL.Image """ source_x, source_y = im.size diff_x = int(source_x - min(source_x, target_x)) diff_y = int(source_y - min(source_y, target_y)) if diff_x or diff_y: halfdiff_x, halfdiff_y = diff_x // 2, diff_y // 2 box = [halfdiff_x, halfdiff_y, min(source_x, int(target_x) + halfdiff_x), min(source_y, int(target_y) + halfdiff_y)] im = im.crop(box) return im
pyboto3-1.4.4
pyboto3-1.4.4//pyboto3/cloudwatchlogs.pyfile:/pyboto3/cloudwatchlogs.py:function:put_destination/put_destination
def put_destination(destinationName=None, targetArn=None, roleArn=None): """ Creates or updates a destination. A destination encapsulates a physical resource (such as a Kinesis stream) and enables you to subscribe to a real-time stream of log events of a different account, ingested using PutLogEvents . Currently, the only supported physical resource is a Amazon Kinesis stream belonging to the same account as the destination. A destination controls what is written to its Amazon Kinesis stream through an access policy. By default, PutDestination does not set any access policy with the destination, which means a cross-account user cannot call PutSubscriptionFilter against this destination. To enable this, the destination owner must call PutDestinationPolicy after PutDestination . See also: AWS API Documentation :example: response = client.put_destination( destinationName='string', targetArn='string', roleArn='string' ) :type destinationName: string :param destinationName: [REQUIRED] A name for the destination. :type targetArn: string :param targetArn: [REQUIRED] The ARN of an Amazon Kinesis stream to deliver matching log events to. :type roleArn: string :param roleArn: [REQUIRED] The ARN of an IAM role that grants CloudWatch Logs permissions to call Amazon Kinesis PutRecord on the destination stream. :rtype: dict :return: { 'destination': { 'destinationName': 'string', 'targetArn': 'string', 'roleArn': 'string', 'accessPolicy': 'string', 'arn': 'string', 'creationTime': 123 } } """ pass
fake-bpy-module-2.78-20200428
fake-bpy-module-2.78-20200428//blf.pyfile:/blf.py:function:shadow_offset/shadow_offset
def shadow_offset(fontid: int, x: float, y: float): """Set the offset for shadow text. :param fontid: The id of the typeface as returned by blf.load(), for default font use 0. :type fontid: int :param x: Vertical shadow offset value in pixels. :type x: float :param y: Horizontal shadow offset value in pixels. :type y: float """ pass
programs
programs//conversion_scripts/cit_magic.pyfile:/conversion_scripts/cit_magic.py:function:do_help/do_help
def do_help(): """ returns help string of script """ return __doc__
quantum-grove-1.7.0
quantum-grove-1.7.0//grove/measurements/term_grouping.pyfile:/grove/measurements/term_grouping.py:function:diagonal_basis_commutes/diagonal_basis_commutes
def diagonal_basis_commutes(pauli_a, pauli_b): """ Test if `pauli_a` and `pauli_b` share a diagonal basis Example: Check if [A, B] with the constraint that A & B must share a one-qubit diagonalizing basis. If the inputs were [sZ(0), sZ(0) * sZ(1)] then this function would return True. If the inputs were [sX(5), sZ(4)] this function would return True. If the inputs were [sX(0), sY(0) * sZ(2)] this function would return False. :param pauli_a: Pauli term to check commutation against `pauli_b` :param pauli_b: Pauli term to check commutation against `pauli_a` :return: Boolean of commutation result :rtype: Bool """ overlapping_active_qubits = set(pauli_a.get_qubits()) & set(pauli_b. get_qubits()) for qubit_index in overlapping_active_qubits: if pauli_a[qubit_index] != 'I' and pauli_b[qubit_index ] != 'I' and pauli_a[qubit_index] != pauli_b[qubit_index]: return False return True
reportlab-3.5.42
reportlab-3.5.42//src/reportlab/platypus/paragraph.pyfile:/src/reportlab/platypus/paragraph.py:function:imgVRange/imgVRange
def imgVRange(h, va, fontSize): """return bottom,top offsets relative to baseline(0)""" if va == 'baseline': iyo = 0 elif va in ('text-top', 'top'): iyo = fontSize - h elif va == 'middle': iyo = fontSize - (1.2 * fontSize + h) * 0.5 elif va in ('text-bottom', 'bottom'): iyo = fontSize - 1.2 * fontSize elif va == 'super': iyo = 0.5 * fontSize elif va == 'sub': iyo = -0.5 * fontSize elif hasattr(va, 'normalizedValue'): iyo = va.normalizedValue(fontSize) else: iyo = va return iyo, iyo + h
fake-bpy-module-2.79-20200428
fake-bpy-module-2.79-20200428//bpy/ops/paint.pyfile:/bpy/ops/paint.py:function:vertex_color_smooth/vertex_color_smooth
def vertex_color_smooth(): """Smooth colors across vertices """ pass
pygerduty
pygerduty//common.pyfile:/common.py:function:_singularize/_singularize
def _singularize(string): """Hacky singularization function.""" if string.endswith('ies'): return string[:-3] + 'y' if string.endswith('s'): return string[:-1] return string
webbpsf-0.9.0
webbpsf-0.9.0//astropy_helpers/astropy_helpers/utils.pyfile:/astropy_helpers/astropy_helpers/utils.py:function:get_numpy_include_path/get_numpy_include_path
def get_numpy_include_path(): """ Gets the path to the numpy headers. """ import builtins if hasattr(builtins, '__NUMPY_SETUP__'): del builtins.__NUMPY_SETUP__ import imp import numpy imp.reload(numpy) try: numpy_include = numpy.get_include() except AttributeError: numpy_include = numpy.get_numpy_include() return numpy_include
RelStorage-3.0.1
RelStorage-3.0.1//src/relstorage/adapters/sql/interfaces.pyclass:ITypedParams/datatypes_for_parameters
def datatypes_for_parameters(): """ Returns a sequence of datatypes. XXX: This only works for ordered params; make this work for named parameters. Probably want to treat the two the same, with ordered parameters using indexes as their name. """
und_microservice
und_microservice//helper/url.pyfile:/helper/url.py:function:get_filter_in/get_filter_in
def get_filter_in(filters): """Recuperar filtros de una lista""" filter_in = {} for filter_index, value in list(filters.items()): if isinstance(value, list): filter_in.update({filter_index: value}) del filters[filter_index] return filter_in
dql-0.5.28
dql-0.5.28//dql/expressions/constraint.pyclass:Conjunction/and_
@classmethod def and_(cls, constraints): """ Factory for a group AND """ return cls._factory(constraints, 'AND')
odahu-flow-sdk-1.1.2
odahu-flow-sdk-1.1.2//odahuflow/sdk/models/util.pyfile:/odahuflow/sdk/models/util.py:function:deserialize_date/deserialize_date
def deserialize_date(string): """Deserializes string to date. :param string: str. :type string: str :return: date. :rtype: date """ try: from dateutil.parser import parse return parse(string).date() except ImportError: return string
Jinja2-2.11.2
Jinja2-2.11.2//src/jinja2/environment.pyclass:Template/from_code
@classmethod def from_code(cls, environment, code, globals, uptodate=None): """Creates a template object from compiled code and the globals. This is used by the loaders and environment to create a template object. """ namespace = {'environment': environment, '__file__': code.co_filename} exec(code, namespace) rv = cls._from_namespace(environment, namespace, globals) rv._uptodate = uptodate return rv
farmfs-0.8.0
farmfs-0.8.0//farmfs/ui.pyfile:/farmfs/ui.py:function:reverse/reverse
def reverse(vol, csum): """Yields a set of paths which reference a given checksum_path name."""
json_syntax
json_syntax//action_v1.pyfile:/action_v1.py:function:convert_timedelta_str/convert_timedelta_str
def convert_timedelta_str(dur): """Barebones support for storing a timedelta as an ISO8601 duration.""" micro = '.{:06d}'.format(dur.microseconds) if dur.microseconds else '' return 'P{:d}DT{:d}{}S'.format(dur.days, dur.seconds, micro)
cytoflow-1.0
cytoflow-1.0//cytoflow/utility/util_functions.pyfile:/cytoflow/utility/util_functions.py:function:is_numeric/is_numeric
def is_numeric(s): """ Determine if a ``pandas.Series`` or ``numpy.ndarray`` is numeric from its dtype. """ return s.dtype.kind in 'iufc'
myo-python-1.0.4
myo-python-1.0.4//myo/macaddr.pyfile:/myo/macaddr.py:function:decode/decode
def decode(bstr): """ Decodes an ASCII encoded binary MAC address tring into a number. """ bstr = bstr.replace(b':', b'') if len(bstr) != 12: raise ValueError('not a valid MAC address: {!r}'.format(bstr)) try: return int(bstr, 16) except ValueError: raise ValueError('not a valid MAC address: {!r}'.format(bstr))
onnxconverter_common
onnxconverter_common//utils.pyfile:/utils.py:function:caffe2_installed/caffe2_installed
def caffe2_installed(): """ Checks that *caffe* is available. """ try: import caffe2 return True except ImportError: return False
hazelcast
hazelcast//util.pyfile:/util.py:function:check_not_empty/check_not_empty
def check_not_empty(collection, message): """ Tests if a collection is not empty. :param collection: (Collection), the collection tested to see if it is not empty. :param message: (str), the error message. """ if not collection: raise AssertionError(message)
omero-forms-1.1.0
omero-forms-1.1.0//omero_forms/utils.pyfile:/omero_forms/utils.py:function:_build_assignment_lookup/_build_assignment_lookup
def _build_assignment_lookup(annos): """ Builds a lookup as a dictionary of formIds to groupId lists """ _assignments = {} if annos is not None: for anno in annos: _form_id = None _group_id = None kvs = anno.getMapValue() for kv in kvs: if kv.name == 'formId': _form_id = kv.value elif kv.name == 'groupId': _group_id = kv.value _assignments.setdefault(_form_id, set()).add(int(_group_id)) return _assignments
igraph
igraph//drawing/shapes.pyclass:RectangleDrawer/intersection_point
@staticmethod def intersection_point(center_x, center_y, source_x, source_y, width, height=None): """Determines where the rectangle centered at (center_x, center_y) having the given width and height intersects with a line drawn from (source_x, source_y) to (center_x, center_y). @see: ShapeDrawer.intersection_point""" height = height or width delta_x, delta_y = center_x - source_x, center_y - source_y if delta_x == 0 and delta_y == 0: return center_x, center_y if delta_y > 0 and delta_x <= delta_y and delta_x >= -delta_y: ry = center_y - height / 2 ratio = height / 2 / delta_y return center_x - ratio * delta_x, ry if delta_y < 0 and delta_x <= -delta_y and delta_x >= delta_y: ry = center_y + height / 2 ratio = height / 2 / -delta_y return center_x - ratio * delta_x, ry if delta_x > 0 and delta_y <= delta_x and delta_y >= -delta_x: rx = center_x - width / 2 ratio = width / 2 / delta_x return rx, center_y - ratio * delta_y if delta_x < 0 and delta_y <= -delta_x and delta_y >= delta_x: rx = center_x + width / 2 ratio = width / 2 / -delta_x return rx, center_y - ratio * delta_y if delta_x == 0: if delta_y > 0: return center_x, center_y - height / 2 return center_x, center_y + height / 2 if delta_y == 0: if delta_x > 0: return center_x - width / 2, center_y return center_x + width / 2, center_y
ice.control-0.4.0
ice.control-0.4.0//src/ice/control/controls/tree/interfaces.pyclass:IXML/length
def length(): """Return unicode string with number of children to display in tree or empty string"""
plone.app.portlets-4.4.5
plone.app.portlets-4.4.5//plone/app/portlets/interfaces.pyclass:IDeferredPortletRenderer/deferred_update
def deferred_update(): """refresh portlet data on KSS events (and only then) this is similar to update() but it is only called from a KSS action and thus can be used to do long computing/retrieval only on loading the portlet via KSS but not in the initial page load. """
fake-blender-api-2.79-0.3.1
fake-blender-api-2.79-0.3.1//bpy/ops/image.pyfile:/bpy/ops/image.py:function:view_zoom/view_zoom
def view_zoom(factor: float=0.0): """Zoom in/out the image :param factor: Factor, Zoom factor, values higher than 1.0 zoom in, lower values zoom out :type factor: float """ pass
audio.coders-4.0.2
audio.coders-4.0.2//.lib/pkg_resources.pyclass:IResourceProvider/get_resource_filename
def get_resource_filename(manager, resource_name): """Return a true filesystem path for `resource_name` `manager` must be an ``IResourceManager``"""
touchdown
touchdown//aws/route53/zone.pyfile:/aws/route53/zone.py:function:_normalize/_normalize
def _normalize(dns_name): """ The Amazon Route53 API silently accepts 'foo.com' as a dns record, but internally that becomes 'foo.com.'. In order to match records we need to do the same. """ return dns_name.rstrip('.') + '.'
robottelo
robottelo//cli/usergroup.pyclass:UserGroup/remove_role
@classmethod def remove_role(cls, options=None): """Remove a user role. Usage: hammer user-group remove-role [OPTIONS] Options: --id ID --name NAME Name to search by --role ROLE_NAME User role name --role-id ROLE_ID """ cls.command_sub = 'remove-role' return cls.execute(cls._construct_command(options), output_format='csv')
texfigure-0.1
texfigure-0.1//astropy_helpers/astropy_helpers/sphinx/ext/traitsdoc.pyfile:/astropy_helpers/astropy_helpers/sphinx/ext/traitsdoc.py:function:looks_like_issubclass/looks_like_issubclass
def looks_like_issubclass(obj, classname): """ Return True if the object has a class or superclass with the given class name. Ignores old-style classes. """ t = obj if t.__name__ == classname: return True for klass in t.__mro__: if klass.__name__ == classname: return True return False
art
art//art.pyfile:/art.py:function:distance_calc/distance_calc
def distance_calc(s1, s2): """ Calculate Levenshtein distance between two words. :param s1: first word :type s1 : str :param s2: second word :type s2 : str :return: distance between two word References : 1- https://stackoverflow.com/questions/2460177/edit-distance-in-python 2- https://en.wikipedia.org/wiki/Levenshtein_distance """ if len(s1) > len(s2): s1, s2 = s2, s1 distances = range(len(s1) + 1) for i2, c2 in enumerate(s2): distances_ = [i2 + 1] for i1, c1 in enumerate(s1): if c1 == c2: distances_.append(distances[i1]) else: distances_.append(1 + min((distances[i1], distances[i1 + 1], distances_[-1]))) distances = distances_ return distances[-1]
mxnet-1.6.0.data
mxnet-1.6.0.data//purelib/mxnet/_numpy_op_doc.pyfile:/purelib/mxnet/_numpy_op_doc.py:function:_npx_nonzero/_npx_nonzero
def _npx_nonzero(a): """ Return the indices of the elements that are non-zero. Returns a ndarray with ndim is 2. Each row contains the indices of the non-zero elements. The values in `a` are always tested and returned in row-major, C-style order. The result of this is always a 2-D array, with a row for each non-zero element. Parameters ---------- a : array_like Input array. Returns ------- array : ndarray Indices of elements that are non-zero. Notes ----- This function differs from the original numpy.nonzero in the following aspects: - Does not support python numeric. - The return value is same as numpy.transpose(numpy.nonzero(a)). Examples -------- >>> x = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]]) >>> x array([[3, 0, 0], [0, 4, 0], [5, 6, 0]]) >>> npx.nonzero(x) array([[0, 0], [1, 1], [2, 0], [2, 1]], dtype=int64) >>> np.transpose(npx.nonzero(x)) array([[0, 1, 2, 2], [0, 1, 0, 1]], dtype=int64) """ pass
model-describer-0.1.2.2
model-describer-0.1.2.2//mdesc/utils/check_utils.pyclass:CheckInputs/is_regression
@staticmethod def is_regression(modelobj): """ determined whether users modelobj is regression or classification based on presence of predict_proba :param modelobj: sklearn model object :return: sklearn predict method, str classification type :rtype: sklearn predict, str """ if hasattr(modelobj, 'predict_proba'): predict_engine = getattr(modelobj, 'predict_proba') model_type = 'classification' else: predict_engine = getattr(modelobj, 'predict') model_type = 'regression' return predict_engine, model_type
mercurial-5.4
mercurial-5.4//mercurial/interfaces/repository.pyclass:imanifeststorage/clearcaches
def clearcaches(clear_persisted_data=False): """Clear any caches associated with this instance."""
tellsticknet-0.1.2
tellsticknet-0.1.2//tellsticknet/protocols/oregon.pyfile:/tellsticknet/protocols/oregon.py:function:decode/decode
def decode(packet): """ https://raw.githubusercontent.com/telldus/telldus/master/telldus-core/service/ProtocolOregon.cpp >>> decode(dict(data=0x201F242450443BDD, model=6701))["data"]["temp"] 24.2 >>> decode(dict(data=0x201F242450443BDD, model=6701))["data"]["humidity"] 45.0 """ if packet['model'] != 6701: raise NotImplementedError('The Oregon model %i is not implemented.' % packet['model']) data = packet['data'] value = int(data) value >>= 8 checksum1 = value & 255 value >>= 8 checksum = (value >> 4 & 15) + (value & 15) hum1 = value & 15 value >>= 8 checksum += (value >> 4 & 15) + (value & 15) neg = value & 1 << 3 hum2 = value >> 4 & 15 value >>= 8 checksum += (value >> 4 & 15) + (value & 15) temp2 = value & 15 temp1 = value >> 4 & 15 value >>= 8 checksum += (value >> 4 & 15) + (value & 15) temp3 = value >> 4 & 15 value >>= 8 checksum += (value >> 4 & 15) + (value & 15) address = value & 255 value >>= 8 checksum += (value >> 4 & 15) + (value & 15) checksum += 1 + 10 + 2 + 13 - 10 if checksum != checksum1: raise ValueError( 'The checksum in the Oregon packet does not match the caluclated one!' ) temperature = (temp1 * 100 + temp2 * 10 + temp3) / 10.0 if neg: temperature = -temperature humidity = hum1 * 10.0 + hum2 return dict(packet, sensorId=address, data=dict(temp=temperature, humidity=humidity))
galaxy
galaxy//tool_util/linters/inputs.pyfile:/tool_util/linters/inputs.py:function:lint_repeats/lint_repeats
def lint_repeats(tool_xml, lint_ctx): """Lint repeat blocks in tool inputs.""" repeats = tool_xml.findall('./inputs//repeat') for repeat in repeats: if 'name' not in repeat.attrib: lint_ctx.error('Repeat does not specify name attribute.') if 'title' not in repeat.attrib: lint_ctx.error('Repeat does not specify title attribute.')
python_ta
python_ta//typecheck/base.pyfile:/typecheck/base.py:function:op_to_dunder_binary/op_to_dunder_binary
def op_to_dunder_binary(op: str) ->str: """Return the dunder method name corresponding to binary op.""" if op == '+': return '__add__' elif op == '-': return '__sub__' elif op == '*': return '__mul__' elif op == '//': return '__idiv__' elif op == '%': return '__mod__' elif op == '/': return '__div__' elif op == '**': return '__pow__' elif op == '&': return '__and__' elif op == '^': return '__xor__' elif op == '|': return '__or__' elif op == '==': return '__eq__' elif op == '!=': return '__ne__' elif op == '<': return '__lt__' elif op == '<=': return '__le__' elif op == '>': return '__gt__' elif op == '>=': return '__ge__' else: return op
wish-facebook-6.0.6
wish-facebook-6.0.6//open_facebook/utils.pyfile:/open_facebook/utils.py:function:import_statsd/import_statsd
def import_statsd(): """ Import only the statd by wolph not the mozilla statsd TODO: Move to mozilla statds which is more widely used """ try: import django_statsd is_wolphs_statsd = hasattr(django_statsd, 'start') and hasattr( django_statsd, 'stop') if not is_wolphs_statsd: django_statsd = None except ImportError: django_statsd = None return django_statsd
odinweb-0.5.2
odinweb-0.5.2//odinweb/helpers.pyfile:/odinweb/helpers.py:function:parse_content_type/parse_content_type
def parse_content_type(value): """ Parse out the content type from a content type header. >>> parse_content_type('application/json; charset=utf8') 'application/json' """ if not value: return '' return value.split(';')[0].strip()
flatlib-0.2.1
flatlib-0.2.1//flatlib/dignities/accidental.pyfile:/flatlib/dignities/accidental.py:function:viaCombusta/viaCombusta
def viaCombusta(obj): """ Returns if an object is in the Via Combusta. """ return 195 < obj.lon < 225
madrigalWeb-3.1.12
madrigalWeb-3.1.12//madrigalWeb/globalDownload.pyfile:/madrigalWeb/globalDownload.py:function:getTimesOfExperiment/getTimesOfExperiment
def getTimesOfExperiment(expList, expId): """getTimesOfExperiment returns a list of the start and end time of the experiment given expId. Input: expList - the list of MadrigalExperiment objects expId - the experiment id Returns: a list of: (startyear, startmonth, startday, starthour, startmin, startsec, endyear, endmonth, endday, endhour, endmin, endsec) """ retList = None for exp in expList: if exp.id == expId: retList = (exp.startyear, exp.startmonth, exp.startday, exp. starthour, exp.startmin, exp.startsec, exp.endyear, exp. endmonth, exp.endday, exp.endhour, exp.endmin, exp.endsec) return retList
larray-0.32.2
larray-0.32.2//larray/core/array.pyfile:/larray/core/array.py:function:percentile/percentile
def percentile(array, *args, **kwargs): """ Computes the qth percentile of the data along the specified axis. See Also -------- Array.percentile """ return array.percentile(*args, **kwargs)
pychedelic-0.1.3
pychedelic-0.1.3//pychedelic/core/wav.pyfile:/pychedelic/core/wav.py:function:seek/seek
def seek(wfile, position, end=None): """ Seeks `position` in `wfile`, and returns the number of frames to read until `end`. """ end_frame = wfile.getnframes() if end != None: end_frame = min(end * wfile.getframerate(), end_frame) position_frame = position * wfile.getframerate() wfile.setpos(int(round(position_frame))) return int(round(end_frame - position_frame))
blindtex
blindtex//latex2ast/parser.pyfile:/latex2ast/parser.py:function:p_style/p_style
def p_style(p): """ math_object : STYLE block | STYLE symbol """ p[2].style = p[1] p[0] = [p[2]]