code
stringlengths
51
2.34k
sequence
stringlengths
186
3.94k
docstring
stringlengths
11
171
def execute(self, fetchcommand, sql, params=None): cur = self.conn.cursor() if params: if not type(params).__name__ == 'tuple': raise ValueError('the params argument needs to be a tuple') return None cur.execute(sql, params) else: cur.execute(sql) self.conn.commit() if not fetchcommand or fet...
module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement identifier block if_statement not_operator comparison_operator attribu...
where 'fetchcommand' is either 'fetchone' or 'fetchall'
def update(): with settings(warn_only=True): print(cyan('\nInstalling/Updating required packages...')) pip = local('venv/bin/pip install -U --allow-all-external --src libs -r requirements.txt', capture=True) if pip.failed: print(red(pip)) abort("pip exited with return...
module function_definition identifier parameters block with_statement with_clause with_item call identifier argument_list keyword_argument identifier true block expression_statement call identifier argument_list call identifier argument_list string string_start string_content escape_sequence string_end expression_state...
Update virtual env with requirements packages.
def new(self, request): form = (self.form or generate_form(self.model))() return self._render( request = request, template = 'new', context = { 'form': form }, status = 200 )
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call parenthesized_expression boolean_operator attribute identifier identifier call identifier argument_list attribute identifier identifier argument_list return_statement call attribute identifier id...
Render a form to create a new object.
def fetch_url(url, dest, parent_to_remove_before_fetch): logger.debug('Downloading file {} from {}', dest, url) try: shutil.rmtree(parent_to_remove_before_fetch) except FileNotFoundError: pass os.makedirs(parent_to_remove_before_fetch) resp = requests.get(url, stream=True) with o...
module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier try_statement block expression_statement call attribute identifier identifier argument_list ...
Helper function to fetch a file from a URL.
def build(self): monomers = [HelicalHelix(major_pitch=self.major_pitches[i], major_radius=self.major_radii[i], major_handedness=self.major_handedness[i], aa=self.aas[i], minor_heli...
module function_definition identifier parameters identifier block expression_statement assignment identifier list_comprehension call identifier argument_list keyword_argument identifier subscript attribute identifier identifier identifier keyword_argument identifier subscript attribute identifier identifier identifier ...
Builds a model of a coiled coil protein using input parameters.
def _optimize_providers(self, providers): new_providers = {} provider_by_driver = {} for alias, driver in six.iteritems(providers): for name, data in six.iteritems(driver): if name not in provider_by_driver: provider_by_driver[name] = {} ...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call attribute identifier identifier argument_list identifier block for_statement patt...
Return an optimized mapping of available providers
def upload(): build = g.build utils.jsonify_assert(len(request.files) == 1, 'Need exactly one uploaded file') file_storage = request.files.values()[0] data = file_storage.read() content_type, _ = mimetypes.guess_type(file_storage.filename) artifact = _save_artifact(build...
module function_definition identifier parameters block expression_statement assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list comparison_operator call identifier argument_list attribute identifier identifier integer string string_start string_c...
Uploads an artifact referenced by a run.
def vip_create_event(self, vip_info): vip_data = vip_info.get('vip') port_id = vip_data.get('port_id') vip_id = vip_data.get('id') self.add_lbaas_port(port_id, vip_id)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string st...
Process vip create event.
def _import_class(self, module2cls): d = module2cls.rfind(".") classname = module2cls[d + 1: len(module2cls)] m = __import__(module2cls[0:d], globals(), locals(), [classname]) return getattr(m, classname)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier subscript identifier slice binary_operator identifier intege...
Import class by module dot split string
def createNetcon(self, thresh=10): nc = h.NetCon(self.soma(0.5)._ref_v, None, sec = self.soma) nc.threshold = thresh return nc
module function_definition identifier parameters identifier default_parameter identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list attribute call attribute identifier identifier argument_list float identifier none keyword_argument identifier attribute id...
created netcon to record spikes
def cart2spher(x, y, z): hxy = np.hypot(x, y) r = np.hypot(hxy, z) theta = np.arctan2(z, hxy) phi = np.arctan2(y, x) return r, theta, phi
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier ...
Cartesian to Spherical coordinate conversion.
def iterkeys(obj): "Get key iterator from dictionary for Python 2 and 3" return iter(obj.keys()) if sys.version_info.major == 3 else obj.iterkeys()
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end return_statement conditional_expression call identifier argument_list call attribute identifier identifier argument_list comparison_operator attribute attribute identifier identifier iden...
Get key iterator from dictionary for Python 2 and 3
def invert_delete_row(self, key, value): self.rows = filter(lambda x: x.get(key) == value, self.rows)
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment attribute identifier identifier call identifier argument_list lambda lambda_parameters identifier comparison_operator call attribute identifier identifier argument_list identifier identifier attribute...
Inverts delete_row and returns the rows where key = value
def excursion(directory): old_dir = os.getcwd() try: os.chdir(directory) yield finally: os.chdir(old_dir)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list try_statement block expression_statement call attribute identifier identifier argument_list identifier expression_statement yield finally_clause block expressio...
Context-manager that temporarily changes to a new working directory.
def countWordOverlapFrequencies(filename="goodOverlapPairs.pkl"): with open(filename,"rb") as f: goodOverlapPairs = pickle.load(f) with open("word_bitmaps_40_bits_minimum.pkl","rb") as f: bitmaps = pickle.load(f) wordFrequencies = {} for w1, w2, overlap in goodOverlapPairs: wordFrequencies[w1] = wor...
module function_definition identifier parameters default_parameter identifier string string_start string_content string_end block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement...
Count how many high overlaps each word has, and print it out
def parse_iso8601_date(string): match = _RE_ISO8601_DATE.search(string) if not match: raise ValueError('Expected ISO 8601 date') year = int(match.group('year')) month = int(match.group('month')) day = int(match.group('day')) return date(year, month, day)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement not_operator identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_sta...
Parse an ISO 8601 date string
def management(self): endpoint = self._instance.get_endpoint_for_service_type( "management", region_name=self._instance._region_name, ) token = self._instance.auth.get_token(self._instance.session) self._management = tuskar_client.get_client( 2, os_aut...
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier attribute attribute identifier identifier identifier expression_s...
Returns an management service client
def example_lab_to_xyz(): print("=== Simple Example: Lab->XYZ ===") lab = LabColor(0.903, 16.296, -2.22) print(lab) xyz = convert_color(lab, XYZColor) print(xyz) print("=== End Example ===\n")
module function_definition identifier parameters block expression_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list float float unary_operator float expression_statement call identifier argument_list identifier ...
This function shows a simple conversion of an Lab color to an XYZ color.
def path_to_reference(path): path = str(path) if '.' not in path: try: return globals()["__builtins__"][path] except KeyError: try: return getattr(globals()["__builtins__"], path) except AttributeError: pass try: ...
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator string string_start string_content string_end identifier block try_statement block return_statement subscript subscript call identifier a...
Convert an object path reference to a reference.
def _check_prob_and_prob_vector(predictions): from .._deps import numpy ptype = predictions.dtype import array if ptype not in [float, numpy.ndarray, array.array, int]: err_msg = "Input `predictions` must be of numeric type (for binary " err_msg += "classification) or array (of probabil...
module function_definition identifier parameters identifier block import_from_statement relative_import import_prefix dotted_name identifier dotted_name identifier expression_statement assignment identifier attribute identifier identifier import_statement dotted_name identifier if_statement comparison_operator identifi...
Check that the predictionsa are either probabilities of prob-vectors.
def _get_mosaik_nn_args(out_file): base_nn_url = "https://raw.github.com/wanpinglee/MOSAIK/master/src/networkFile/" out = [] for arg, fname in [("-annse", "2.1.26.se.100.005.ann"), ("-annpe", "2.1.26.pe.100.0065.ann")]: arg_fname = os.path.join(os.path.dirname(out_file), fname...
module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier list for_statement pattern_list identifier identifier list tuple string string_start string_content string_end string stri...
Retrieve default neural network files from GitHub to pass to Mosaik.
def _handle_ping(client, topic, dct): if dct['type'] == 'request': resp = { 'type': 'answer', 'name': client.name, 'source': dct } client.publish('ping', resp)
module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier dictionary pair string string_start s...
Internal method that will be called when receiving ping message.
def rand_pad(padding:int, size:int, mode:str='reflection'): "Fixed `mode` `padding` and random crop of `size`" return [pad(padding=padding,mode=mode), crop(size=size, **rand_pos)]
module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier typed_default_parameter identifier type identifier string string_start string_content string_end block expression_statement string string_start string_content string_end return_statemen...
Fixed `mode` `padding` and random crop of `size`
def upload_data(job, master_ip, inputs, hdfs_name, upload_name, spark_on_toil): if mock_mode(): truncate_file(master_ip, hdfs_name, spark_on_toil) log.info("Uploading output BAM %s to %s.", hdfs_name, upload_name) call_conductor(job, master_ip, hdfs_name, upload_name, memory=inputs.memory) remov...
module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block if_statement call identifier argument_list block expression_statement call identifier argument_list identifier identifier identifier expression_statement call attribute identifier identifier argument...
Upload file hdfsName from hdfs to s3
def object(self): proxy = self._proxy return ObjectProxy(proxy.get_connection(), proxy.get_name(), proxy.get_object_path())
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier return_statement call identifier argument_list call attribute identifier identifier argument_list call attribute identifier identifier argument_list call attribute identifier iden...
Get an ObjectProxy instanec for the underlying object.
def append(self, item: TransItem): self.data[item.key].append(item)
module function_definition identifier parameters identifier typed_parameter identifier type identifier block expression_statement call attribute subscript attribute identifier identifier attribute identifier identifier identifier argument_list identifier
Append an item to the internal dictionary.
def calculate_dimensions(image, long_side, short_side): if image.width >= image.height: return '{0}x{1}'.format(long_side, short_side) return '{0}x{1}'.format(short_side, long_side)
module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block return_statement call attribute string string_start string_content string_end identifier argument_list identifier identifier retu...
Returns the thumbnail dimensions depending on the images format.
def createCenterPointMarker(self): self.axes.add_patch(patches.Rectangle((-0.75,-self.thick),0.5,2.0*self.thick,facecolor='orange',zorder=3)) self.axes.add_patch(patches.Rectangle((0.25,-self.thick),0.5,2.0*self.thick,facecolor='orange',zorder=3)) self.axes.add_patch(patches.Circle((0,0),radius=...
module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list tuple unary_operator float unary_operator attribute identifier identifier float binary_operator float attribut...
Creates the center pointer in the middle of the screen.
def cublasDsymm(handle, side, uplo, m, n, alpha, A, lda, B, ldb, beta, C, ldc): status = _libcublas.cublasDsymm_v2(handle, _CUBLAS_SIDE_MODE[side], _CUBLAS_FILL_MODE[uplo], m, n, ctypes.byref(ctypes...
module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier subscript identif...
Matrix-matrix product for real symmetric matrix.
def setup_options_button(self): if not self.options_button: self.options_button = create_toolbutton( self, text=_('Options'), icon=ima.icon('tooloptions')) actions = self.actions + [MENU_SEPARATOR] + self.plugin_actions self.options_menu = QMenu(self) ...
module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier call identifier argument_list identifier keyword_argument identifier call identifier argument_list string string_start string_...
Add the cog menu button to the toolbar.
def parseFile(self, filename): modname = self.filenameToModname(filename) module = Module(modname, filename) self.modules[modname] = module if self.trackUnusedNames: module.imported_names, module.unused_names = \ find_imports_and_track_names(filename, ...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment subscript a...
Parse a single file.
def getUmis(self, n): if n < (self.random_fill_size - self.random_ix): barcodes = self.random_umis[self.random_ix: self.random_ix+n] else: if n > self.random_fill_size: self.random_fill_size = n * 2 self.refill_random() barcodes = self.rand...
module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier parenthesized_expression binary_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier sli...
return n umis from the random_umis atr.
def schema_exists(cls, cur, schema_name): cur.execute("SELECT EXISTS (SELECT schema_name FROM information_schema.schemata WHERE schema_name = '{0}');" .format(schema_name)) return cur.fetchone()[0]
module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier return_statement subscript call attribute identifier identifier...
Check if schema exists
def generate_nonce_timestamp(): global count rng = botan.rng().get(30) uuid4 = uuid.uuid4().bytes tmpnonce = (bytes(str(count).encode('utf-8'))) + uuid4 + rng nonce = tmpnonce[:41] count += 1 return nonce
module function_definition identifier parameters block global_statement identifier expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list integer expression_statement assignment identifier attribute call attribute identifier identifier argum...
Generate unique nonce with counter, uuid and rng.
def _load_data(batch, targets, major_axis): if isinstance(batch, list): new_batch = [] for i in range(len(targets)): new_batch.append([b.data[i] for b in batch]) new_targets = [[dst for _, dst in d_target] for d_target in targets] _load_general(new_batch, new_targets, maj...
module function_definition identifier parameters identifier identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier list for_statement identifier call identifier argument_list call identifier argument_list identifier block expression_...
Load data into sliced arrays.
def create_filehandlers(self, filenames, fh_kwargs=None): filenames = list(OrderedDict.fromkeys(filenames)) logger.debug("Assigning to %s: %s", self.info['name'], filenames) self.info.setdefault('filenames', []).extend(filenames) filename_set = set(filenames) created_fhs = {} ...
module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list st...
Organize the filenames into file types and create file handlers.
def proj_units_to_meters(proj_str): proj_parts = proj_str.split() new_parts = [] for itm in proj_parts: key, val = itm.split('=') key = key.strip('+') if key in ['a', 'b', 'h']: val = float(val) if val < 6e6: val *= 1000. val = ...
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment pattern_list identifier identifier cal...
Convert projection units from kilometers to meters.
def sphinx_class(self): classdoc = self.prop.sphinx_class().replace( ':class:`', '{info} of :class:`' ) return classdoc.format(info=self.class_info)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list string string_start string_content string_end string string_start string_content string_end return_...
Redefine sphinx class to point to prop class
def _get_first_assessment_section(self): if ('sections' not in self._my_map or not self._my_map['sections']): assessment_id = self.get_assessment_offered().get_assessment().get_id() first_part_id = get_first_part_id_for_assessment(assessment_id, runtime=self._runtime, proxy=self._proxy) ...
module function_definition identifier parameters identifier block if_statement parenthesized_expression boolean_operator comparison_operator string string_start string_content string_end attribute identifier identifier not_operator subscript attribute identifier identifier string string_start string_content string_end ...
Gets the first section for this Taken's Assessment.
def _project_eigenvectors(self): self._p_eigenvectors = [] for vecs_q in self._eigenvectors: p_vecs_q = [] for vecs in vecs_q.T: p_vecs_q.append(np.dot(vecs.reshape(-1, 3), self._projection_direction)) self._p_eig...
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier list for_statement identifier attribute identifier identifier block expression_statement assignment identifier list for_statement identifier attribute identifier identifier block expression_...
Eigenvectors are projected along Cartesian direction
def _assert_git_repo(target): hooks_dir = os.path.abspath(os.path.join(target, HOOKS_DIR_PATH)) if not os.path.isdir(hooks_dir): raise GitHookInstallerError(u"{0} is not a git repository.".format(target))
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier identifier if_statement not_operator call attribute attr...
Asserts that a given target directory is a git repository
def register_phonon_task(self, *args, **kwargs): kwargs["task_class"] = PhononTask return self.register_task(*args, **kwargs)
module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier return_statement call attribute identifier identifier argument_list list_splat...
Register a phonon task.
def common_options(func): def parse_preset(ctx, param, value): return PRESETS.get(value, (None, None)) def parse_private(ctx, param, value): return hex_from_b64(value) if value else None func = click.option('--private', default=None, help='Private.', callback=parse_private)(func) func = ...
module function_definition identifier parameters identifier block function_definition identifier parameters identifier identifier identifier block return_statement call attribute identifier identifier argument_list identifier tuple none none function_definition identifier parameters identifier identifier identifier blo...
Commonly used command options.
def register_laser_hooks(self, hook_type: str, hook: Callable): if hook_type == "add_world_state": self._add_world_state_hooks.append(hook) elif hook_type == "execute_state": self._execute_state_hooks.append(hook) elif hook_type == "start_sym_exec": self._star...
module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement call attribute attribute identifier identifier iden...
registers the hook with this Laser VM
def extensions(): import numpy from Cython.Build import cythonize ext = [ Extension('phydmslib.numutils', ['phydmslib/numutils.pyx'], include_dirs=[numpy.get_include()], extra_compile_args=['-Wno-unused-function']), ] return cythonize(e...
module function_definition identifier parameters block import_statement dotted_name identifier import_from_statement dotted_name identifier identifier dotted_name identifier expression_statement assignment identifier list call identifier argument_list string string_start string_content string_end list string string_sta...
Returns list of `cython` extensions for `lazy_cythonize`.
def ingest_containers(self, containers=None): containers = containers or self.stream or {} output_containers = [] for container_name, definition in containers.items(): container = definition.copy() container['name'] = container_name output_containers.append(co...
module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier boolean_operator boolean_operator identifier attribute identifier identifier dictionary expression_statement assignment identifier list for_statement pattern_list identifier ide...
Transform the YAML into a dict with normalized keys
def shovel_help(shovel, *names): if not len(names): return heirarchical_help(shovel, '') else: for name in names: task = shovel[name] if isinstance(task, Shovel): return heirarchical_help(task, name) else: return task.help()
module function_definition identifier parameters identifier list_splat_pattern identifier block if_statement not_operator call identifier argument_list identifier block return_statement call identifier argument_list identifier string string_start string_end else_clause block for_statement identifier identifier block ex...
Return a string about help with the tasks, or lists tasks available
def flash_errors(form, category='warning'): for (field, errors) in form.errors.items(): for error in errors: flash('{0} - {1}'.format(getattr(form, field).label.text, error), category)
module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block for_statement tuple_pattern identifier identifier call attribute attribute identifier identifier identifier argument_list block for_statement identifier identifier block expressio...
Flash all form error messages
def compute_radius(wcs): ra, dec = wcs.wcs.crval img_center = SkyCoord(ra=ra * u.degree, dec=dec * u.degree) wcs_foot = wcs.calc_footprint() img_corners = SkyCoord(ra=wcs_foot[:, 0] * u.degree, dec=wcs_foot[:, 1] * u.degree) radius = img_center.separation(img_corners).max(...
module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier binary_operator identifier attrib...
Compute the radius from the center to the furthest edge of the WCS.
def _get_ssh_client(self): return ipa_utils.get_ssh_client( self.instance_ip, self.ssh_private_key_file, self.ssh_user, timeout=self.timeout )
module function_definition identifier parameters identifier block return_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier
Return a new or existing SSH client for given ip.
def measure_cost(repeat, scipy_trans_lhs, scipy_dns_lhs, func_name, *args, **kwargs): mx.nd.waitall() args_list = [] for arg in args: args_list.append(arg) start = time.time() if scipy_trans_lhs: args_list[0] = np.transpose(args_list[0]) if scipy_dns_lhs else sp.spmatrix.transpose(ar...
module function_definition identifier parameters identifier identifier identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier list for_statement ...
Measure time cost of running a function
def build(mnemonic, oprnd1, oprnd2, oprnd3): ins = ReilInstruction() ins.mnemonic = mnemonic ins.operands = [oprnd1, oprnd2, oprnd3] return ins
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier list iden...
Return the specified instruction.
def _parse_region(self, rec, line_iter): had_info = False keyvals, section = self._parse_keyvals(line_iter) if keyvals: rec.metadata = keyvals[0] while section and section[0] != "STUDY": had_info = True keyvals, next_section = self._parse_keyvals(line_...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier false expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement ass...
Parse a section of an ISA-Tab, assigning information to a supplied record.
def _get_collection_for_user(self, collection_id, user): collection_query = Collection.objects.filter(pk=collection_id) if not collection_query.exists(): raise exceptions.ValidationError('Collection id does not exist') collection = collection_query.first() if not user.has_per...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier if_statement not_operator call attribute identifier identifier argument_list b...
Check that collection exists and user has `add` permission.
def scale_edges(self, multiplier): if not isinstance(multiplier,int) and not isinstance(multiplier,float): raise TypeError("multiplier must be an int or float") for node in self.traverse_preorder(): if node.edge_length is not None: node.edge_length *= multiplier
module function_definition identifier parameters identifier identifier block if_statement boolean_operator not_operator call identifier argument_list identifier identifier not_operator call identifier argument_list identifier identifier block raise_statement call identifier argument_list string string_start string_cont...
Multiply all edges in this ``Tree`` by ``multiplier``
def lower_coerce_type_blocks(ir_blocks): new_ir_blocks = [] for block in ir_blocks: new_block = block if isinstance(block, CoerceType): predicate = BinaryComposition( u'contains', Literal(list(block.target_class)), LocalField('@class')) new_block = Filter(...
module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment identif...
Lower CoerceType blocks into Filter blocks with a type-check predicate.
def _draw_outline(o:Patch, lw:int): "Outline bounding box onto image `Patch`." o.set_path_effects([patheffects.Stroke( linewidth=lw, foreground='black'), patheffects.Normal()])
module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier block expression_statement string string_start string_content string_end expression_statement call attribute identifier identifier argument_list list call attribute identifier identifie...
Outline bounding box onto image `Patch`.
def _construct_mongos(self, logpath, port, configdb): extra = '' auth_param = '' if self.args['auth']: key_path = os.path.abspath(os.path.join(self.dir, 'keyfile')) auth_param = '--keyFile %s' % key_path if self.unknown_args: extra = self._filter_valid...
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier string string_start string_end expression_statement assignment identifier string string_start string_end if_statement subscript attribute identifier identifier string string_star...
Construct command line strings for a mongos process.
def probes_used_extract_scores(full_scores, same_probes): if full_scores.shape[1] != same_probes.shape[0]: raise "Size mismatch" import numpy as np model_scores = np.ndarray((full_scores.shape[0],np.sum(same_probes)), 'float64') c=0 for i in range(0,full_scores.shape[1]): if same_probes[i]: for j in...
module function_definition identifier parameters identifier identifier block if_statement comparison_operator subscript attribute identifier identifier integer subscript attribute identifier identifier integer block raise_statement string string_start string_content string_end import_statement aliased_import dotted_nam...
Extracts a matrix of scores for a model, given a probes_used row vector of boolean
def count(self, query): if self.manual: return self.total if isinstance(query, Select): q = query.with_only_columns([func.count()]).order_by(None).limit(None).offset(None) return do_(q).scalar() return query.count()
module function_definition identifier parameters identifier identifier block if_statement attribute identifier identifier block return_statement attribute identifier identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute call attribute...
If query is Select object, this function will try to get count of select
def format_sms_payload(self, message, to, sender='elkme', options=[]): self.validate_number(to) if not isinstance(message, str): message = " ".join(message) message = message.rstrip() sms = { 'from': sender, 'to': to, 'message': message ...
module function_definition identifier parameters identifier identifier identifier default_parameter identifier string string_start string_content string_end default_parameter identifier list block expression_statement call attribute identifier identifier argument_list identifier if_statement not_operator call identifie...
Helper function to create a SMS payload with little effort
def run_cli(): "Command line interface to hiwenet." features_path, groups_path, weight_method, num_bins, edge_range, \ trim_outliers, trim_percentile, return_networkx_graph, out_weights_path = parse_args() features, groups = read_features_and_groups(features_path, groups_path) extract(features, grou...
module function_definition identifier parameters block expression_statement string string_start string_content string_end expression_statement assignment pattern_list identifier identifier identifier identifier identifier line_continuation identifier identifier identifier identifier call identifier argument_list expres...
Command line interface to hiwenet.
def _onArgument(self, name, annotation): self.objectsStack[-1].arguments.append(Argument(name, annotation))
module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute attribute subscript attribute identifier identifier unary_operator integer identifier identifier argument_list call identifier argument_list identifier identifier
Memorizes a function argument
def validate_path(ctx, param, value): client = ctx.obj if value is None: from renku.models.provenance import ProcessRun activity = client.process_commit() if not isinstance(activity, ProcessRun): raise click.BadParameter('No tool was found.') return activity.path ...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier none block import_from_statement dotted_name identifier identifier identifier dotted_name identifier expression_s...
Detect a workflow path if it is not passed.
def community_colors(n): if (n > 0): colors = cl.scales['12']['qual']['Paired'] shuffle(colors) return colors[:n] else: return choice(cl.scales['12']['qual']['Paired'])
module function_definition identifier parameters identifier block if_statement parenthesized_expression comparison_operator identifier integer block expression_statement assignment identifier subscript subscript subscript attribute identifier identifier string string_start string_content string_end string string_start ...
Returns a list of visually separable colors according to total communities
def _op_msg_uncompressed(flags, command, identifier, docs, check_keys, opts): data, total_size, max_bson_size = _op_msg_no_header( flags, command, identifier, docs, check_keys, opts) request_id, op_message = __pack_message(2013, data) return request_id, op_message, total_size, max_bson_size
module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement assignment pattern_list identifier identifier identifier call identifier argument_list identifier identifier identifier identifier identifier identifier expression_statement assi...
Internal compressed OP_MSG message helper.
def distribute_javaclasses(self, javaclass_dir, dest_dir="src"): info('Copying java files') ensure_dir(dest_dir) for filename in glob.glob(javaclass_dir): shprint(sh.cp, '-a', filename, dest_dir)
module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end block expression_statement call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list identifier for_state...
Copy existing javaclasses from build dir to current dist dir.
def extract_cab (archive, compression, cmd, verbosity, interactive, outdir): cmdlist = [cmd, '-d', outdir] if verbosity > 0: cmdlist.append('-v') cmdlist.append(archive) return cmdlist
module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier list identifier string string_start string_content string_end identifier if_statement comparison_operator identifier integer block expression_statement call...
Extract a CAB archive.
def com_google_fonts_check_name_line_breaks(ttFont): failed = False for name in ttFont["name"].names: string = name.string.decode(name.getEncoding()) if "\n" in string: failed = True yield FAIL, ("Name entry {} on platform {} contains" " a line-break.").format(NameID(name.name...
module function_definition identifier parameters identifier block expression_statement assignment identifier false for_statement identifier attribute subscript identifier string string_start string_content string_end identifier block expression_statement assignment identifier call attribute attribute identifier identif...
Name table entries should not contain line-breaks.
def _authenticate_client(self, client): if self.login and not self.restart_required: try: db = client[self.auth_source] if self.x509_extra_user: db.authenticate( DEFAULT_SUBJECT, mechanism='MONGODB-X5...
module function_definition identifier parameters identifier identifier block if_statement boolean_operator attribute identifier identifier not_operator attribute identifier identifier block try_statement block expression_statement assignment identifier subscript identifier attribute identifier identifier if_statement a...
Authenticate the client if necessary.
def _sig_handler(self, signum, stack): log_debug("Got SIGINT.") if signum == signal.SIGINT: LLNetReal.running = False if self._pktqueue.qsize() == 0: self._pktqueue.put( (None,None,None) )
module function_definition identifier parameters identifier identifier identifier block expression_statement call identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment attribute identifier ...
Handle process INT signal.
def to_browser_mode(self): for message_no in range(len(self.messages)): self.__to_browser(message_no)
module function_definition identifier parameters identifier block for_statement identifier call identifier argument_list call identifier argument_list attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier
Write all the messages to files and open them in the browser
def input_validate_aead(aead, name='aead', expected_len=None, max_aead_len = pyhsm.defines.YSM_AEAD_MAX_SIZE): if isinstance(aead, pyhsm.aead_cmd.YHSM_GeneratedAEAD): aead = aead.data if expected_len != None: return input_validate_str(aead, name, exact_len = expected_len) else: retur...
module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier none default_parameter identifier attribute attribute identifier identifier identifier block if_statement call identifier argument_list identifier attribute...
Input validation for YHSM_GeneratedAEAD or string.
def build( c, clean=False, browse=False, nitpick=False, opts=None, source=None, target=None, ): if clean: _clean(c) if opts is None: opts = "" if nitpick: opts += " -n -W -T" cmd = "sphinx-build{0} {1} {2}".format( (" " + opts) if opts else "",...
module function_definition identifier parameters identifier default_parameter identifier false default_parameter identifier false default_parameter identifier false default_parameter identifier none default_parameter identifier none default_parameter identifier none block if_statement identifier block expression_statem...
Build the project's Sphinx docs.
def _assign_as_root(self, id_): rfc = self._ras.get_relationship_form_for_create(self._phantom_root_id, id_, []) rfc.set_display_name('Implicit Root to ' + str(id_) + ' Parent-Child Relationship') rfc.set_description(self._relationship_type.get_display_name().get_text() + ' relationship for impl...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier list expression_statement call attribute identifier identifier argument_list binary_o...
Assign an id_ a root object in the hierarchy
def value_to_sql_str(v): if v is None: return 'null' if type(v) in (types.IntType, types.FloatType, types.LongType): return str(v) if type(v) in (types.StringType, types.UnicodeType): return "'%s'" %(v.replace(u"'", u"\\'")) if isinstance(v, datetime): return "'%s'" %(v.s...
module function_definition identifier parameters identifier block if_statement comparison_operator identifier none block return_statement string string_start string_content string_end if_statement comparison_operator call identifier argument_list identifier tuple attribute identifier identifier attribute identifier ide...
transform a python variable to the appropriate representation in SQL
def create_prefix_dir(nb_file, fmt): if 'prefix' in fmt: nb_dir = os.path.dirname(nb_file) + os.path.sep if not os.path.isdir(nb_dir): logging.log(logging.WARNING, "[jupytext] creating missing directory %s", nb_dir) os.makedirs(nb_dir)
module function_definition identifier parameters identifier identifier block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier binary_operator call attribute attribute identifier identifier identifier argument_list identifier attri...
Create directory if fmt has a prefix
def _make_walker(self, *args, **kwargs): walker = self.walker_class(*args, **kwargs) return walker
module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list list_splat identifier dictionary_splat identifier return_statement identifier
Create a walker instance.
def show(self, y:Image=None, ax:plt.Axes=None, figsize:tuple=(3,3), title:Optional[str]=None, hide_axis:bool=True, color:str='white', **kwargs): "Show the `ImageBBox` on `ax`." if ax is None: _,ax = plt.subplots(figsize=figsize) bboxes, lbls = self._compute_boxes() h,w = self.flo...
module function_definition identifier parameters identifier typed_default_parameter identifier type identifier none typed_default_parameter identifier type attribute identifier identifier none typed_default_parameter identifier type identifier tuple integer integer typed_default_parameter identifier type generic_type i...
Show the `ImageBBox` on `ax`.
def render_description_meta_tag(context, is_og=False): request = context['request'] content = '' if context.get('object'): try: content = context['object'].get_meta_description() except AttributeError: pass elif context.get('meta_tagger'): content = contex...
module function_definition identifier parameters identifier default_parameter identifier false block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_end if_statement call attribute identif...
Returns the description as meta or open graph tag.
def _make_graph(self, max_insert): if len(self.partial_links) != 0: raise Error('Error in _make_graph(). Cannot continue because there are partial links') self.contig_links = {} for key in self.links: for l in self.links[key]: insert_size = l.insert_size()...
module function_definition identifier parameters identifier identifier block if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment attribute ...
helper function to construct graph from current state of object
def tags(self): tag_list = self.spec.get('tag', []) if isinstance(tag_list, (list, set, tuple)): return list(tag_list) return [tag_list]
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end list if_statement call identifier argument_list identifier tuple identifier identifier identi...
Returns a list of all the tags applied to this view
def _sync_reminders(self, reminders_json): for reminder_json in reminders_json: reminder_id = reminder_json['id'] task_id = reminder_json['item_id'] if task_id not in self.tasks: continue task = self.tasks[task_id] self.reminders[remind...
module function_definition identifier parameters identifier identifier block for_statement identifier identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier subscript identifier string string_start string_...
Populate the user's reminders from a JSON encoded list.
def build_available_time_string(availabilities): prefix = 'We have availabilities at ' if len(availabilities) > 3: prefix = 'We have plenty of availability, including ' prefix += build_time_output_string(availabilities[0]) if len(availabilities) == 2: return '{} and {}'.format(prefix, bu...
module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content string_end if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier string string_start string_content...
Build a string eliciting for a possible time slot among at least two availabilities.
def galprop_gasmap(self, **kwargs): kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) self._replace_none(kwargs_copy) localpath = NameFactory.galprop_gasmap_format.format(**kwargs_copy) if kwargs.get('fullpath', False): return self.fullpath(loca...
module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list dictionary_splat identifier exp...
return the file name for Galprop input gasmaps
def main(): if len(argv) < 2: print 'Usage: %s fst_file [optional: save_file]' % argv[0] return flex_a = Flexparser() mma = flex_a.yyparse(argv[1]) mma.minimize() print mma if len(argv) == 3: mma.save(argv[2])
module function_definition identifier parameters block if_statement comparison_operator call identifier argument_list identifier integer block print_statement binary_operator string string_start string_content string_end subscript identifier integer return_statement expression_statement assignment identifier call ident...
Testing function for Flex Regular Expressions to FST DFA
def process_exception(self, request, e): if isinstance(e, RedirectException): response = e.get_response() self.process_response(request, response)
module function_definition identifier parameters identifier identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_...
Still process session data when specially Exception
def update_time_reset_passwd(user_name, the_time): entry = TabMember.update( time_reset_passwd=the_time, ).where(TabMember.user_name == user_name) try: entry.execute() return True except: return False
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list keyword_argument identifier identifier identifier argument_list comparison_operator attribute identifier identifier identifier try_sta...
Update the time when user reset passwd.
def save(self, fname=''): if fname is '': self.case.save() else: self.case.SaveAs(self.path+os.sep+fname)
module function_definition identifier parameters identifier default_parameter identifier string string_start string_end block if_statement comparison_operator identifier string string_start string_end block expression_statement call attribute attribute identifier identifier identifier argument_list else_clause block ex...
Save the current case
def mask_roi_unique(self): A = np.vstack([self.mask_1.mask_roi_sparse,self.mask_2.mask_roi_sparse]).T B = A[np.lexsort(A.T[::-1])] return B[np.concatenate(([True],np.any(B[1:]!=B[:-1],axis=1)))]
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute call attribute identifier identifier argument_list list attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier identifier expression_statement assignm...
Assemble a set of unique magnitude tuples for the ROI
def InterfaceMatcher(clazz, subclass, protocol): interface = (clazz, subclass, protocol) def Matcher(device): for setting in device.iterSettings(): if GetInterface(setting) == interface: return setting return Matcher
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier tuple identifier identifier identifier function_definition identifier parameters identifier block for_statement identifier call attribute identifier identifier argument_list block if_statem...
Returns a matcher that returns the setting with the given interface.
def _get_previous_open_tag(self, obj): prev_instance = self.get_previous_instance(obj) if prev_instance and prev_instance.plugin_type == self.__class__.__name__: return prev_instance.glossary.get('open_tag')
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement boolean_operator identifier comparison_operator attribute identifier identifier attribute attribute identifier identifier ide...
Return the open tag of the previous sibling
def uid(self, p_todo): try: return self._todo_id_map[p_todo] except KeyError as ex: raise InvalidTodoException from ex
module function_definition identifier parameters identifier identifier block try_statement block return_statement subscript attribute identifier identifier identifier except_clause as_pattern identifier as_pattern_target identifier block raise_statement identifier identifier
Returns the unique text-based ID for a todo item.
def erase(ctx): if os.path.exists(ctx.obj['report']): os.remove(ctx.obj['report'])
module function_definition identifier parameters identifier block if_statement call attribute attribute identifier identifier identifier argument_list subscript attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list sub...
Erase the existing smother report.
def require_content_type(self, content_type): if self.request.headers.get('content-type', '') != content_type: self.halt(400, 'Content type must be ' + content_type)
module function_definition identifier parameters identifier identifier block if_statement comparison_operator call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier block expression_statement ca...
Raises a 400 if request content type is not as specified.
def tax_for_order(self, order_deets): request = self._post('taxes', order_deets) return self.responder(request)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement call attribute identifier identifier argument_list identifier
Shows the sales tax that should be collected for a given order.
def _allow_custom_expire(self, load): expire_override = self.opts.get('token_expire_user_override', False) if expire_override is True: return True if isinstance(expire_override, collections.Mapping): expire_whitelist = expire_override.get(load['eauth'], []) if...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end false if_statement comparison_operator identifier true block return_statement true...
Return bool if requesting user is allowed to set custom expire
def handle_pre_response(self, item_session: ItemSession) -> Actions: action = self.consult_pre_response_hook(item_session) if action == Actions.RETRY: item_session.set_status(Status.skipped) elif action == Actions.FINISH: item_session.set_status(Status.done) elif ...
module function_definition identifier parameters identifier typed_parameter identifier type identifier type identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier attribute identifier identifier block expressi...
Process a response that is starting.
def key(self): prefix = type(self).cls_key() return '{}:{}:obj'.format(prefix, self.id)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier argument_list return_statement call attribute string string_start string_content string_end identifier argument_list identifier attribute identi...
Returns the redis key to access this object's values
def convert_to_annotation(file, output): resource = parse_bel_resource(file) write_annotation( keyword=resource['Namespace']['Keyword'], values={k: '' for k in resource['Values']}, citation_name=resource['Citation']['NameString'], description=resource['Namespace']['DescriptionStr...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement call identifier argument_list keyword_argument identifier subscript subscript identifier string string_start string_content string_end str...
Convert a namespace file to an annotation file.