code
stringlengths
51
2.34k
sequence
stringlengths
186
3.94k
docstring
stringlengths
11
171
def decode_content(self): ct = self.headers.get('content-type') if ct: ct, options = parse_options_header(ct) charset = options.get('charset') if ct in JSON_CONTENT_TYPES: return self.json() elif ct.startswith('text/'): return self.text elif ct == FORM_URL_ENCODED: return parse_qsl(self.content.decode(charset), keep_blank_values=True) return self.content
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 if_statement identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier identifier block return_statement call attribute identifier identifier argument_list elif_clause call attribute identifier identifier argument_list string string_start string_content string_end block return_statement attribute identifier identifier elif_clause comparison_operator identifier identifier block return_statement call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier true return_statement attribute identifier identifier
Return the best possible representation of the response body.
def _node_digest(self) -> Dict[str, Any]: res = {"kind": self._yang_class()} if self.mandatory: res["mandatory"] = True if self.description: res["description"] = self.description return res
module function_definition identifier parameters identifier type generic_type identifier type_parameter type identifier type identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end call attribute identifier identifier argument_list if_statement attribute identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end true if_statement attribute identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier return_statement identifier
Return dictionary of receiver's properties suitable for clients.
def _find_id(self, result, uid): if isinstance(result, list): if any([self._find_id(value, uid) for value in result]): return True if isinstance(result, dict): list_children = [value for value in result.values() if isinstance(value, list)] for value in list_children: if self._find_id(value, uid): return True dict_children = [value for value in result.values() if isinstance(value, dict)] for value in dict_children: if self._find_id(value, uid): return True if not list_children and not dict_children and 'id' in result: result_id = result['id'] return result_id == type(result_id)(uid) return False
module function_definition identifier parameters identifier identifier identifier block if_statement call identifier argument_list identifier identifier block if_statement call identifier argument_list list_comprehension call attribute identifier identifier argument_list identifier identifier for_in_clause identifier identifier block return_statement true if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier list_comprehension identifier for_in_clause identifier call attribute identifier identifier argument_list if_clause call identifier argument_list identifier identifier for_statement identifier identifier block if_statement call attribute identifier identifier argument_list identifier identifier block return_statement true expression_statement assignment identifier list_comprehension identifier for_in_clause identifier call attribute identifier identifier argument_list if_clause call identifier argument_list identifier identifier for_statement identifier identifier block if_statement call attribute identifier identifier argument_list identifier identifier block return_statement true if_statement boolean_operator boolean_operator not_operator identifier not_operator identifier comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end return_statement comparison_operator identifier call call identifier argument_list identifier argument_list identifier return_statement false
This method performs a depth-first search for the given uid in the dictionary of results.
def make_dirs_if_dont_exist(path): if path[-1] not in ['/']: path += '/' path = os.path.dirname(path) if path != '': try: os.makedirs(path) except OSError: pass
module function_definition identifier parameters identifier block if_statement comparison_operator subscript identifier unary_operator integer list string string_start string_content string_end block expression_statement augmented_assignment identifier string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator identifier string string_start string_end block try_statement block expression_statement call attribute identifier identifier argument_list identifier except_clause identifier block pass_statement
Create directories in path if they do not exist
def _no_access(basedir): import os return not os.access(basedir, os.W_OK | os.X_OK)
module function_definition identifier parameters identifier block import_statement dotted_name identifier return_statement not_operator call attribute identifier identifier argument_list identifier binary_operator attribute identifier identifier attribute identifier identifier
Return True if the given base dir is not accessible or writeable
def _chunks(self, l, n): l.sort() newn = int(1.0 * len(l) / n + 0.5) for i in range(0, n-1): yield l[i*newn:i*newn+newn] yield l[n*newn-newn:]
module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list binary_operator binary_operator binary_operator float call identifier argument_list identifier identifier float for_statement identifier call identifier argument_list integer binary_operator identifier integer block expression_statement yield subscript identifier slice binary_operator identifier identifier binary_operator binary_operator identifier identifier identifier expression_statement yield subscript identifier slice binary_operator binary_operator identifier identifier identifier
Yield n successive chunks from a list l.
def reduce_log_sum_exp(attrs, inputs, proto_obj): keep_dims = True if 'keepdims' not in attrs else attrs.get('keepdims') exp_op = symbol.exp(inputs[0]) sum_op = symbol.sum(exp_op, axis=attrs.get('axes'), keepdims=keep_dims) log_sym = symbol.log(sum_op) return log_sym, attrs, inputs
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier conditional_expression true comparison_operator string string_start string_content string_end identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement expression_list identifier identifier identifier
Reduce the array along a given axis by log sum exp value
def trim_req(req): reqfirst = next(iter(req)) if '.' in reqfirst: return {reqfirst.split('.')[0]: req[reqfirst]} return req
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier if_statement comparison_operator string string_start string_content string_end identifier block return_statement dictionary pair subscript call attribute identifier identifier argument_list string string_start string_content string_end integer subscript identifier identifier return_statement identifier
Trim any function off of a requisite
def dict( self, *, include: 'SetStr' = None, exclude: 'SetStr' = None, by_alias: bool = False, skip_defaults: bool = False ) -> 'DictStrAny': get_key = self._get_key_factory(by_alias) get_key = partial(get_key, self.fields) return_keys = self._calculate_keys(include=include, exclude=exclude, skip_defaults=skip_defaults) if return_keys is None: return {get_key(k): v for k, v in self._iter(by_alias=by_alias, skip_defaults=skip_defaults)} else: return { get_key(k): v for k, v in self._iter(by_alias=by_alias, skip_defaults=skip_defaults) if k in return_keys }
module function_definition identifier parameters identifier keyword_separator typed_default_parameter identifier type string string_start string_content string_end none typed_default_parameter identifier type string string_start string_content string_end none typed_default_parameter identifier type identifier false typed_default_parameter identifier type identifier false type string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier if_statement comparison_operator identifier none block return_statement dictionary_comprehension pair call identifier argument_list identifier identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier else_clause block return_statement dictionary_comprehension pair call identifier argument_list identifier identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier if_clause comparison_operator identifier identifier
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
def parse_man_page(command, platform): page_path = find_page_location(command, platform) output_lines = parse_page(page_path) return output_lines
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list identifier return_statement identifier
Parse the man page and return the parsed lines.
def terms_required(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if DJANGO_VERSION <= (2, 0, 0): user_authenticated = request.user.is_authenticated() else: user_authenticated = request.user.is_authenticated if not user_authenticated or not TermsAndConditions.get_active_terms_not_agreed_to(request.user): return view_func(request, *args, **kwargs) current_path = request.path login_url_parts = list(urlparse(ACCEPT_TERMS_PATH)) querystring = QueryDict(login_url_parts[4], mutable=True) querystring['returnTo'] = current_path login_url_parts[4] = querystring.urlencode(safe='/') return HttpResponseRedirect(urlunparse(login_url_parts)) return _wrapped_view
module function_definition identifier parameters identifier block decorated_definition decorator call identifier argument_list identifier keyword_argument identifier call identifier argument_list identifier function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement comparison_operator identifier tuple integer integer integer block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list else_clause block expression_statement assignment identifier attribute attribute identifier identifier identifier if_statement boolean_operator not_operator identifier not_operator call attribute identifier identifier argument_list attribute identifier identifier block return_statement call identifier argument_list identifier list_splat identifier dictionary_splat identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list subscript identifier integer keyword_argument identifier true expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment subscript identifier integer call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end return_statement call identifier argument_list call identifier argument_list identifier return_statement identifier
This decorator checks to see if the user is logged in, and if so, if they have accepted the site terms.
def _extract_constants(self, specification): constants = {} for attribute in specification.attributes: if attribute.allowed_choices and len(attribute.allowed_choices) > 0: name = attribute.local_name.upper() for choice in attribute.allowed_choices: constants["CONST_%s_%s" % (name, choice.upper())] = choice return constants
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary for_statement identifier attribute identifier identifier block if_statement boolean_operator attribute identifier identifier comparison_operator call identifier argument_list attribute identifier identifier integer block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list for_statement identifier attribute identifier identifier block expression_statement assignment subscript identifier binary_operator string string_start string_content string_end tuple identifier call attribute identifier identifier argument_list identifier return_statement identifier
Removes attributes and computes constants
def write_dataframe_to_idb(self, ticker): cachepath = self._cache cachefile = ('%s/%s-1M.csv.gz' % (cachepath, ticker)) if not os.path.exists(cachefile): log.warn('Import file does not exist: %s' % (cachefile)) return df = pd.read_csv(cachefile, compression='infer', header=0, infer_datetime_format=True) df['Datetime'] = pd.to_datetime(df['Date'] + ' ' + df['Time']) df = df.set_index('Datetime') df = df.drop(['Date', 'Time'], axis=1) try: self.dfdb.write_points(df, ticker) except InfluxDBClientError as err: log.error('Write to database failed: %s' % err)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier parenthesized_expression binary_operator string string_start string_content string_end tuple identifier identifier if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end parenthesized_expression identifier return_statement expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier integer keyword_argument identifier true expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list binary_operator binary_operator subscript identifier string string_start string_content string_end string string_start string_content string_end subscript identifier string string_start string_content string_end 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 list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier integer try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier
Write Pandas Dataframe to InfluxDB database
def FindInstalledFiles(self): from SCons.Tool import install if install._UNIQUE_INSTALLED_FILES is None: install._UNIQUE_INSTALLED_FILES = SCons.Util.uniquer_hashables(install._INSTALLED_FILES) return install._UNIQUE_INSTALLED_FILES
module function_definition identifier parameters identifier block import_from_statement dotted_name identifier identifier dotted_name identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier return_statement attribute identifier identifier
returns the list of all targets of the Install and InstallAs Builder.
def _to_datalibrary(fname, gi, folder_name, sample_info, config): library = _get_library(gi, sample_info, config) libitems = gi.libraries.show_library(library.id, contents=True) folder = _get_folder(gi, folder_name, library, libitems) _file_to_folder(gi, fname, sample_info, libitems, library, folder)
module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier keyword_argument identifier true expression_statement assignment identifier call identifier argument_list identifier identifier identifier identifier expression_statement call identifier argument_list identifier identifier identifier identifier identifier identifier
Upload a file to a Galaxy data library in a project specific folder.
def neighbors_iter(self): for n, adj in self.graph.adj.items(): yield n, {n: attr["bond"] for n, attr in adj.items()}
module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier call attribute attribute attribute identifier identifier identifier identifier argument_list block expression_statement yield expression_list identifier dictionary_comprehension pair identifier subscript identifier string string_start string_content string_end for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list
Iterate over atoms and return its neighbors.
def validate(self, value): if self.blank and value == '': return True if URIValidator.uri_regex.match(value): self._choice = value return True else: self.error_message = '%s is not a valid URI' % value return False
module function_definition identifier parameters identifier identifier block if_statement boolean_operator attribute identifier identifier comparison_operator identifier string string_start string_end block return_statement true if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment attribute identifier identifier identifier return_statement true else_clause block expression_statement assignment attribute identifier identifier binary_operator string string_start string_content string_end identifier return_statement false
Return a boolean indicating if the value is a valid URI
def mime_type(template): _, ext = os.path.splitext(template.filename) return EXTENSION_MAP.get(ext, 'text/html; charset=utf-8')
module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier return_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end
infer the content-type from the extension
def normal_from_points(a, b, c): x1, y1, z1 = a x2, y2, z2 = b x3, y3, z3 = c ab = (x2 - x1, y2 - y1, z2 - z1) ac = (x3 - x1, y3 - y1, z3 - z1) x, y, z = cross(ab, ac) d = (x * x + y * y + z * z) ** 0.5 return (x / d, y / d, z / d)
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment pattern_list identifier identifier identifier identifier expression_statement assignment pattern_list identifier identifier identifier identifier expression_statement assignment pattern_list identifier identifier identifier identifier expression_statement assignment identifier tuple binary_operator identifier identifier binary_operator identifier identifier binary_operator identifier identifier expression_statement assignment identifier tuple binary_operator identifier identifier binary_operator identifier identifier binary_operator identifier identifier expression_statement assignment pattern_list identifier identifier identifier call identifier argument_list identifier identifier expression_statement assignment identifier binary_operator parenthesized_expression binary_operator binary_operator binary_operator identifier identifier binary_operator identifier identifier binary_operator identifier identifier float return_statement tuple binary_operator identifier identifier binary_operator identifier identifier binary_operator identifier identifier
Computes a normal vector given three points.
def to_pascal(arr, is_dp=False): threshold = 400 if is_dp else 1200 if np.max(np.abs(arr)) < threshold: warn_msg = "Conversion applied: hPa -> Pa to array: {}".format(arr) logging.debug(warn_msg) return arr*100. return arr
module function_definition identifier parameters identifier default_parameter identifier false block expression_statement assignment identifier conditional_expression integer identifier integer if_statement comparison_operator call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier return_statement binary_operator identifier float return_statement identifier
Force data with units either hPa or Pa to be in Pa.
def load_calibration(labware: Labware): calibration_path = CONFIG['labware_calibration_offsets_dir_v4'] labware_offset_path = calibration_path/'{}.json'.format(labware._id) if labware_offset_path.exists(): calibration_data = _read_file(str(labware_offset_path)) offset_array = calibration_data['default']['offset'] offset = Point(x=offset_array[0], y=offset_array[1], z=offset_array[2]) labware.set_calibration(offset) if 'tipLength' in calibration_data.keys(): tip_length = calibration_data['tipLength']['length'] labware.tip_length = tip_length
module function_definition identifier parameters typed_parameter identifier type identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier binary_operator identifier call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier if_statement call attribute identifier identifier argument_list block expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier expression_statement assignment identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call identifier argument_list keyword_argument identifier subscript identifier integer keyword_argument identifier subscript identifier integer keyword_argument identifier subscript identifier integer expression_statement call attribute identifier identifier argument_list identifier if_statement comparison_operator string string_start string_content string_end call attribute identifier identifier argument_list block expression_statement assignment identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment attribute identifier identifier identifier
Look up a calibration if it exists and apply it to the given labware.
def discard_logcat_logs(self): if self.driver_wrapper.is_android_test(): try: self.driver_wrapper.driver.get_log('logcat') except Exception: pass
module function_definition identifier parameters identifier block if_statement call attribute attribute identifier identifier identifier argument_list block try_statement block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end except_clause identifier block pass_statement
Discard previous logcat logs
def make_syntax_err(self, err, original): msg, loc = err.args return self.make_err(CoconutSyntaxError, msg, original, loc)
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment pattern_list identifier identifier attribute identifier identifier return_statement call attribute identifier identifier argument_list identifier identifier identifier identifier
Make a CoconutSyntaxError from a CoconutDeferredSyntaxError.
def close(self): h = self.gdx_handle gdxcc.gdxClose(h) gdxcc.gdxFree(h)
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier
Close Gdx file and free up resources.
def register_hook(self, event, hook): if event not in self.hooks: raise ValueError('Unsupported event specified, with event name "%s"' % (event)) if isinstance(hook, Callable): self.hooks[event].append(hook) elif hasattr(hook, '__iter__'): self.hooks[event].extend(h for h in hook if isinstance(h, Callable))
module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end parenthesized_expression identifier if_statement call identifier argument_list identifier identifier block expression_statement call attribute subscript attribute identifier identifier identifier identifier argument_list identifier elif_clause call identifier argument_list identifier string string_start string_content string_end block expression_statement call attribute subscript attribute identifier identifier identifier identifier generator_expression identifier for_in_clause identifier identifier if_clause call identifier argument_list identifier identifier
Properly register a hook.
def crps_climo(self): o_bar = self.errors["O"].values / float(self.num_forecasts) crps_c = np.sum(self.num_forecasts * (o_bar ** 2) - o_bar * self.errors["O"].values * 2.0 + self.errors["O_2"].values) / float(self.thresholds.size * self.num_forecasts) return crps_c
module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator attribute subscript attribute identifier identifier string string_start string_content string_end identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list binary_operator binary_operator binary_operator attribute identifier identifier parenthesized_expression binary_operator identifier integer binary_operator binary_operator identifier attribute subscript attribute identifier identifier string string_start string_content string_end identifier float attribute subscript attribute identifier identifier string string_start string_content string_end identifier call identifier argument_list binary_operator attribute attribute identifier identifier identifier attribute identifier identifier return_statement identifier
Calculate the climatological CRPS.
def verify(self, payload): if not self.authenticator: return payload try: self.authenticator.auth(payload) return self.authenticator.unsigned(payload) except AuthenticatorInvalidSignature: raise except Exception as exception: raise AuthenticateError(str(exception))
module function_definition identifier parameters identifier identifier block if_statement not_operator attribute identifier identifier block return_statement identifier try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list identifier return_statement call attribute attribute identifier identifier identifier argument_list identifier except_clause identifier block raise_statement except_clause as_pattern identifier as_pattern_target identifier block raise_statement call identifier argument_list call identifier argument_list identifier
Verify payload authenticity via the supplied authenticator
def chunks(iterable, size=50): batch = [] for n in iterable: batch.append(n) if len(batch) % size == 0: yield batch batch = [] if batch: yield batch
module function_definition identifier parameters identifier default_parameter identifier integer block expression_statement assignment identifier list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier if_statement comparison_operator binary_operator call identifier argument_list identifier identifier integer block expression_statement yield identifier expression_statement assignment identifier list if_statement identifier block expression_statement yield identifier
Break an iterable into lists of size
def _bond_length_low(r, deriv): r = Vector3(3, deriv, r, (0, 1, 2)) d = r.norm() return d.results()
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list integer identifier identifier tuple integer integer integer expression_statement assignment identifier call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list
Similar to bond_length, but with a relative vector
def to_existing_absolute_path(string): value = os.path.abspath(string) if not os.path.exists( value ) or not os.path.isdir( value ): msg = '"%r" is not a valid path to a directory.' % string raise argparse.ArgumentTypeError(msg) return value
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement boolean_operator not_operator call attribute attribute identifier identifier identifier argument_list identifier not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end identifier raise_statement call attribute identifier identifier argument_list identifier return_statement identifier
Converts a path into its absolute path and verifies that it exists or throws an exception.
def clean_html(context, data): doc = _get_html_document(context, data) if doc is None: context.emit(data=data) return remove_paths = context.params.get('remove_paths') for path in ensure_list(remove_paths): for el in doc.findall(path): el.drop_tree() html_text = html.tostring(doc, pretty_print=True) content_hash = context.store_data(html_text) data['content_hash'] = content_hash context.emit(data=data)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier return_statement expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end for_statement identifier call identifier argument_list identifier block for_statement identifier call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier true expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier
Clean an HTML DOM and store the changed version.
def to_array(self, channels=2): if self.fade_type == "linear": return np.linspace(self.in_volume, self.out_volume, self.duration * channels)\ .reshape(self.duration, channels) elif self.fade_type == "exponential": if self.in_volume < self.out_volume: return (np.logspace(8, 1, self.duration * channels, base=.5) * ( self.out_volume - self.in_volume) / 0.5 + self.in_volume).reshape(self.duration, channels) else: return (np.logspace(1, 8, self.duration * channels, base=.5 ) * (self.in_volume - self.out_volume) / 0.5 + self.out_volume).reshape(self.duration, channels) elif self.fade_type == "cosine": return
module function_definition identifier parameters identifier default_parameter identifier integer block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block return_statement call attribute call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier binary_operator attribute identifier identifier identifier line_continuation identifier argument_list attribute identifier identifier identifier elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block return_statement call attribute parenthesized_expression binary_operator binary_operator binary_operator call attribute identifier identifier argument_list integer integer binary_operator attribute identifier identifier identifier keyword_argument identifier float parenthesized_expression binary_operator attribute identifier identifier attribute identifier identifier float attribute identifier identifier identifier argument_list attribute identifier identifier identifier else_clause block return_statement call attribute parenthesized_expression binary_operator binary_operator binary_operator call attribute identifier identifier argument_list integer integer binary_operator attribute identifier identifier identifier keyword_argument identifier float parenthesized_expression binary_operator attribute identifier identifier attribute identifier identifier float attribute identifier identifier identifier argument_list attribute identifier identifier identifier elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block return_statement
Generate the array of volume multipliers for the dynamic
def previous_row(self): if self.mode == self.SYMBOL_MODE: self.select_row(-1) return prev_row = self.current_row() - 1 if prev_row >= 0: title = self.list.item(prev_row).text() else: title = '' if prev_row == 0 and '</b></big><br>' in title: self.list.scrollToTop() elif '</b></big><br>' in title: self.select_row(-2) else: self.select_row(-1)
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list unary_operator integer return_statement expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list integer if_statement comparison_operator identifier integer block expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier identifier argument_list else_clause block expression_statement assignment identifier string string_start string_end if_statement boolean_operator comparison_operator identifier integer comparison_operator string string_start string_content string_end identifier block expression_statement call attribute attribute identifier identifier identifier argument_list elif_clause comparison_operator string string_start string_content string_end identifier block expression_statement call attribute identifier identifier argument_list unary_operator integer else_clause block expression_statement call attribute identifier identifier argument_list unary_operator integer
Select previous row in list widget.
def cart2frac_all(coordinates, lattice_array): frac_coordinates = deepcopy(coordinates) for coord in range(frac_coordinates.shape[0]): frac_coordinates[coord] = fractional_from_cartesian( frac_coordinates[coord], lattice_array) return frac_coordinates
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier for_statement identifier call identifier argument_list subscript attribute identifier identifier integer block expression_statement assignment subscript identifier identifier call identifier argument_list subscript identifier identifier identifier return_statement identifier
Convert all cartesian coordinates to fractional.
def go_to(self, url_or_text): if is_text_string(url_or_text): url = QUrl(url_or_text) else: url = url_or_text self.notebookwidget.load(url)
module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier block expression_statement assignment identifier call identifier argument_list identifier else_clause block expression_statement assignment identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier
Go to page utl.
def post(self, request, *args, **kwargs): current_timestamp = "%.0f" % time.time() user_id_str = u"{0}".format(request.user.id) token = generate_token(settings.CENTRIFUGE_SECRET, user_id_str, "{0}".format(current_timestamp), info="") participant = Participant.objects.get(id=request.user.id) channels = [] for thread in Thread.managers.get_threads_where_participant_is_active(participant_id=participant.id): channels.append( build_channel(settings.CENTRIFUGO_MESSAGE_NAMESPACE, thread.id, thread.participants.all()) ) threads_channel = build_channel(settings.CENTRIFUGO_THREAD_NAMESPACE, request.user.id, [request.user.id]) channels.append(threads_channel) to_return = { 'user': user_id_str, 'timestamp': current_timestamp, 'token': token, 'connection_url': "{0}connection/".format(settings.CENTRIFUGE_ADDRESS), 'channels': channels, 'debug': settings.DEBUG, } return HttpResponse(json.dumps(to_return), content_type='application/json; charset=utf-8')
module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end call attribute identifier identifier argument_list expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list attribute attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier identifier call attribute string string_start string_content string_end identifier argument_list identifier keyword_argument identifier string string_start string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute attribute identifier identifier identifier expression_statement assignment identifier list for_statement identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list attribute identifier identifier attribute identifier identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call identifier argument_list attribute identifier identifier attribute attribute identifier identifier identifier list attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end attribute identifier identifier return_statement call identifier argument_list call attribute identifier identifier argument_list identifier keyword_argument identifier string string_start string_content string_end
Returns a token identifying the user in Centrifugo.
def bounded_stats_per_chunk(chunk, block_counts, start, stop): chunk_z, chunk_x = chunk.get_coords() for z in range(16): world_z = z + chunk_z*16 if ( (start != None and world_z < int(start[2])) or (stop != None and world_z > int(stop[2])) ): break for x in range(16): world_x = x + chunk_x*16 if ( (start != None and world_x < int(start[0])) or (stop != None and world_x > int(stop[0])) ): break for y in range(chunk.get_max_height() + 1): if ( (start != None and y < int(start[1])) or (stop != None and y > int(stop[1])) ): break block_id = chunk.get_block(x,y,z) if block_id != None: try: block_counts[block_id] += 1 except KeyError: block_counts[block_id] = 1
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list for_statement identifier call identifier argument_list integer block expression_statement assignment identifier binary_operator identifier binary_operator identifier integer if_statement parenthesized_expression boolean_operator parenthesized_expression boolean_operator comparison_operator identifier none comparison_operator identifier call identifier argument_list subscript identifier integer parenthesized_expression boolean_operator comparison_operator identifier none comparison_operator identifier call identifier argument_list subscript identifier integer block break_statement for_statement identifier call identifier argument_list integer block expression_statement assignment identifier binary_operator identifier binary_operator identifier integer if_statement parenthesized_expression boolean_operator parenthesized_expression boolean_operator comparison_operator identifier none comparison_operator identifier call identifier argument_list subscript identifier integer parenthesized_expression boolean_operator comparison_operator identifier none comparison_operator identifier call identifier argument_list subscript identifier integer block break_statement for_statement identifier call identifier argument_list binary_operator call attribute identifier identifier argument_list integer block if_statement parenthesized_expression boolean_operator parenthesized_expression boolean_operator comparison_operator identifier none comparison_operator identifier call identifier argument_list subscript identifier integer parenthesized_expression boolean_operator comparison_operator identifier none comparison_operator identifier call identifier argument_list subscript identifier integer block break_statement expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier identifier if_statement comparison_operator identifier none block try_statement block expression_statement augmented_assignment subscript identifier identifier integer except_clause identifier block expression_statement assignment subscript identifier identifier integer
Given a chunk, return the number of blocks types within the specified selection
def restoredata(filename=None): if filename is None: filename = 'credolib_state.pickle' ns = get_ipython().user_ns with open(filename, 'rb') as f: d = pickle.load(f) for k in d.keys(): ns[k] = d[k]
module function_definition identifier parameters default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier attribute call identifier argument_list identifier 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 assignment identifier call attribute identifier identifier argument_list identifier for_statement identifier call attribute identifier identifier argument_list block expression_statement assignment subscript identifier identifier subscript identifier identifier
Restore the state of the credolib workspace from a pickle file.
def clear(self): for p in self._txBody.p_lst[1:]: self._txBody.remove(p) p = self.paragraphs[0] p.clear()
module function_definition identifier parameters identifier block for_statement identifier subscript attribute attribute identifier identifier identifier slice integer block expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier subscript attribute identifier identifier integer expression_statement call attribute identifier identifier argument_list
Remove all paragraphs except one empty one.
def parse_config_list(config_list): if config_list is None: return {} else: mapping = {} for pair in config_list: if (constants.CONFIG_SEPARATOR not in pair) or (pair.count(constants.CONFIG_SEPARATOR) != 1): raise ValueError("configs must be passed as two strings separted by a %s", constants.CONFIG_SEPARATOR) (config, value) = pair.split(constants.CONFIG_SEPARATOR) mapping[config] = value return mapping
module function_definition identifier parameters identifier block if_statement comparison_operator identifier none block return_statement dictionary else_clause block expression_statement assignment identifier dictionary for_statement identifier identifier block if_statement boolean_operator parenthesized_expression comparison_operator attribute identifier identifier identifier parenthesized_expression comparison_operator call attribute identifier identifier argument_list attribute identifier identifier integer block raise_statement call identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement assignment tuple_pattern identifier identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment subscript identifier identifier identifier return_statement identifier
Parse a list of configuration properties separated by '='
def fa2s2b(fastas): s2b = {} for fa in fastas: for seq in parse_fasta(fa): s = seq[0].split('>', 1)[1].split()[0] s2b[s] = fa.rsplit('/', 1)[-1].rsplit('.', 1)[0] return s2b
module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary for_statement identifier identifier block for_statement identifier call identifier argument_list identifier block expression_statement assignment identifier subscript call attribute subscript call attribute subscript identifier integer identifier argument_list string string_start string_content string_end integer integer identifier argument_list integer expression_statement assignment subscript identifier identifier subscript call attribute subscript call attribute identifier identifier argument_list string string_start string_content string_end integer unary_operator integer identifier argument_list string string_start string_content string_end integer integer return_statement identifier
convert fastas to s2b dictionary
def __get_vibration_code(self, left_motor, right_motor, duration): inner_event = struct.pack( '2h6x2h2x2H28x', 0x50, -1, duration, 0, int(left_motor * 65535), int(right_motor * 65535)) buf_conts = ioctl(self._write_device, 1076905344, inner_event) return int(codecs.encode(buf_conts[1:3], 'hex'), 16)
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end integer unary_operator integer identifier integer call identifier argument_list binary_operator identifier integer call identifier argument_list binary_operator identifier integer expression_statement assignment identifier call identifier argument_list attribute identifier identifier integer identifier return_statement call identifier argument_list call attribute identifier identifier argument_list subscript identifier slice integer integer string string_start string_content string_end integer
This is some crazy voodoo, if you can simplify it, please do.
def inject_extra_args(callback, request, kwargs): annots = dict(callback.__annotations__) del annots['return'] for param_name, (param_type, _) in annots.items(): if param_type == Ptypes.path: continue elif param_type == Ptypes.body: value = getattr(request, PTYPE_TO_REQUEST_PROPERTY[param_type]) value = json.loads(value.decode('utf-8')) else: get = lambda attr: getattr(request, attr).get(param_name, None) value = get(PTYPE_TO_REQUEST_PROPERTY[param_type]) if value is not None: kwargs[param_name] = value
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier delete_statement subscript identifier string string_start string_content string_end for_statement pattern_list identifier tuple_pattern identifier identifier call attribute identifier identifier argument_list block if_statement comparison_operator identifier attribute identifier identifier block continue_statement elif_clause comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier call identifier argument_list identifier subscript identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end else_clause block expression_statement assignment identifier lambda lambda_parameters identifier call attribute call identifier argument_list identifier identifier identifier argument_list identifier none expression_statement assignment identifier call identifier argument_list subscript identifier identifier if_statement comparison_operator identifier none block expression_statement assignment subscript identifier identifier identifier
Inject extra arguments from header, body, form.
def pipe_util(func): @wraps(func) def pipe_util_wrapper(function, *args, **kwargs): if isinstance(function, XObject): function = ~function original_function = function if args or kwargs: function = xpartial(function, *args, **kwargs) name = lambda: '%s(%s)' % (get_name(func), ', '.join( filter(None, (get_name(original_function), repr_args(*args, **kwargs))))) f = func(function) result = pipe | set_name(name, f) attrs = getattr(f, 'attrs', {}) for k, v in dict_items(attrs): setattr(result, k, v) return result return pipe_util_wrapper
module function_definition identifier parameters identifier block decorated_definition decorator call identifier argument_list identifier function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier unary_operator identifier expression_statement assignment identifier identifier if_statement boolean_operator identifier identifier block expression_statement assignment identifier call identifier argument_list identifier list_splat identifier dictionary_splat identifier expression_statement assignment identifier lambda binary_operator string string_start string_content string_end tuple call identifier argument_list identifier call attribute string string_start string_content string_end identifier argument_list call identifier argument_list none tuple call identifier argument_list identifier call identifier argument_list list_splat identifier dictionary_splat identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier binary_operator identifier call identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end dictionary for_statement pattern_list identifier identifier call identifier argument_list identifier block expression_statement call identifier argument_list identifier identifier identifier return_statement identifier return_statement identifier
Decorator that handles X objects and partial application for pipe-utils.
def transmit_by_fitness(from_whom, to_whom=None, what=None): parents = from_whom parent_fs = [p.fitness for p in parents] parent_probs = [(f / (1.0 * sum(parent_fs))) for f in parent_fs] rnd = random.random() temp = 0.0 for i, probability in enumerate(parent_probs): temp += probability if temp > rnd: parent = parents[i] break parent.transmit(what=what, to_whom=to_whom)
module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier identifier expression_statement assignment identifier list_comprehension attribute identifier identifier for_in_clause identifier identifier expression_statement assignment identifier list_comprehension parenthesized_expression binary_operator identifier parenthesized_expression binary_operator float call identifier argument_list identifier for_in_clause identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier float for_statement pattern_list identifier identifier call identifier argument_list identifier block expression_statement augmented_assignment identifier identifier if_statement comparison_operator identifier identifier block expression_statement assignment identifier subscript identifier identifier break_statement expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier
Choose a parent with probability proportional to their fitness.
def draw_circle(self, color, world_loc, world_radius, thickness=0): if world_radius > 0: center = self.world_to_surf.fwd_pt(world_loc).round() radius = max(1, int(self.world_to_surf.fwd_dist(world_radius))) pygame.draw.circle(self.surf, color, center, radius, thickness if thickness < radius else 0)
module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier integer block if_statement comparison_operator identifier integer block expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier identifier argument_list expression_statement assignment identifier call identifier argument_list integer call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier identifier identifier conditional_expression identifier comparison_operator identifier identifier integer
Draw a circle using world coordinates and radius.
def _merge_last(values, merge_after, merge_with=' '): if len(values) > merge_after: values = values[0:(merge_after-1)] + [merge_with.join(values[(merge_after-1):])] return values
module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end block if_statement comparison_operator call identifier argument_list identifier identifier block expression_statement assignment identifier binary_operator subscript identifier slice integer parenthesized_expression binary_operator identifier integer list call attribute identifier identifier argument_list subscript identifier slice parenthesized_expression binary_operator identifier integer return_statement identifier
Merge values all values after X into the last value
def singledispatch(*, nargs=None, nouts=None, ndefs=None): def wrapper(f): return wraps(f)(SingleDispatchFunction(f, nargs=nargs, nouts=nouts, ndefs=ndefs)) return wrapper
module function_definition identifier parameters keyword_separator default_parameter identifier none default_parameter identifier none default_parameter identifier none block function_definition identifier parameters identifier block return_statement call call identifier argument_list identifier argument_list call identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier return_statement identifier
singledispatch decorate of both functools.singledispatch and func
def del_item(self): item = self.current rectangle = self.items[item] self.canvas.delete(item, rectangle) if callable(self._callback_del): self._callback_del(item, rectangle)
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier if_statement call identifier argument_list attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier
Delete the current item on the Canvas.
def calc_check_digit(digits): ints = [int(d) for d in digits] l = len(ints) odds = slice((l - 1) % 2, l, 2) even = slice(l % 2, l, 2) checksum = 3 * sum(ints[odds]) + sum(ints[even]) return str(-checksum % 10)
module function_definition identifier parameters identifier block expression_statement assignment identifier list_comprehension call identifier argument_list identifier for_in_clause identifier identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list binary_operator parenthesized_expression binary_operator identifier integer integer identifier integer expression_statement assignment identifier call identifier argument_list binary_operator identifier integer identifier integer expression_statement assignment identifier binary_operator binary_operator integer call identifier argument_list subscript identifier identifier call identifier argument_list subscript identifier identifier return_statement call identifier argument_list binary_operator unary_operator identifier integer
Calculate and return the GS1 check digit.
def calc_basics(width=-1, length=-1, height=2.4, prevailing_wind=2.8): if width == -1: width = int(input('enter building width : ')) if length == -1: length = int(input('enter building length : ')) res = {} res['area'] = width * length res['perim'] = 2 * width + 2 * length res['roof_cladding'] = res['area'] res['wall_cladding'] = res['perim'] * height pprint(res) return res
module function_definition identifier parameters default_parameter identifier unary_operator integer default_parameter identifier unary_operator integer default_parameter identifier float default_parameter identifier float block if_statement comparison_operator identifier unary_operator integer block expression_statement assignment identifier call identifier argument_list call identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier unary_operator integer block expression_statement assignment identifier call identifier argument_list call identifier argument_list string string_start string_content string_end expression_statement assignment identifier dictionary expression_statement assignment subscript identifier string string_start string_content string_end binary_operator identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end binary_operator binary_operator integer identifier binary_operator integer identifier expression_statement assignment subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end binary_operator subscript identifier string string_start string_content string_end identifier expression_statement call identifier argument_list identifier return_statement identifier
calculate various aspects of the structure
def determine_vocab(self, qualifier): vocab_value = VOCAB_INDEX.get(self.tag, None) if isinstance(vocab_value, dict): if qualifier is None: qualifier = 'None' return vocab_value.get(qualifier, None) elif vocab_value is not None: return vocab_value else: return None
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier none if_statement call identifier argument_list identifier identifier block if_statement comparison_operator identifier none block expression_statement assignment identifier string string_start string_content string_end return_statement call attribute identifier identifier argument_list identifier none elif_clause comparison_operator identifier none block return_statement identifier else_clause block return_statement none
Determine the vocab from the qualifier.
def _initialize_client_from_environment(): global _client, project_id, write_key, read_key, master_key, base_url if _client is None: project_id = project_id or os.environ.get("KEEN_PROJECT_ID") write_key = write_key or os.environ.get("KEEN_WRITE_KEY") read_key = read_key or os.environ.get("KEEN_READ_KEY") master_key = master_key or os.environ.get("KEEN_MASTER_KEY") base_url = base_url or os.environ.get("KEEN_BASE_URL") if not project_id: raise InvalidEnvironmentError("Please set the KEEN_PROJECT_ID environment variable or set keen.project_id!") _client = KeenClient(project_id, write_key=write_key, read_key=read_key, master_key=master_key, base_url=base_url)
module function_definition identifier parameters block global_statement identifier identifier identifier identifier identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier boolean_operator identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier boolean_operator identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier boolean_operator identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier boolean_operator identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier boolean_operator identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement not_operator identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier
Initialize a KeenClient instance using environment variables.
def setup(provider=None): site = init(provider) if not site: site = yaml.safe_load(_read_file(DEPLOY_YAML)) provider_class = PROVIDERS[site['provider']] provider_class.init(site)
module function_definition identifier parameters default_parameter identifier none block expression_statement assignment identifier call identifier argument_list identifier if_statement not_operator identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement assignment identifier subscript identifier subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier
Creates the provider config files needed to deploy your project
def _get_status_tokens(self): " The tokens for the status bar. " result = [] for i, w in enumerate(self.pymux.arrangement.windows): if i > 0: result.append(('', ' ')) if w == self.pymux.arrangement.get_active_window(): style = 'class:window.current' format_str = self.pymux.window_status_current_format else: style = 'class:window' format_str = self.pymux.window_status_format result.append(( style, format_pymux_string(self.pymux, format_str, window=w), self._create_select_window_handler(w))) return result
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier list for_statement pattern_list identifier identifier call identifier argument_list attribute attribute attribute identifier identifier identifier identifier block if_statement comparison_operator identifier integer block expression_statement call attribute identifier identifier argument_list tuple string string_start string_end string string_start string_content string_end if_statement comparison_operator identifier call attribute attribute attribute identifier identifier identifier identifier argument_list block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier attribute attribute identifier identifier identifier else_clause block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list tuple identifier call identifier argument_list attribute identifier identifier identifier keyword_argument identifier identifier call attribute identifier identifier argument_list identifier return_statement identifier
The tokens for the status bar.
def run_once(function, state={}, errors={}): @six.wraps(function) def _wrapper(*args, **kwargs): if function in errors: six.reraise(*errors[function]) try: return state[function] except KeyError: try: state[function] = result = function(*args, **kwargs) return result except Exception: errors[function] = sys.exc_info() raise return _wrapper
module function_definition identifier parameters identifier default_parameter identifier dictionary default_parameter identifier dictionary block decorated_definition decorator call attribute identifier identifier argument_list identifier function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list list_splat subscript identifier identifier try_statement block return_statement subscript identifier identifier except_clause identifier block try_statement block expression_statement assignment subscript identifier identifier assignment identifier call identifier argument_list list_splat identifier dictionary_splat identifier return_statement identifier except_clause identifier block expression_statement assignment subscript identifier identifier call attribute identifier identifier argument_list raise_statement return_statement identifier
A memoization decorator, whose purpose is to cache calls.
def paypal_time(time_obj=None): warn_untested() if time_obj is None: time_obj = time.gmtime() return time.strftime(PayPalNVP.TIMESTAMP_FORMAT, time_obj)
module function_definition identifier parameters default_parameter identifier none block expression_statement call identifier argument_list if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list attribute identifier identifier identifier
Returns a time suitable for PayPal time fields.
def command(name, nargs=0, complete=None, range=None, count=None, bang=False, register=False, sync=False, allow_nested=False, eval=None): def dec(f): f._nvim_rpc_method_name = 'command:{}'.format(name) f._nvim_rpc_sync = sync f._nvim_bind = True f._nvim_prefix_plugin_path = True opts = {} if range is not None: opts['range'] = '' if range is True else str(range) elif count is not None: opts['count'] = count if bang: opts['bang'] = '' if register: opts['register'] = '' if nargs: opts['nargs'] = nargs if complete: opts['complete'] = complete if eval: opts['eval'] = eval if not sync and allow_nested: rpc_sync = "urgent" else: rpc_sync = sync f._nvim_rpc_spec = { 'type': 'command', 'name': name, 'sync': rpc_sync, 'opts': opts } return f return dec
module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier false default_parameter identifier false default_parameter identifier false default_parameter identifier false default_parameter identifier none block function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier true expression_statement assignment attribute identifier identifier true expression_statement assignment identifier dictionary if_statement comparison_operator identifier none block expression_statement assignment subscript identifier string string_start string_content string_end conditional_expression string string_start string_end comparison_operator identifier true call identifier argument_list identifier elif_clause comparison_operator identifier none block expression_statement assignment subscript identifier string string_start string_content string_end identifier if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_end if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_end if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier if_statement boolean_operator not_operator identifier identifier block expression_statement assignment identifier string string_start string_content string_end else_clause block expression_statement assignment identifier identifier expression_statement assignment attribute identifier 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 identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier return_statement identifier return_statement identifier
Tag a function or plugin method as a Nvim command handler.
def distribute_covar_matrix_to_match_covariance_type( tied_cv, covariance_type, n_components): if covariance_type == 'spherical': cv = np.tile(tied_cv.mean() * np.ones(tied_cv.shape[1]), (n_components, 1)) elif covariance_type == 'tied': cv = tied_cv elif covariance_type == 'diag': cv = np.tile(np.diag(tied_cv), (n_components, 1)) elif covariance_type == 'full': cv = np.tile(tied_cv, (n_components, 1, 1)) else: raise ValueError("covariance_type must be one of " + "'spherical', 'tied', 'diag', 'full'") return cv
module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator call attribute identifier identifier argument_list call attribute identifier identifier argument_list subscript attribute identifier identifier integer tuple identifier integer elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier identifier elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier tuple identifier integer elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list identifier tuple identifier integer integer else_clause block raise_statement call identifier argument_list binary_operator string string_start string_content string_end string string_start string_content string_end return_statement identifier
Create all the covariance matrices from a given template.
def reader(stream): for line in stream: item = Item() item.json = line yield item
module function_definition identifier parameters identifier block for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier identifier identifier expression_statement yield identifier
Read Items from a stream containing lines of JSON.
def last(pipe, items=1): if items == 1: tmp=None for i in pipe: tmp=i return tmp else: return tuple(deque(pipe, maxlen=items))
module function_definition identifier parameters identifier default_parameter identifier integer block if_statement comparison_operator identifier integer block expression_statement assignment identifier none for_statement identifier identifier block expression_statement assignment identifier identifier return_statement identifier else_clause block return_statement call identifier argument_list call identifier argument_list identifier keyword_argument identifier identifier
this function simply returns the last item in an iterable
def _aggregations(search, definitions): if definitions: for name, agg in definitions.items(): search.aggs[name] = agg if not callable(agg) else agg() return search
module function_definition identifier parameters identifier identifier block if_statement identifier block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement assignment subscript attribute identifier identifier identifier conditional_expression identifier not_operator call identifier argument_list identifier call identifier argument_list return_statement identifier
Add aggregations to query.
def remove_user_setting(self, section, name, save=False): configfile = get_configfile_user() return _remove_setting(section, name, configfile, save)
module function_definition identifier parameters identifier identifier identifier default_parameter identifier false block expression_statement assignment identifier call identifier argument_list return_statement call identifier argument_list identifier identifier identifier identifier
remove a setting from the user config
def do_yo(self, args): chant = ['yo'] + ['ho'] * args.ho separator = ', ' if args.commas else ' ' chant = separator.join(chant) self.poutput('{0} and a bottle of {1}'.format(chant, args.beverage))
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator list string string_start string_content string_end binary_operator list string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier conditional_expression string string_start string_content string_end attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier attribute identifier identifier
Compose a yo-ho-ho type chant with flexible options.
def embed_code_links(app, exception): if exception is not None: return if not app.builder.config.plot_gallery: return if app.builder.name not in ['html', 'readthedocs']: return logger.info('embedding documentation hyperlinks...', color='white') gallery_conf = app.config.sphinx_gallery_conf gallery_dirs = gallery_conf['gallery_dirs'] if not isinstance(gallery_dirs, list): gallery_dirs = [gallery_dirs] for gallery_dir in gallery_dirs: _embed_code_links(app, gallery_conf, gallery_dir)
module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier none block return_statement if_statement not_operator attribute attribute attribute identifier identifier identifier identifier block return_statement if_statement comparison_operator attribute attribute identifier identifier identifier list string string_start string_content string_end string string_start string_content string_end block return_statement expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier subscript identifier string string_start string_content string_end if_statement not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier list identifier for_statement identifier identifier block expression_statement call identifier argument_list identifier identifier identifier
Embed hyperlinks to documentation into example code
def check_write_permission(self, user_id, do_raise=True): return self.get_resource().check_write_permission(user_id, do_raise=do_raise)
module function_definition identifier parameters identifier identifier default_parameter identifier true block return_statement call attribute call attribute identifier identifier argument_list identifier argument_list identifier keyword_argument identifier identifier
Check whether this user can write this node
def http_method(self, data): data = data.upper() if data in ['DELETE', 'GET', 'POST', 'PUT']: self._http_method = data if self._headers.get('Content-Type') is None and data in ['POST', 'PUT']: self.add_header('Content-Type', 'application/json') else: raise AttributeError( 'Request Object Error: {} is not a valid HTTP method.'.format(data) )
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block expression_statement assignment attribute identifier identifier identifier if_statement boolean_operator comparison_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end none comparison_operator identifier list string string_start string_content string_end string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end else_clause block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier
The HTTP method for this request.
def logs(ctx, services, num, follow): logger.debug("running command %s (%s)", ctx.command.name, ctx.params, extra={"command": ctx.command.name, "params": ctx.params}) home = ctx.obj["HOME"] services_path = os.path.join(home, SERVICES) tail_threads = [] for service in services: logpath = os.path.join(services_path, service, LOGS_DIR, STDOUTLOG) if os.path.exists(logpath): logger.debug("tailing %s", logpath) t = threading.Thread(target=Tailer, kwargs={"name": service, "nlines": num, "filepath": logpath, "follow": follow}) t.daemon = True t.start() tail_threads.append(t) if tail_threads: while tail_threads[0].isAlive(): tail_threads[0].join(0.1)
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute attribute identifier identifier identifier attribute identifier identifier keyword_argument identifier dictionary pair string string_start string_content string_end attribute attribute identifier identifier identifier pair string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier identifier identifier if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier expression_statement assignment attribute identifier identifier true expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier if_statement identifier block while_statement call attribute subscript identifier integer identifier argument_list block expression_statement call attribute subscript identifier integer identifier argument_list float
Show logs of daemonized service.
def _OpenFilesForRead(self, metadata_value_pairs, token): aff4_paths = [ result.AFF4Path(metadata.client_urn) for metadata, result in metadata_value_pairs ] fds = aff4.FACTORY.MultiOpen(aff4_paths, mode="r", token=token) fds_dict = dict([(fd.urn, fd) for fd in fds]) return fds_dict
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list attribute identifier identifier for_in_clause pattern_list identifier identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier expression_statement assignment identifier call identifier argument_list list_comprehension tuple attribute identifier identifier identifier for_in_clause identifier identifier return_statement identifier
Open files all at once if necessary.
def _get(self, **kwargs): path = self._construct_path_to_item() return self._http.get(path)
module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list return_statement call attribute attribute identifier identifier identifier argument_list identifier
Get the resource from a remote Transifex server.
def convert(self, *args, **kwargs): self.strings() self.metadata() self.result.save(self.output())
module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list
Yes it is, thanks captain.
def desc(self) -> str: kind, value = self.kind.value, self.value return f"{kind} {value!r}" if value else kind
module function_definition identifier parameters identifier type identifier block expression_statement assignment pattern_list identifier identifier expression_list attribute attribute identifier identifier identifier attribute identifier identifier return_statement conditional_expression string string_start interpolation identifier string_content interpolation identifier type_conversion string_end identifier identifier
A helper property to describe a token as a string for debugging
def canparse(argparser, args): old_error_method = argparser.error argparser.error = _raise_ValueError try: argparser.parse_args(args) except ValueError: return False else: return True finally: argparser.error = old_error_method
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment attribute identifier identifier identifier try_statement block expression_statement call attribute identifier identifier argument_list identifier except_clause identifier block return_statement false else_clause block return_statement true finally_clause block expression_statement assignment attribute identifier identifier identifier
Determines if argparser can parse args.
def send_message(self, payload): self.l.info("Creating outbound message request") result = ms_client.create_outbound(payload) self.l.info("Created outbound message request") return result
module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end return_statement identifier
Create a post request to the message sender
def _subfield_conflicts( conflicts, response_name, ast1, ast2, ): if conflicts: return ( (response_name, [conflict[0] for conflict in conflicts]), tuple(itertools.chain([ast1], *[conflict[1] for conflict in conflicts])), tuple(itertools.chain([ast2], *[conflict[2] for conflict in conflicts])), ) return None
module function_definition identifier parameters identifier identifier identifier identifier block if_statement identifier block return_statement tuple tuple identifier list_comprehension subscript identifier integer for_in_clause identifier identifier call identifier argument_list call attribute identifier identifier argument_list list identifier list_splat list_comprehension subscript identifier integer for_in_clause identifier identifier call identifier argument_list call attribute identifier identifier argument_list list identifier list_splat list_comprehension subscript identifier integer for_in_clause identifier identifier return_statement none
Given a series of Conflicts which occurred between two sub-fields, generate a single Conflict.
def forward_backward(self, x): (src_seq, tgt_seq, src_valid_length, tgt_valid_length), batch_size = x with mx.autograd.record(): out, _ = self._model(src_seq, tgt_seq[:, :-1], src_valid_length, tgt_valid_length - 1) smoothed_label = self._label_smoothing(tgt_seq[:, 1:]) ls = self._loss(out, smoothed_label, tgt_valid_length - 1).sum() ls = (ls * (tgt_seq.shape[1] - 1)) / batch_size / self._rescale_loss ls.backward() return ls
module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list tuple_pattern identifier identifier identifier identifier identifier identifier with_statement with_clause with_item call attribute attribute identifier identifier identifier argument_list block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier subscript identifier slice slice unary_operator integer identifier binary_operator identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier slice slice integer expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier identifier binary_operator identifier integer identifier argument_list expression_statement assignment identifier binary_operator binary_operator parenthesized_expression binary_operator identifier parenthesized_expression binary_operator subscript attribute identifier identifier integer integer identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list return_statement identifier
Perform forward and backward computation for a batch of src seq and dst seq
def process_log_record(self, log_record): log_record["version"] = __version__ log_record["program"] = PROGRAM_NAME log_record["service_name"] = log_record.pop('threadName', None) return log_record
module function_definition identifier parameters identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end none return_statement identifier
Add customer record keys and rename threadName key.
def draw_confusion_matrix(matrix): fig = tfmpl.create_figure(figsize=(7,7)) ax = fig.add_subplot(111) ax.set_title('Confusion matrix for MNIST classification') tfmpl.plots.confusion_matrix.draw( ax, matrix, axis_labels=['Digit ' + str(x) for x in range(10)], normalize=True ) return fig
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier tuple integer integer expression_statement assignment identifier call attribute identifier identifier argument_list integer expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list identifier identifier keyword_argument identifier list_comprehension binary_operator string string_start string_content string_end call identifier argument_list identifier for_in_clause identifier call identifier argument_list integer keyword_argument identifier true return_statement identifier
Draw confusion matrix for MNIST.
def drop(): _State.connection() _State.table.drop(checkfirst=True) _State.metadata.remove(_State.table) _State.table = None _State.new_transaction()
module function_definition identifier parameters block expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier true expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier none expression_statement call attribute identifier identifier argument_list
Drop the current table if it exists
def hydrate(self, values): def hydrate_(obj): if isinstance(obj, Structure): try: f = self.hydration_functions[obj.tag] except KeyError: return obj else: return f(*map(hydrate_, obj.fields)) elif isinstance(obj, list): return list(map(hydrate_, obj)) elif isinstance(obj, dict): return {key: hydrate_(value) for key, value in obj.items()} else: return obj return tuple(map(hydrate_, values))
module function_definition identifier parameters identifier identifier block function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block try_statement block expression_statement assignment identifier subscript attribute identifier identifier attribute identifier identifier except_clause identifier block return_statement identifier else_clause block return_statement call identifier argument_list list_splat call identifier argument_list identifier attribute identifier identifier elif_clause call identifier argument_list identifier identifier block return_statement call identifier argument_list call identifier argument_list identifier identifier elif_clause call identifier argument_list identifier identifier block return_statement dictionary_comprehension pair identifier call identifier argument_list identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list else_clause block return_statement identifier return_statement call identifier argument_list call identifier argument_list identifier identifier
Convert PackStream values into native values.
def smooth_hanning(x, size=11): if x.ndim != 1: raise ValueError, "smooth_hanning only accepts 1-D arrays." if x.size < size: raise ValueError, "Input vector needs to be bigger than window size." if size < 3: return x s = np.r_[x[size - 1:0:-1], x, x[-1:-size:-1]] w = np.hanning(size) y = np.convolve(w / w.sum(), s, mode='valid') return y
module function_definition identifier parameters identifier default_parameter identifier integer block if_statement comparison_operator attribute identifier identifier integer block raise_statement expression_list identifier string string_start string_content string_end if_statement comparison_operator attribute identifier identifier identifier block raise_statement expression_list identifier string string_start string_content string_end if_statement comparison_operator identifier integer block return_statement identifier expression_statement assignment identifier subscript attribute identifier identifier subscript identifier slice binary_operator identifier integer integer unary_operator integer identifier subscript identifier slice unary_operator integer unary_operator identifier unary_operator integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator identifier call attribute identifier identifier argument_list identifier keyword_argument identifier string string_start string_content string_end return_statement identifier
smooth a 1D array using a hanning window with requested size.
def write_bsedebug(basis): s = '' for el, eldata in basis['elements'].items(): s += element_data_str(el, eldata) return s
module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_end for_statement pattern_list identifier identifier call attribute subscript identifier string string_start string_content string_end identifier argument_list block expression_statement augmented_assignment identifier call identifier argument_list identifier identifier return_statement identifier
Converts a basis set to BSE Debug format
def _decode_fname(self): self.fname = self.fname[:self.fname.find('\0')] self.fname = self.fname.replace('\\', '/')
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier subscript attribute identifier identifier slice call attribute attribute identifier identifier identifier argument_list string string_start string_content escape_sequence string_end expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content escape_sequence string_end string string_start string_content string_end
Extracts the actual string from the available bytes.
def do_edit(self, arg): "Open an editor visiting the current file at the current line" if arg == '': filename, lineno = self._get_current_position() else: filename, lineno, _ = self._get_position_of_arg(arg) if filename is None: return match = re.match(r'.*<\d+-codegen (.*):(\d+)>', filename) if match: filename = match.group(1) lineno = int(match.group(2)) try: self._open_editor(self._get_editor_cmd(filename, lineno)) except Exception as exc: self.error(exc)
module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end if_statement comparison_operator identifier string string_start string_end block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list else_clause block expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier none block return_statement expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list integer expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list integer try_statement block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier
Open an editor visiting the current file at the current line
def _todict(cls): return dict((getattr(cls, attr), attr) for attr in dir(cls) if not attr.startswith('_'))
module function_definition identifier parameters identifier block return_statement call identifier generator_expression tuple call identifier argument_list identifier identifier identifier for_in_clause identifier call identifier argument_list identifier if_clause not_operator call attribute identifier identifier argument_list string string_start string_content string_end
generate a dict keyed by value
def write(self, *args, **kwargs): return self.stream.write(ending="", *args, **kwargs)
module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block return_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier string string_start string_end list_splat identifier dictionary_splat identifier
Call the stream's write method without linebreaks at line endings.
def segment_midpoints(neurites, neurite_type=NeuriteType.all): def _seg_midpoint(sec): pts = sec.points[:, COLS.XYZ] return np.divide(np.add(pts[:-1], pts[1:]), 2.0) return map_segments(_seg_midpoint, neurites, neurite_type)
module function_definition identifier parameters identifier default_parameter identifier attribute identifier identifier block function_definition identifier parameters identifier block expression_statement assignment identifier subscript attribute identifier identifier slice attribute identifier identifier return_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list subscript identifier slice unary_operator integer subscript identifier slice integer float return_statement call identifier argument_list identifier identifier identifier
Return a list of segment mid-points in a collection of neurites
def lambert_yticks(ax, ticks): te = lambda xy: xy[1] lc = lambda t, n, b: np.vstack((np.linspace(b[0], b[1], n), np.zeros(n) + t)).T yticks, yticklabels = _lambert_ticks(ax, ticks, 'left', lc, te) ax.yaxis.tick_left() ax.set_yticks(yticks) ax.set_yticklabels([ax.yaxis.get_major_formatter()(ytick) for ytick in yticklabels])
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier lambda lambda_parameters identifier subscript identifier integer expression_statement assignment identifier lambda lambda_parameters identifier identifier identifier attribute call attribute identifier identifier argument_list tuple call attribute identifier identifier argument_list subscript identifier integer subscript identifier integer identifier binary_operator call attribute identifier identifier argument_list identifier identifier identifier expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier identifier string string_start string_content string_end identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list list_comprehension call call attribute attribute identifier identifier identifier argument_list argument_list identifier for_in_clause identifier identifier
Draw ricks on the left y-axis of a Lamber Conformal projection.
def _validate_planar_fault_geometry(self, node, _float_re): valid_spacing = node["spacing"] for key in ["topLeft", "topRight", "bottomLeft", "bottomRight"]: lon = getattr(node, key)["lon"] lat = getattr(node, key)["lat"] depth = getattr(node, key)["depth"] valid_lon = (lon >= -180.0) and (lon <= 180.0) valid_lat = (lat >= -90.0) and (lat <= 90.0) valid_depth = (depth >= 0.0) is_valid = valid_lon and valid_lat and valid_depth if not is_valid or not valid_spacing: raise LogicTreeError( node, self.filename, "'planarFaultGeometry' node is not valid")
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end for_statement identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier subscript call identifier argument_list identifier identifier string string_start string_content string_end expression_statement assignment identifier subscript call identifier argument_list identifier identifier string string_start string_content string_end expression_statement assignment identifier subscript call identifier argument_list identifier identifier string string_start string_content string_end expression_statement assignment identifier boolean_operator parenthesized_expression comparison_operator identifier unary_operator float parenthesized_expression comparison_operator identifier float expression_statement assignment identifier boolean_operator parenthesized_expression comparison_operator identifier unary_operator float parenthesized_expression comparison_operator identifier float expression_statement assignment identifier parenthesized_expression comparison_operator identifier float expression_statement assignment identifier boolean_operator boolean_operator identifier identifier identifier if_statement boolean_operator not_operator identifier not_operator identifier block raise_statement call identifier argument_list identifier attribute identifier identifier string string_start string_content string_end
Validares a node representation of a planar fault geometry
def auto_setup(self): self.add_cmd_handler(CAPABILITY_RESPONSE, self._handle_report_capability_response) self.send_sysex(CAPABILITY_QUERY, []) self.pass_time(0.1) while self.bytes_available(): self.iterate() if self._layout: self.setup_layout(self._layout) else: raise IOError("Board detection failed.")
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier list expression_statement call attribute identifier identifier argument_list float while_statement call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier else_clause block raise_statement call identifier argument_list string string_start string_content string_end
Automatic setup based on Firmata's "Capability Query"
def _prepare_request_json(self, kwargs): kwargs = self._check_for_python_keywords(kwargs) if 'check' in kwargs: od = OrderedDict() od['check'] = kwargs['check'] kwargs.pop('check') od.update(kwargs) return od return kwargs
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier return_statement identifier return_statement identifier
Prepare request args for sending to device as JSON.
def _left_zero_blocks(self, r): if not self._include_off_diagonal: return r elif not self._upper: return 0 elif self._include_diagonal: return r else: return r + 1
module function_definition identifier parameters identifier identifier block if_statement not_operator attribute identifier identifier block return_statement identifier elif_clause not_operator attribute identifier identifier block return_statement integer elif_clause attribute identifier identifier block return_statement identifier else_clause block return_statement binary_operator identifier integer
Number of blocks with zeros from the left in block row `r`.
def scrape(self, request, response, link_type=None): for scraper in self._document_scrapers: scrape_result = scraper.scrape(request, response, link_type) if scrape_result is None: continue if scrape_result.link_contexts: return scrape_result
module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block for_statement identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier identifier if_statement comparison_operator identifier none block continue_statement if_statement attribute identifier identifier block return_statement identifier
Iterate the scrapers, returning the first of the results.
def pick_a_model_randomly(models: List[Any]) -> Any: try: return random.choice(models) except IndexError as e: raise ModelPickerException(cause=e)
module function_definition identifier parameters typed_parameter identifier type generic_type identifier type_parameter type identifier type identifier block try_statement block return_statement call attribute identifier identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block raise_statement call identifier argument_list keyword_argument identifier identifier
Naive picking function, return one of the models chosen randomly.
def start_capture(self): previous_map_tool = self.canvas.mapTool() if previous_map_tool != self.tool: self.previous_map_tool = previous_map_tool self.canvas.setMapTool(self.tool) self.hide()
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment attribute identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list
Start capturing the rectangle.
def choice(*es): msg = 'Expected one of: {}'.format(', '.join(map(repr, es))) def match_choice(s, grm=None, pos=0): errs = [] for e in es: try: return e(s, grm, pos) except PegreError as ex: errs.append((ex.message, ex.position)) if errs: raise PegreChoiceError(errs, pos) return match_choice
module function_definition identifier parameters list_splat_pattern identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier identifier function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier integer block expression_statement assignment identifier list for_statement identifier identifier block try_statement block return_statement call identifier argument_list identifier identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list tuple attribute identifier identifier attribute identifier identifier if_statement identifier block raise_statement call identifier argument_list identifier identifier return_statement identifier
Create a PEG function to match an ordered choice.
def checklist(ctx): checklist = steps = dict(x1=None, x2=None, x3=None, x4=None, x5=None, x6=None) yesno_map = {True: "x", False: "_", None: " "} answers = {name: yesno_map[value] for name, value in steps.items()} print(checklist.format(**answers))
module function_definition identifier parameters identifier block expression_statement assignment identifier assignment identifier call identifier argument_list keyword_argument identifier none keyword_argument identifier none keyword_argument identifier none keyword_argument identifier none keyword_argument identifier none keyword_argument identifier none expression_statement assignment identifier dictionary pair true string string_start string_content string_end pair false string string_start string_content string_end pair none string string_start string_content string_end expression_statement assignment identifier dictionary_comprehension pair identifier subscript identifier identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list expression_statement call identifier argument_list call attribute identifier identifier argument_list dictionary_splat identifier
Checklist for releasing this project.
def sanitize_url(url): parts = urlparse(url) if parts.password is None: return url host_info = parts.netloc.rsplit('@', 1)[-1] parts = parts._replace(netloc='{}:{}@{}'.format( parts.username, REDACTED, host_info)) return parts.geturl()
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator attribute identifier identifier none block return_statement identifier expression_statement assignment identifier subscript call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end integer unary_operator integer expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier identifier identifier return_statement call attribute identifier identifier argument_list
Redact password in urls.
def on_arc_right(self, speed, radius_mm, distance_mm, brake=True, block=True): self._on_arc(speed, radius_mm, distance_mm, brake, block, True)
module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier true default_parameter identifier true block expression_statement call attribute identifier identifier argument_list identifier identifier identifier identifier identifier true
Drive clockwise in a circle with 'radius_mm' for 'distance_mm'
def functions_factory(cls, coef, degree, knots, ext, **kwargs): return cls._basis_spline_factory(coef, degree, knots, 0, ext)
module function_definition identifier parameters identifier identifier identifier identifier identifier dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list identifier identifier identifier integer identifier
Given some coefficients, return a B-spline.