code
stringlengths
51
2.34k
sequence
stringlengths
186
3.94k
docstring
stringlengths
11
171
def transformArray(data, keysToSplit=[]): transformed = [ ] for item in data: transformed.append(transform(item, keysToSplit)) return transformed
module function_definition identifier parameters identifier default_parameter identifier list block expression_statement assignment identifier list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier identifier return...
Transform a SPARQL json array based on the rules of transform
def translate_state(self, s): if not isinstance(s, basestring): return s s = s.capitalize().replace("_", " ") return t(_(s))
module function_definition identifier parameters identifier identifier block if_statement not_operator call identifier argument_list identifier identifier block return_statement identifier expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_li...
Translate the given state string
def connect_client_to_kernel(self, client, is_cython=False, is_pylab=False, is_sympy=False): connection_file = client.connection_file stderr_handle = None if self.test_no_stderr else client.stderr_handle km, kc = self.create_kernel_manager_and_kernel_client( ...
module function_definition identifier parameters identifier identifier default_parameter identifier false default_parameter identifier false default_parameter identifier false block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier conditional_expressi...
Connect a client to its kernel
def update_org_owner(cls, module): try: cls.module_registry[module]["OrgOwnerModel"]._meta.get_field( "organization_user" ) except FieldDoesNotExist: cls.module_registry[module]["OrgOwnerModel"].add_to_class( "organization_user", ...
module function_definition identifier parameters identifier identifier block try_statement block expression_statement call attribute attribute subscript subscript attribute identifier identifier identifier string string_start string_content string_end identifier identifier argument_list string string_start string_conte...
Creates the links to the organization and organization user for the owner.
def _wire_events(self): self._device.on_open += self._on_open self._device.on_close += self._on_close self._device.on_read += self._on_read self._device.on_write += self._on_write self._zonetracker.on_fault += self._on_zone_fault self._zonetracker.on_restore += self._on_z...
module function_definition identifier parameters identifier block expression_statement augmented_assignment attribute attribute identifier identifier identifier attribute identifier identifier expression_statement augmented_assignment attribute attribute identifier identifier identifier attribute identifier identifier ...
Wires up the internal device events.
def tracker_class(clsname): stats = server.stats if not stats: bottle.redirect('/tracker') stats.annotate() return dict(stats=stats, clsname=clsname)
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_stateme...
Get class instance details.
def _normalize_stack(graphobjs): for operands, operator in graphobjs: operator = str(operator) if re.match(r'Q*q+$', operator): for char in operator: yield ([], char) else: yield (operands, operator)
module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement call attribute identifier identifier argument_list string string_start string_content strin...
Convert runs of qQ's in the stack into single graphobjs
def convert_to_duckling_language_id(cls, lang): if lang is not None and cls.is_supported(lang): return lang elif lang is not None and cls.is_supported(lang + "$core"): return lang + "$core" else: raise ValueError("Unsupported language '{}'. Supported languages...
module function_definition identifier parameters identifier identifier block if_statement boolean_operator comparison_operator identifier none call attribute identifier identifier argument_list identifier block return_statement identifier elif_clause boolean_operator comparison_operator identifier none call attribute i...
Ensure a language identifier has the correct duckling format and is supported.
def join_images(img_files, out_file): images = [PIL.Image.open(f) for f in img_files] joined = PIL.Image.new( 'RGB', (sum(i.size[0] for i in images), max(i.size[1] for i in images)) ) left = 0 for img in images: joined.paste(im=img, box=(left, 0)) left = left + img.si...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list_comprehension call attribute attribute identifier identifier identifier argument_list identifier for_in_clause identifier identifier expression_statement assignment identifier call attribute attr...
Join the list of images into the out file
def image_by_id(self, id): if not id: return None return next((image for image in self.images() if image['Id'] == id), None)
module function_definition identifier parameters identifier identifier block if_statement not_operator identifier block return_statement none return_statement call identifier argument_list generator_expression identifier for_in_clause identifier call attribute identifier identifier argument_list if_clause comparison_op...
Return image with given Id
def cached(function): cache_variable = '_cached_' + function.__name__ @wraps(function) def function_wrapper(obj, *args, **kwargs): try: cache = getattr(obj, cache_variable) except AttributeError: cache = {} setattr(obj, cache_variable, cache) args_...
module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end attribute identifier identifier decorated_definition decorator call identifier argument_list identifier function_definition identifier parameters ide...
Method decorator caching a method's returned values.
def symmetry_cycles(self): result = set([]) for symmetry in self.symmetries: result.add(symmetry.cycles) return result
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list list for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier return_st...
The cycle representations of the graph symmetries
def confirm_user(query): user = _query_to_user(query) if click.confirm(f'Are you sure you want to confirm {user!r}?'): if security_service.confirm_user(user): click.echo(f'Successfully confirmed {user!r} at ' f'{user.confirmed_at.strftime("%Y-%m-%d %H:%M:%S%z")}') ...
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement call attribute identifier identifier argument_list string string_start string_content interpolation identifier type_conversion string_content string_end bloc...
Confirm a user account.
def follow_model(self, model): if model: self.models_by_name[model.__name__.lower()] = model signals.post_save.connect(create_or_update, sender=model) signals.post_delete.connect(self.remove_orphans, sender=model)
module function_definition identifier parameters identifier identifier block if_statement identifier block expression_statement assignment subscript attribute identifier identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier...
Follow a particular model class, updating associated Activity objects automatically.
def __set_premature_stop_codon_status(self, hgvs_string): if re.search('.+\*(\d+)?$', hgvs_string): self.is_premature_stop_codon = True self.is_non_silent = True if hgvs_string.endswith('*'): self.is_nonsense_mutation = True else: s...
module function_definition identifier parameters identifier identifier block if_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier block expression_statement assignment attribute identifier identifier true expression_statement assignment attribute ident...
Set whether there is a premature stop codon.
def median(self): mu = self.mean() ret_val = math.exp(mu) if math.isnan(ret_val): ret_val = float("inf") return ret_val
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement call attribute identifier identifier argum...
Computes the median of a log-normal distribution built with the stats data.
def _normalize_path(self, path): if type(path) is str: path = path.encode() path = path.split(b'\0')[0] if path[0:1] != self.pathsep: path = self.cwd + self.pathsep + path keys = path.split(self.pathsep) i = 0 while i < len(keys): if ke...
module function_definition identifier parameters identifier identifier block if_statement comparison_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier subscript call ...
Takes a path and returns a simple absolute path as a list of directories from the root
def _createIndexRti(self, index, nodeName): return PandasIndexRti(index=index, nodeName=nodeName, fileName=self.fileName, iconColor=self._iconColor)
module function_definition identifier parameters identifier identifier identifier block return_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifie...
Auxiliary method that creates a PandasIndexRti.
def cookies(self): return (self.get_query() .select(PageView.ip, PageView.headers['Cookie']) .where(PageView.headers['Cookie'].is_null(False)) .tuples())
module function_definition identifier parameters identifier block return_statement parenthesized_expression call attribute call attribute call attribute call attribute identifier identifier argument_list identifier argument_list attribute identifier identifier subscript attribute identifier identifier string string_sta...
Retrieve the cookies header from all the users who visited.
def removeReadGroupSet(self): self._openRepo() dataset = self._repo.getDatasetByName(self._args.datasetName) readGroupSet = dataset.getReadGroupSetByName( self._args.readGroupSetName) def func(): self._updateRepo(self._repo.removeReadGroupSet, readGroupSet) ...
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute attribute identifier identifier identifier expression_sta...
Removes a readGroupSet from the repo.
def ensureFulltextIndex(self, fields, minLength = None) : data = { "type" : "fulltext", "fields" : fields, } if minLength is not None : data["minLength"] = minLength ind = Index(self, creationData = data) self.indexes["fulltext"][ind.infos["id"...
module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end identif...
Creates a fulltext index if it does not already exist, and returns it
def generate_folder_names(name, project): out_data_dir = prms.Paths.outdatadir project_dir = os.path.join(out_data_dir, project) batch_dir = os.path.join(project_dir, name) raw_dir = os.path.join(batch_dir, "raw_data") return out_data_dir, project_dir, batch_dir, raw_dir
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier expression...
Creates sensible folder names.
def _groupby_and_aggregate(self, how, grouper=None, *args, **kwargs): if grouper is None: self._set_binner() grouper = self.grouper obj = self._selected_obj grouped = groupby(obj, by=None, grouper=grouper, axis=self.axis) try: if isinstance(obj, ABCDat...
module function_definition identifier parameters identifier identifier default_parameter identifier none list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list expression_state...
Re-evaluate the obj with a groupby aggregation.
def save_sensors(self): if not self.need_save: return fname = os.path.realpath(self.persistence_file) exists = os.path.isfile(fname) dirname = os.path.dirname(fname) if (not os.access(dirname, os.W_OK) or exists and not os.access(fname, os.W_OK)): ...
module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block return_statement expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assig...
Save sensors to file.
def post(self, id): model = self.model.objects.only('id').get_or_404(id=id) follow, created = Follow.objects.get_or_create( follower=current_user.id, following=model, until=None) count = Follow.objects.followers(model).count() if not current_app.config['TESTING']: ...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end identifier argument_list keyword_argument iden...
Follow an object given its ID
def change_user_password(self, ID, data): log.info('Change user %s password' % ID) self.put('users/%s/change_password.json' % ID, data)
module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list binary_operator...
Change password of a User.
def _delete_fields(self): for key in self._json_dict.keys(): if not key.startswith("_"): delattr(self, key) self._json_dict = {} self.id = None self.name = None
module function_definition identifier parameters identifier block for_statement identifier call attribute attribute identifier identifier identifier argument_list block if_statement not_operator call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement c...
Delete this object's attributes, including name and id
def starting_expression(source_code, offset): word_finder = worder.Worder(source_code, True) expression, starting, starting_offset = \ word_finder.get_splitted_primary_before(offset) if expression: return expression + '.' + starting return starting
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier true expression_statement assignment pattern_list identifier identifier identifier line_continuation call attribute identifier identifier ...
Return the expression to complete
def current_values(self): current_dict = { 'date': self.current_session_date, 'score': self.current_sleep_score, 'stage': self.current_sleep_stage, 'breakdown': self.current_sleep_breakdown, 'tnt': self.current_tnt, 'bed_temp': self.current...
module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_co...
Return a dict of all the 'current' parameters.
def getObjectTypeBit(self, t): if isinstance(t, string_types): t = t.upper() try: return self.objectType[t] except KeyError: raise CommandExecutionError(( 'Invalid object type "{0}". It should be one of the following: {1}'...
module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list try_statement block return_statement subscript attribute identifier identifier...
returns the bit value of the string object type
def hide_auth(msg): for pattern, repl in RE_HIDE_AUTH: msg = pattern.sub(repl, msg) return msg
module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier return_statement identifier
Remove sensitive information from msg.
def press_check(df): new_df = df.copy() press = new_df.copy().index.values ref = press[0] inversions = np.diff(np.r_[press, press[-1]]) < 0 mask = np.zeros_like(inversions) for k, p in enumerate(inversions): if p: ref = press[k] cut = press[k + 1 :] < ref ...
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier attribute attribute call attribute identifier identifier argument_list identifier identifier expression_statement ass...
Remove pressure reversals from the index.
def fcs(bits): fcs = FCS() for bit in bits: yield bit fcs.update_bit(bit) digest = bitarray(endian="little") digest.frombytes(fcs.digest()) for bit in digest: yield bit
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list for_statement identifier identifier block expression_statement yield identifier expression_statement call attribute identifier identifier argument_list identifier expression_stateme...
Append running bitwise FCS CRC checksum to end of generator
def _WritePathInfo(self, client_id, path_info): if client_id not in self.metadatas: raise db.UnknownClientError(client_id) path_record = self._GetPathRecord(client_id, path_info) path_record.AddPathInfo(path_info) parent_path_info = path_info.GetParent() if parent_path_info is not None: ...
module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block raise_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier ide...
Writes a single path info record for given client.
def split_none(self): "Don't split the data and create an empty validation set." val = self[[]] val.ignore_empty = True return self._split(self.path, self, val)
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier subscript identifier list expression_statement assignment attribute identifier identifier true return_statement call attribute identifier identi...
Don't split the data and create an empty validation set.
def proper_repr(value: Any) -> str: if isinstance(value, sympy.Basic): result = sympy.srepr(value) fixed_tokens = [ 'Symbol', 'pi', 'Mul', 'Add', 'Mod', 'Integer', 'Float', 'Rational' ] for token in fixed_tokens: result = result.replace(token, 'sympy.' + token...
module function_definition identifier parameters typed_parameter identifier type identifier type identifier block if_statement call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expressio...
Overrides sympy and numpy returning repr strings that don't parse.
def _vpc_peering_conn_id_for_name(name, conn): log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' ...
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier identifier if_statement not_operator iden...
Get the ID associated with this name
def symlink(source, link_name): if os.path.islink(link_name) and os.readlink(link_name) == source: return os_symlink = getattr(os, "symlink", None) if callable(os_symlink): os_symlink(source, link_name) else: import ctypes csl = ctypes.windll.kernel32.CreateSymbolicLinkW ...
module function_definition identifier parameters identifier identifier block if_statement boolean_operator call attribute attribute identifier identifier identifier argument_list identifier comparison_operator call attribute identifier identifier argument_list identifier identifier block return_statement expression_sta...
Method to allow creating symlinks on Windows
def _get_jenks_config(): config_file = (get_configuration_file() or os.path.expanduser(os.path.join("~", CONFIG_FILE_NAME))) if not os.path.exists(config_file): open(config_file, 'w').close() with open(config_file, 'r') as fh: return JenksData( yaml.load(fh.rea...
module function_definition identifier parameters block expression_statement assignment identifier parenthesized_expression boolean_operator call identifier argument_list call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list string...
retrieve the jenks configuration object
def _list_paths(self, bucket, prefix): s3 = self.s3 kwargs = {"Bucket": bucket, "Prefix": prefix} if self.list_objects: list_objects_api = "list_objects" else: list_objects_api = "list_objects_v2" paginator = s3.get_paginator(list_objects_api) for ...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content s...
Read config for list object api, paginate through list objects.
def read_writer_config(config_files, loader=UnsafeLoader): conf = {} LOG.debug('Reading %s', str(config_files)) for config_file in config_files: with open(config_file) as fd: conf.update(yaml.load(fd.read(), Loader=loader)) try: writer_info = conf['writer'] except KeyErro...
module function_definition identifier parameters identifier default_parameter identifier identifier block expression_statement assignment identifier dictionary expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list identifier f...
Read the writer `config_files` and return the info extracted.
def GetAnnotatedMethods(cls): result = {} for i_cls in reversed(inspect.getmro(cls)): for name in compatibility.ListAttrs(i_cls): cls_method = getattr(i_cls, name) if not callable(cls_method): continue if not hasattr(cls_method, "__http_methods__"): continue ...
module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary for_statement identifier call identifier argument_list call attribute identifier identifier argument_list identifier block for_statement identifier call attribute identifier identifier argument_list i...
Returns a dictionary of annotated router methods.
def prepare_request(self, request): try: request_id = local.request_id except AttributeError: request_id = NO_REQUEST_ID if self.request_id_header and request_id != NO_REQUEST_ID: request.headers[self.request_id_header] = request_id return super(Sessio...
module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier attribute identifier identifier except_clause identifier block expression_statement assignment identifier identifier if_statement boolean_operator attribute identifier identifier c...
Include the request ID, if available, in the outgoing request
def store_snow_tweets_from_disk_to_mongodb(snow_tweets_folder): client = pymongo.MongoClient("localhost", 27017) db = client["snow_tweet_storage"] collection = db["tweets"] for tweet in extract_all_snow_tweets_from_disk_generator(snow_tweets_folder): collection.insert(tweet)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end integer expression_statement assignment identifier subscript identifier string string_start string_content string_...
Store all SNOW tweets in a mongodb collection.
def to_bytes(s, encoding=None, errors='strict'): encoding = encoding or 'utf-8' if is_unicode(s): return s.encode(encoding, errors) elif is_strlike(s): return s else: if six.PY2: return str(s) else: return str(s).encode(encoding, errors)
module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier boolean_operator identifier string string_start string_content string_end if_statement call identifier...
Convert string to bytes.
def _simple_cmd(cmd, app, url='http://localhost:8080/manager', timeout=180): try: opts = { 'path': app, 'version': ls(url)[app]['version'] } return '\n'.join(_wget(cmd, opts, url, timeout=timeout)['msg']) except Exception: return 'FAIL - No context exists ...
module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end default_parameter identifier integer block try_statement block expression_statement assignment identifier dictionary pair string string_start string_content string_end identi...
Simple command wrapper to commands that need only a path option
def tag(name, tag_name): with LOCK: metric(name) TAGS.setdefault(tag_name, set()).add(name)
module function_definition identifier parameters identifier identifier block with_statement with_clause with_item identifier block expression_statement call identifier argument_list identifier expression_statement call attribute call attribute identifier identifier argument_list identifier call identifier argument_list...
Tag the named metric with the given tag.
def toggle_eventtype(self): check = self.check_all_eventtype.isChecked() for btn in self.idx_eventtype_list: btn.setChecked(check)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list iden...
Check or uncheck all event types in event type scroll.
def reset_position(self): self.pos = 0 self.col = 0 self.row = 1 self.eos = 0
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier integer expression_statement assignment attrib...
Reset all current positions.
def _evaluate_cut(transition, cut, unpartitioned_account, direction=Direction.BIDIRECTIONAL): cut_transition = transition.apply_cut(cut) partitioned_account = account(cut_transition, direction) log.debug("Finished evaluating %s.", cut) alpha = account_distance(unpartitioned_account, pa...
module function_definition identifier parameters identifier identifier identifier default_parameter identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argumen...
Find the |AcSystemIrreducibilityAnalysis| for a given cut.
def clean(self): super().clean() if self.voter is None and self.anonymous_key is None: raise ValidationError(_('A user id or an anonymous key must be used.')) if self.voter and self.anonymous_key: raise ValidationError(_('A user id or an anonymous key must be used, but no...
module function_definition identifier parameters identifier block expression_statement call attribute call identifier argument_list identifier argument_list if_statement boolean_operator comparison_operator attribute identifier identifier none comparison_operator attribute identifier identifier none block raise_stateme...
Validates the considered instance.
def dashes(phone): if isinstance(phone, str): if phone.startswith("+1"): return "1-" + "-".join((phone[2:5], phone[5:8], phone[8:])) elif len(phone) == 10: return "-".join((phone[:3], phone[3:6], phone[6:])) else: return phone else: return phon...
module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block return_statement binary_operator string string_start string_content...
Returns the phone number formatted with dashes.
def remove_env(environment): if not environment: print("You need to supply an environment name") return parser = read_config() if not parser.remove_section(environment): print("Unknown environment type '%s'" % environment) return write_config(parser) print("Removed en...
module function_definition identifier parameters identifier block if_statement not_operator identifier block expression_statement call identifier argument_list string string_start string_content string_end return_statement expression_statement assignment identifier call identifier argument_list if_statement not_operato...
Remove an environment from the configuration.
def return_value(self): if self._raises: if inspect.isclass(self._raises): raise self._raises() else: raise self._raises else: if isinstance(self._returns, tuple): return tuple([x.value if isinstance(x, Variable) ...
module function_definition identifier parameters identifier block if_statement attribute identifier identifier block if_statement call attribute identifier identifier argument_list attribute identifier identifier block raise_statement call attribute identifier identifier argument_list else_clause block raise_statement ...
Returns the value for this expectation or raises the proper exception.
def direct_reply(self, text): channel_id = self._client.open_dm_channel(self._get_user_id()) self._client.rtm_send_message(channel_id, text)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifie...
Send a reply via direct message using RTM API
def parse_value(self, value_string: str): self.value = Decimal(value_string) return self.value
module function_definition identifier parameters identifier typed_parameter identifier type identifier block expression_statement assignment attribute identifier identifier call identifier argument_list identifier return_statement attribute identifier identifier
Parses the amount string.
def jscanner(url): response = requester(url, main_url, delay, cook, headers, timeout, host, proxies, user_agents, failed, processed) matches = rendpoint.findall(response) for match in matches: match = match[0] + match[1] if not re.search(r'[}{><"\']', match) and not match == '/': ...
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier expression_statement assignment identifier call attribute id...
Extract endpoints from JavaScript code.
def make_mesh( coor, ngroups, conns, mesh_in ): mat_ids = [] for ii, conn in enumerate( conns ): mat_id = nm.empty( (conn.shape[0],), dtype = nm.int32 ) mat_id.fill( mesh_in.mat_ids[ii][0] ) mat_ids.append( mat_id ) mesh_out = Mesh.from_data( 'merged mesh', coor, ngroups, conns, ...
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier list for_statement pattern_list identifier identifier call identifier argument_list identifier block expression_statement assignment identifier call attribute identifier identifi...
Create a mesh reusing mat_ids and descs of mesh_in.
def leaveoneout(self): traintestfile = self.fileprefix + '.train' options = "-F " + self.format + " " + self.timbloptions + " -t leave_one_out" if sys.version < '3': self.api = timblapi.TimblAPI(b(options), b"") else: self.api = timblapi.TimblAPI(options, "") ...
module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier binary_operator binary_operator binary_operator binary_operator string str...
Train & Test using leave one out
def next_frame_sampling(): hparams = next_frame_basic_deterministic() hparams.scheduled_sampling_mode = "prob_inverse_exp" hparams.scheduled_sampling_max_prob = 1.0 hparams.scheduled_sampling_decay_steps = 10000 return hparams
module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier float expression_s...
Basic conv model with scheduled sampling.
def send(self, data): self._send_data(int_to_hex(len(data))) self._send_data(data)
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier
Send a formatted message to the ADB server
def compute_expansion_alignment(satz_a, satz_b, satz_c, satz_d): zeta_a = satz_a zeta_b = satz_b phi_a = compute_phi(zeta_a) phi_b = compute_phi(zeta_b) theta_a = compute_theta(zeta_a, phi_a) theta_b = compute_theta(zeta_b, phi_b) phi = (phi_a + phi_b) / 2 zeta = compute_zeta(phi) th...
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier identifier expression_statement assignment identifier identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignme...
All angles in radians.
def __apf_cmd(cmd): apf_cmd = '{0} {1}'.format(salt.utils.path.which('apf'), cmd) out = __salt__['cmd.run_all'](apf_cmd) if out['retcode'] != 0: if not out['stderr']: msg = out['stdout'] else: msg = out['stderr'] raise CommandExecutionError( 'apf f...
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_conte...
Return the apf location
def sorted_source_files(self): assert self.final, 'Call build() before using the graph.' out = [] for node in nx.topological_sort(self.graph): if isinstance(node, NodeSet): out.append(node.nodes) else: out.append([node]) return list...
module function_definition identifier parameters identifier block assert_statement attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier list for_statement identifier call attribute identifier identifier argument_list attribute identifier identifier blo...
Returns a list of targets in topologically sorted order.
def save_current_figure_as(self): if self.current_thumbnail is not None: self.save_figure_as(self.current_thumbnail.canvas.fig, self.current_thumbnail.canvas.fmt)
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute identifier identifier argument_list attribute attribute attribute identifier identifier identifier identifier attribute attribute attribute id...
Save the currently selected figure.
def process_slice(self, b_rot90=None): if b_rot90: self._Mnp_2Dslice = np.rot90(self._Mnp_2Dslice) if self.func == 'invertIntensities': self.invert_slice_intensities()
module function_definition identifier parameters identifier default_parameter identifier none block if_statement identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement comparison_operator attribute ...
Processes a single slice.
def wrapped_target(target, q_stdout, q_stderr, q_error, robust, name, *args, **kwargs): import sys sys.stdout = IOQueue(q_stdout) sys.stderr = IOQueue(q_stderr) try: target(*args, **kwargs) except: if not robust: s = 'Error in tab\n' + traceback.format_exc() l...
module function_definition identifier parameters identifier identifier identifier identifier identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block import_statement dotted_name identifier expression_statement assignment attribute identifier identifier call identifier argument_list...
Wraps a target with queues replacing stdout and stderr
def _async_callable(func): if isinstance(func, types.CoroutineType): return func @functools.wraps(func) async def _async_def_wrapper(*args, **kwargs): return func(*args, **kwargs) return _async_def_wrapper
module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier attribute identifier identifier block return_statement identifier decorated_definition decorator call attribute identifier identifier argument_list identifier function_definition identifier parameters...
Ensure the callable is an async def.
def do_mute(self, sender, body, args): if sender.get('MUTED'): self.send_message('you are already muted', sender) else: self.broadcast('%s has muted this chatroom' % (sender['NICK'],)) sender['QUEUED_MESSAGES'] = [] sender['MUTED'] = True
module function_definition identifier parameters identifier identifier identifier identifier block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_conten...
Temporarily mutes chatroom for a user
def run_checks(collector): artifact = collector.configuration["dashmat"].artifact chosen = artifact if chosen in (None, "", NotSpecified): chosen = None dashmat = collector.configuration["dashmat"] modules = collector.configuration["__active_modules__"] config_root = collector.configurat...
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute subscript attribute identifier identifier string string_start string_content string_end identifier expression_statement assignment identifier identifier if_statement comparison_operator identifier tupl...
Just run the checks for our modules
def cut_for_search(self, sentence, HMM=True): words = self.cut(sentence, HMM=HMM) for w in words: if len(w) > 2: for i in xrange(len(w) - 1): gram2 = w[i:i + 2] if self.FREQ.get(gram2): yield gram2 if...
module function_definition identifier parameters identifier identifier default_parameter identifier true block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier for_statement identifier identifier block if_statement comparison...
Finer segmentation for search engines.
def _wait_until_connectable(self, timeout=30): count = 0 while not utils.is_connectable(self.profile.port): if self.process.poll() is not None: raise WebDriverException( "The browser appears to have exited " "before we could connect. If...
module function_definition identifier parameters identifier default_parameter identifier integer block expression_statement assignment identifier integer while_statement not_operator call attribute identifier identifier argument_list attribute attribute identifier identifier identifier block if_statement comparison_ope...
Blocks until the extension is connectable in the firefox.
async def get_real_ext_ip(self): while self._ip_hosts: try: timeout = aiohttp.ClientTimeout(total=self._timeout) async with aiohttp.ClientSession( timeout=timeout, loop=self._loop ) as session, session.get(self._pop_random_ip_host()...
module function_definition identifier parameters identifier block while_statement attribute identifier identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier with_statement with_clause...
Return real external IP address.
def time_logger(name): start_time = time.time() yield end_time = time.time() total_time = end_time - start_time logging.info("%s; time: %ss", name, total_time)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement yield expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identif...
This logs the time usage of a code block
def _round(ctx, number, num_digits): number = conversions.to_decimal(number, ctx) num_digits = conversions.to_integer(num_digits, ctx) return decimal_round(number, num_digits, ROUND_HALF_UP)
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 ...
Rounds a number to a specified number of digits
def adduser(app, username, password): with app.app_context(): create_user(username=username, password=password) click.echo('user created!')
module function_definition identifier parameters identifier identifier identifier block with_statement with_clause with_item call attribute identifier identifier argument_list block expression_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier expressio...
Add new user with admin access
def setup(self, **kwargs): for key in kwargs: if key not in self.config.keys(): raise error.GrabMisuseError('Unknown option: %s' % key) if 'url' in kwargs: if self.config.get('url'): kwargs['url'] = self.make_url_absolute(kwargs['url']) sel...
module function_definition identifier parameters identifier dictionary_splat_pattern identifier block for_statement identifier identifier block if_statement comparison_operator identifier call attribute attribute identifier identifier identifier argument_list block raise_statement call attribute identifier identifier a...
Setting up Grab instance configuration.
def shutdown(self): if not self._shutdown: self._data_queue.put((None, None)) self._fetcher.join() for _ in range(self._num_workers): self._key_queue.put((None, None)) for w in self._workers: if w.is_alive(): w.t...
module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list tuple none none expression_statement call attribute attribute identifier identifier identifier ar...
Shutdown internal workers by pushing terminate signals.
def delete(self): try: self.revert() except errors.ChangelistError: pass self._connection.run(['change', '-d', str(self._change)])
module function_definition identifier parameters identifier block try_statement block expression_statement call attribute identifier identifier argument_list except_clause attribute identifier identifier block pass_statement expression_statement call attribute attribute identifier identifier identifier argument_list li...
Reverts all files in this changelist then deletes the changelist from perforce
def bind(cls): document["show_author_picker"].bind("click", lambda x: cls.show()) cls.storno_btn_el.bind("click", lambda x: cls.hide()) cls.pick_btn_el.bind("click", cls.on_pick_button_pressed)
module function_definition identifier parameters identifier block expression_statement call attribute subscript identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end lambda lambda_parameters identifier call attribute identifier identifier argumen...
Bind the callbacks to the buttons.
def PrintTags(self, file): print >>file, '/* Tag definition for %s */' % self._name print >>file, 'enum %s_ {' % self._name.lower() for entry in self._entries: print >>file, ' %s=%d,' % (self.EntryTagName(entry), entry.Tag()) print >>f...
module function_definition identifier parameters identifier identifier block print_statement chevron identifier binary_operator string string_start string_content string_end attribute identifier identifier print_statement chevron identifier binary_operator string string_start string_content string_end call attribute at...
Prints the tag definitions for a structure.
def form_node(cls): assert issubclass(cls, FormNode) res = attrs(init=False, slots=True)(cls) res._args = [] res._required_args = 0 res._rest_arg = None state = _FormArgMode.REQUIRED for field in fields(res): if 'arg_mode' in field.metadata: if state is _FormArgMode.REST:...
module function_definition identifier parameters identifier block assert_statement call identifier argument_list identifier identifier expression_statement assignment identifier call call identifier argument_list keyword_argument identifier false keyword_argument identifier true argument_list identifier expression_stat...
A class decorator to finalize fully derived FormNode subclasses.
def compare_version(self, version_string, op): from pkg_resources import parse_version from monty.operator import operator_from_str op = operator_from_str(op) return op(parse_version(self.version), parse_version(version_string))
module function_definition identifier parameters identifier identifier identifier block import_from_statement dotted_name identifier dotted_name identifier import_from_statement dotted_name identifier identifier dotted_name identifier expression_statement assignment identifier call identifier argument_list identifier r...
Compare Abinit version to `version_string` with operator `op`
def clean(self): if self.cleaners: yield from asyncio.wait([x() for x in self.cleaners], loop=self.loop)
module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement yield call attribute identifier identifier argument_list list_comprehension call identifier argument_list for_in_clause identifier attribute identifier identifier keyword_argument id...
Run all of the cleaners added by the user.
def _load_vocab_file(vocab_file, reserved_tokens=None): if reserved_tokens is None: reserved_tokens = RESERVED_TOKENS subtoken_list = [] with tf.gfile.Open(vocab_file, mode="r") as f: for line in f: subtoken = _native_to_unicode(line.strip()) subtoken = subtoken[1:-1] if subtoken in rese...
module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier identifier expression_statement assignment identifier list with_statement with_clause with_item as_pattern call attribute ...
Load vocabulary while ensuring reserved tokens are at the top.
def _do_scale(image, size): shape = tf.cast(tf.shape(image), tf.float32) w_greater = tf.greater(shape[0], shape[1]) shape = tf.cond(w_greater, lambda: tf.cast([shape[0] / shape[1] * size, size], tf.int32), lambda: tf.cast([size, shape[1] / shape[0] * size], tf.int32)) return ...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement assignment identifier call attribu...
Rescale the image by scaling the smaller spatial dimension to `size`.
def __AddWorkers(self, num_to_add): assert(self.__IsWebUiReady()) zone_to_ips = self.__GetZoneToWorkerIpsTable() zone_old_new = [] for zone, ips in zone_to_ips.iteritems(): num_nodes_in_zone = len(ips) num_nodes_to_add = 0 zone_old_new.append((zone, num_nodes_in_zone, num_nodes_to...
module function_definition identifier parameters identifier identifier block assert_statement parenthesized_expression call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier list for_stat...
Adds workers evenly across all enabled zones.
def _handshake(self, conn, addr): msg = conn.recv(len(MAGIC_REQ)) log.debug('Received message %s from %s', msg, addr) if msg != MAGIC_REQ: log.warning('%s is not a valid REQ message from %s', msg, addr) return log.debug('Sending the private key') conn.send...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start strin...
Ensures that the client receives the AES key.
def update(d, e): res = copy.copy(d) res.update(e) return res
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier
Return a copy of dict `d` updated with dict `e`.
def create(self, verbose=None): if not self.email_enabled: raise EmailNotEnabledError("See settings.EMAIL_ENABLED") response = requests.post( self.api_url, auth=("api", self.api_key), data={ "address": self.address, "name": ...
module function_definition identifier parameters identifier default_parameter identifier none block if_statement not_operator attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identi...
Returns a response after attempting to create the list.
def delete(self) : "deletes the document from the database" if self.URL is None : raise DeletionError("Can't delete a document that was not saved") r = self.connection.session.delete(self.URL) data = r.json() if (r.status_code != 200 and r.status_code != 202) or 'erro...
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end if_statement comparison_operator attribute identifier identifier none block raise_statement call identifier argument_list string string_start string_content string_end expression_statemen...
deletes the document from the database
def cnn_learner(data:DataBunch, base_arch:Callable, cut:Union[int,Callable]=None, pretrained:bool=True, lin_ftrs:Optional[Collection[int]]=None, ps:Floats=0.5, custom_head:Optional[nn.Module]=None, split_on:Optional[SplitFuncOrIdxList]=None, bn_final:bool=False, init=nn.init.kaiming_norm...
module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier typed_default_parameter identifier type generic_type identifier type_parameter type identifier type identifier none typed_default_parameter identifier type identifier true typed_default...
Build convnet style learner.
def stupid_hack(most=10, wait=None): if wait is not None: time.sleep(wait) else: time.sleep(random.randrange(1, most))
module function_definition identifier parameters default_parameter identifier integer default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement call attribute id...
Return a random time between 1 - 10 Seconds.
def question_default_loader(self, pk): try: obj = Question.objects.get(pk=pk) except Question.DoesNotExist: return None else: self.question_default_add_related_pks(obj) return obj
module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier except_clause attribute identifier identifier block return_statement ...
Load a Question from the database.
def after_import(self, dataset, result, using_transactions, dry_run, **kwargs): if not dry_run and any(r.import_type == RowResult.IMPORT_TYPE_NEW for r in result.rows): connection = connections[DEFAULT_DB_ALIAS] sequence_sql = connection.ops.sequence_reset_sql(no_style(), [self._meta.mod...
module function_definition identifier parameters identifier identifier identifier identifier identifier dictionary_splat_pattern identifier block if_statement boolean_operator not_operator identifier call identifier generator_expression comparison_operator attribute identifier identifier attribute identifier identifier...
Reset the SQL sequences after new objects are imported
def isotime(s): "Convert timestamps in ISO8661 format to and from Unix time." if type(s) == type(1): return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(s)) elif type(s) == type(1.0): date = int(s) msec = s - date date = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(s)) ...
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end if_statement comparison_operator call identifier argument_list identifier call identifier argument_list integer block return_statement call attribute identifier identifier argument_list s...
Convert timestamps in ISO8661 format to and from Unix time.
def executable_exists(executable): for directory in os.getenv("PATH").split(":"): if os.path.exists(os.path.join(directory, executable)): return True return False
module function_definition identifier parameters identifier block for_statement identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier argument_list string string_start string_content string_end block if_statement call attribute attribute id...
Test if an executable is available on the system.
def git_sha_metadata(content, git_content): if not content.settings['GIT_SHA_METADATA']: return if not git_content.is_committed(): return content.metadata['gitsha_newest'] = str(git_content.get_newest_commit()) content.metadata['gitsha_oldest'] = str(git_content.get_oldest_commit())
module function_definition identifier parameters identifier identifier block if_statement not_operator subscript attribute identifier identifier string string_start string_content string_end block return_statement if_statement not_operator call attribute identifier identifier argument_list block return_statement expres...
Add sha metadata to content
def convert_kv(key, val, attr_type, attr={}, cdata=False): LOG.info('Inside convert_kv(): key="%s", val="%s", type(val) is: "%s"' % ( unicode_me(key), unicode_me(val), type(val).__name__) ) key, attr = make_valid_xml_name(key, attr) if attr_type: attr['type'] = get_xml_type(val) attr...
module function_definition identifier parameters identifier identifier identifier default_parameter identifier dictionary default_parameter identifier false block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple call identifier a...
Converts a number or string into an XML element
def _inspectArguments(self, args): if args: self.exec_path = PathStr(args[0]) else: self.exec_path = None session_name = None args = args[1:] openSession = False for arg in args: if arg in ('-h', '--help'): sel...
module function_definition identifier parameters identifier identifier block if_statement identifier block expression_statement assignment attribute identifier identifier call identifier argument_list subscript identifier integer else_clause block expression_statement assignment attribute identifier identifier none exp...
inspect the command-line-args and give them to appBase