code
stringlengths
51
2.34k
sequence
stringlengths
186
3.94k
docstring
stringlengths
11
171
def pair(self): if self.set_val is not None: return self.env_name, self.set_val elif self.default_val is not None: return self.env_name, os.environ.get(self.env_name, self.default_val) else: return self.env_name, os.environ[self.env_name]
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block return_statement expression_list attribute identifier identifier attribute identifier identifier elif_clause comparison_operator attribute identifier identifier none block return...
Get the name and value for this environment variable
def reject(self): self.canvas.unsetMapTool(self.tool) if self.previous_map_tool != self.tool: self.canvas.setMapTool(self.previous_map_tool) self.tool.reset() self.extent_selector_closed.emit() super(ExtentSelectorDialog, self).reject()
module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier if_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement call ...
User rejected the rectangle.
def _Decode(self, codec_name, data): try: return data.decode(codec_name, "replace") except LookupError: raise RuntimeError("Codec could not be found.") except AssertionError: raise RuntimeError("Codec failed to decode")
module function_definition identifier parameters identifier identifier identifier block try_statement block return_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end except_clause identifier block raise_statement call identifier argument_list string str...
Decode data with the given codec name.
def decode(var, encoding): if PY2: if isinstance(var, unicode): ret = var elif isinstance(var, str): if encoding: ret = var.decode(encoding) else: ret = unicode(var) else: ret = unicode(var) else: ret...
module function_definition identifier parameters identifier identifier block if_statement identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier identifier elif_clause call identifier argument_list identifier identifier block if_statement ident...
If not already unicode, decode it.
def to_tzolkin(jd): lcount = trunc(jd) + 0.5 - EPOCH day = amod(lcount + 4, 13) name = amod(lcount + 20, 20) return int(day), TZOLKIN_NAMES[int(name) - 1]
module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator binary_operator call identifier argument_list identifier float identifier expression_statement assignment identifier call identifier argument_list binary_operator identifier integer integer expre...
Determine Mayan Tzolkin "month" and day from Julian day
def emit(self, *args, **kwargs): if self._block: return for slot in self._slots: if not slot: continue elif isinstance(slot, partial): slot() elif isinstance(slot, weakref.WeakKeyDictionary): for obj, method ...
module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement attribute identifier identifier block return_statement for_statement identifier attribute identifier identifier block if_statement not_operator identifier block continue_state...
Calls all the connected slots with the provided args and kwargs unless block is activated
def output_sshkey(gandi, sshkey, output_keys, justify=12): output_generic(gandi, sshkey, output_keys, justify)
module function_definition identifier parameters identifier identifier identifier default_parameter identifier integer block expression_statement call identifier argument_list identifier identifier identifier identifier
Helper to output an ssh key information.
def match(self, objects: List[Any]) -> bool: s = self._make_string(objects) m = self._compiled_expression.match(s) return m is not None
module function_definition identifier parameters identifier typed_parameter identifier type generic_type identifier type_parameter type identifier type identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier cal...
Return True if the list of objects matches the expression.
def setCurrentRegItem(self, regItem): check_class(regItem, ClassRegItem, allow_none=True) self.tableView.setCurrentRegItem(regItem)
module function_definition identifier parameters identifier identifier block expression_statement call identifier argument_list identifier identifier keyword_argument identifier true expression_statement call attribute attribute identifier identifier identifier argument_list identifier
Sets the current item to the regItem
def _handle_entity(self, token): token = self._tokens.pop() if isinstance(token, tokens.HTMLEntityNumeric): token = self._tokens.pop() if isinstance(token, tokens.HTMLEntityHex): text = self._tokens.pop() self._tokens.pop() return H...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement call identifier argument_list identifier attribute identifier identifier block expression_statement assignment iden...
Handle a case where an HTML entity is at the head of the tokens.
def Kgrad_param_num(self,i,h=1e-4): params = self.getParams() e = sp.zeros_like(params); e[i] = 1 self.setParams(params-h*e) C_L = self.K() self.setParams(params+h*e) C_R = self.K() self.setParams(params) RV = (C_R-C_L)/(2*h) return RV
module function_definition identifier parameters identifier identifier default_parameter identifier float block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier expressio...
check discrepancies between numerical and analytical gradients
def reset(self): self.num_inst = 0 self.sum_metric = 0.0 self.global_num_inst = 0 self.global_sum_metric = 0.0
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier float expression_statement assignment attribute identifier identifier integer expression_statement assignment attribut...
Resets the internal evaluation result to initial state.
def assignQuery(self): self.uiRecordTREE.setQuery(self._queryWidget.query(), autoRefresh=True)
module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list keyword_argument identifier true
Assigns the query from the query widget to the edit.
def load_global_settings(): with open(settings_path, 'r') as settings_f: global global_settings settings_json = json.loads(settings_f.read()) if global_settings is None: global_settings = settings_json global_settings[u'package_path'] = package_dir else: ...
module function_definition identifier parameters block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block global_statement identifier expression_statement assignment identifier call attribute identifie...
Loads settings file containing paths to dependencies and other optional configuration elements.
def to(self, unit): if not _has_astropy: raise ImportError("astropy must be installed for unit/quantity support") if self.unit is None: raise ValueError("no units currently set") if not is_unit_or_unitstring(unit)[0]: raise ValueError("unit not recognized") ...
module function_definition identifier parameters identifier identifier block if_statement not_operator identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement comparison_operator attribute identifier identifier none block raise_statement call identifier ...
convert between units. Returns a new nparray object with the new units
def grok_ttl(secret): ttl_obj = {} lease_msg = '' if 'lease' in secret: ttl_obj['lease'] = secret['lease'] lease_msg = "lease:%s" % (ttl_obj['lease']) if 'lease_max' in secret: ttl_obj['lease_max'] = secret['lease_max'] elif 'lease' in ttl_obj: ttl_obj['lease_max'] = ...
module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary expression_statement assignment identifier string string_start string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignmen...
Parses the TTL information
def _hammer_function_precompute(self,x0, L, Min, model): if x0 is None: return None, None if len(x0.shape)==1: x0 = x0[None,:] m = model.predict(x0)[0] pred = model.predict(x0)[1].copy() pred[pred<1e-16] = 1e-16 s = np.sqrt(pred) r_x0 = (m-Min)/L s_x0 = s/...
module function_definition identifier parameters identifier identifier identifier identifier identifier block if_statement comparison_operator identifier none block return_statement expression_list none none if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block exp...
Pre-computes the parameters of a penalizer centered at x0.
def _load_account(self, acct_id, acct_dir_path): self._config[acct_id] = { 'name': None, 'role_name': DEFAULT_ROLE_NAME, 'regions': {} } with open(os.path.join(acct_dir_path, 'config.json'), 'r') as fh: acct_conf = json.loads(fh.read()) sel...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier dictionary pair string string_start string_content string_end none pair string string_start string_content string_end identifier pair string string...
load configuration from one per-account subdirectory
def render_exception_js(self, exception): from .http import JsonResponse response = {} response["error"] = exception.error response["error_description"] = exception.reason return JsonResponse(response, status=getattr(exception, 'code', 400))
module function_definition identifier parameters identifier identifier block import_from_statement relative_import import_prefix dotted_name identifier dotted_name identifier expression_statement assignment identifier dictionary expression_statement assignment subscript identifier string string_start string_content str...
Return a response with the body containing a JSON-formatter version of the exception.
def ipopo_instances(self): try: with use_ipopo(self.__context) as ipopo: return { instance[0]: ipopo.get_instance_details(instance[0]) for instance in ipopo.get_instances() } except BundleException: return No...
module function_definition identifier parameters identifier block try_statement block with_statement with_clause with_item as_pattern call identifier argument_list attribute identifier identifier as_pattern_target identifier block return_statement dictionary_comprehension pair subscript identifier integer call attribut...
List of iPOPO instances
def copy(self, klass=None): chain = ( klass if klass else self.__class__ )(*self._args, **self._kwargs) chain._tokens = self._tokens.copy() return chain
module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier call parenthesized_expression conditional_expression identifier identifier attribute identifier identifier argument_list list_splat attribute identifier identifier dictionary_sp...
Create a new instance of the current chain.
def score_for_task(properties, category, result): assert result is not None if properties and Property.create_from_names(properties).is_svcomp: return _svcomp_score(category, result) return None
module function_definition identifier parameters identifier identifier identifier block assert_statement comparison_operator identifier none if_statement boolean_operator identifier attribute call attribute identifier identifier argument_list identifier identifier block return_statement call identifier argument_list id...
Return the possible score of task, depending on whether the result is correct or not.
def mpool(self, k_height, k_width, d_height=2, d_width=2, mode="VALID", input_layer=None, num_channels_in=None): return self._pool("mpool", pooling_layers.max_pooling2d, k_height, k_width,...
module function_definition identifier parameters identifier identifier identifier default_parameter identifier integer default_parameter identifier integer default_parameter identifier string string_start string_content string_end default_parameter identifier none default_parameter identifier none block return_statemen...
Construct a max pooling layer.
def configure_cmake(self): cmake = CMake(self) cmake.definitions["FLATBUFFERS_BUILD_TESTS"] = False cmake.definitions["FLATBUFFERS_BUILD_SHAREDLIB"] = self.options.shared cmake.definitions["FLATBUFFERS_BUILD_FLATLIB"] = not self.options.shared cmake.configure() return cma...
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end false expression_statement assignment subscript at...
Create CMake instance and execute configure step
def profiles(self): limit = [] if self.is_admin(): limit.append(_("Administrator")) limit.sort() return limit
module function_definition identifier parameters identifier block expression_statement assignment identifier list if_statement call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list call identifier argument_list string string_start string_content...
return the rolls this people is related with
def action_aggregate(reader, *args): all_aggregated = aggregated_records(reader) first_row = next(all_aggregated) keys = sorted(first_row.keys()) print(*keys, sep='\t') iterable = chain([first_row], all_aggregated) for item in iterable: print(*[item[k] for k in keys], sep='\t')
module function_definition identifier parameters identifier list_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifi...
Aggregate flow records by 5-tuple and print a tab-separated stream
def save_location(self, filename: str, location: PostLocation, mtime: datetime) -> None: filename += '_location.txt' location_string = (location.name + "\n" + "https://maps.google.com/maps?q={0},{1}&ll={0},{1}\n".format(location.lat, ...
module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier type none block expression_statement augmented_assignment identifier string string_start string_content string_end expression_state...
Save post location name and Google Maps link.
def body_block_image_content(tag): "format a graphic or inline-graphic into a body block json format" image_content = OrderedDict() if tag: copy_attribute(tag.attrs, 'xlink:href', image_content, 'uri') if "uri" in image_content: set_if_value(image_content, "alt", "") return i...
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call identifier argument_list if_statement identifier block expression_statement call identifier argument_list attribute identifier identifier s...
format a graphic or inline-graphic into a body block json format
def write_display(self): for i, value in enumerate(self.buffer): self._device.write8(i, value)
module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier
Write display buffer to display hardware.
def _validate_edges_do_not_have_extra_links(class_name, properties): for property_name, property_descriptor in six.iteritems(properties): if property_name in {EDGE_SOURCE_PROPERTY_NAME, EDGE_DESTINATION_PROPERTY_NAME}: continue if property_descriptor.type_id == PROPERTY_TYPE_LINK_ID: ...
module function_definition identifier parameters identifier identifier block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list identifier block if_statement comparison_operator identifier set identifier identifier block continue_statement if_statement comparison_operato...
Validate that edges do not have properties of Link type that aren't the edge endpoints.
def clear(self) -> None: self._headers = httputil.HTTPHeaders( { "Server": "TornadoServer/%s" % tornado.version, "Content-Type": "text/html; charset=UTF-8", "Date": httputil.format_timestamp(time.time()), } ) self.set_defaul...
module function_definition identifier parameters identifier type none block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end binary_operator string string_start string_content string_end attri...
Resets all headers and content for this response.
def _parse_quoted_key(self): quote_style = self._current key_type = None dotted = False for t in KeyType: if t.value == quote_style: key_type = t break if key_type is None: raise RuntimeError("Should not have entered _parse_...
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier none expression_statement assignment identifier false for_statement identifier identifier block if_statement comparison_operator attribu...
Parses a key enclosed in either single or double quotes.
def myreplace(astr, thefind, thereplace): alist = astr.split(thefind) new_s = alist.split(thereplace) return new_s
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement ident...
in string astr replace all occurences of thefind with thereplace
def remove_subreddit(self, subreddit, *args, **kwargs): return self.add_subreddit(subreddit, True, *args, **kwargs)
module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list identifier true list_splat identifier dictionary_splat identifier
Remove a subreddit from the user's multireddit.
def __get_float(section, name): try: return float(section[name]) except (ValueError, TypeError, KeyError): return float(0)
module function_definition identifier parameters identifier identifier block try_statement block return_statement call identifier argument_list subscript identifier identifier except_clause tuple identifier identifier identifier block return_statement call identifier argument_list integer
Get the forecasted float from json section.
def ConsultarTipoDeduccion(self, sep="||"): "Consulta de tipos de Deducciones" ret = self.client.tipoDeduccionConsultar( auth={ 'token': self.Token, 'sign': self.Sign, 'cuit': self.Cuit, }, )['tip...
module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block expression_statement string string_start string_content string_end expression_statement assignment identifier subscript call attribute attribute identifier identifier identifier a...
Consulta de tipos de Deducciones
def ensure_params(kty, provided, required): if not required <= provided: missing = required - provided raise MissingValue('Missing properties for kty={}, {}'.format(kty, str(list(missing))))
module function_definition identifier parameters identifier identifier identifier block if_statement not_operator comparison_operator identifier identifier block expression_statement assignment identifier binary_operator identifier identifier raise_statement call identifier argument_list call attribute string string_st...
Ensure all required parameters are present in dictionary
def remove_duplicate_edges_undirected(udg): lookup = {} edges = sorted(udg.get_all_edge_ids()) for edge_id in edges: e = udg.get_edge(edge_id) tpl_a = e['vertices'] tpl_b = (tpl_a[1], tpl_a[0]) if tpl_a in lookup or tpl_b in lookup: udg.delete_edge_by_id(edge_id) ...
module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list for_statement identifier identifier block expression_statement assignment id...
Removes duplicate edges from an undirected graph.
def sign_ssh_challenge(self, blob, identity): msg = _parse_ssh_blob(blob) log.debug('%s: user %r via %r (%r)', msg['conn'], msg['user'], msg['auth'], msg['key_type']) log.debug('nonce: %r', msg['nonce']) fp = msg['public_key']['fingerprint'] log.debug('fingerpri...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end subscript identifier string st...
Sign given blob using a private key on the device.
def account(self): from ambry.util import parse_url_to_dict d = parse_url_to_dict(self.url) return self._bundle.library.account(d['netloc'])
module function_definition identifier parameters identifier block import_from_statement dotted_name identifier identifier dotted_name identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier return_statement call attribute attribute attribute identifier identif...
Return an account record, based on the host in the url
def plotGenCost(generators): figure() plots = [] for generator in generators: if generator.pcost_model == PW_LINEAR: x = [x for x, _ in generator.p_cost] y = [y for _, y in generator.p_cost] elif generator.pcost_model == POLYNOMIAL: x = scipy.arange(genera...
module function_definition identifier parameters identifier block expression_statement call identifier argument_list expression_statement assignment identifier list for_statement identifier identifier block if_statement comparison_operator attribute identifier identifier identifier block expression_statement assignment...
Plots the costs of the given generators.
def exclude_package(self, package): pfx = package + '.' if self.packages: self.packages = [ p for p in self.packages if p != package and not p.startswith(pfx) ] if self.py_modules: self.py_modules = [ p for p in ...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator identifier string string_start string_content string_end if_statement attribute identifier identifier block expression_statement assignment attribute identifier identifier list_compreh...
Remove packages, modules, and extensions in named package
def move_to_result(self, lst_idx): self.in_result_idx.add(lst_idx) if lst_idx in self.not_in_result_root_match_idx: self.not_in_result_root_match_idx.remove(lst_idx)
module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute attribute identifier ...
Moves element from lst available at lst_idx.
def _validate_label(self, label): letter_pattern = compile("^[a-z]{1}$") number_pattern = compile("^[0]{1}$|^[1-9]{1,2}$") icon_pattern = compile("^[a-zA-Z ]{1,}$") if not match(letter_pattern, label)\ and not match(number_pattern, label)\ and not match(icon_p...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list string string_start string_content string_end expre...
Validates label, raising error if invalid.
def request_uplink_info(self, context, agent): LOG.debug('request_uplink_info from %(agent)s', {'agent': agent}) event_type = 'agent.request.uplink' payload = {'agent': agent} timestamp = time.ctime() data = (event_type, payload) pri = self.obj.PRI_LOW_START + 1 s...
module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end dictionary pair string string_start string_content string_end identifier expression_statement assignment identifie...
Process uplink message from an agent.
def rebase_opt(self): if not hasattr(self, '_rebase_opt'): out, err = Popen( ['cleancss', '--version'], stdout=PIPE).communicate() ver = int(out[:out.index(b'.')]) self._rebase_opt = ['--root', self.root] if ver == 3 else [] return self._rebase_opt
module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment pattern_list identifier identifier call attribute call identifier argument_list list string string_star...
Determine which option name to use.
def _api_response(response): if response.status_code == 404: __context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL raise CommandExecutionError('Element doesn\'t exists') if response.status_code == 401: __context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL ra...
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment subscript identifier string string_start string_content string_end attribute attribute attribute identifier identifier identifier identifier ra...
Check response status code + success_code returned by glassfish
def enable_proxy(self, host, port): self.proxy = [host, _number(port)] self.proxy_enabled = True
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment attribute identifier identifier list identifier call identifier argument_list identifier expression_statement assignment attribute identifier identifier true
Enable a default web proxy
def _execute_example_group(self): "Handles the execution of Example Group" for example in self.example: runner = self.__class__(example, self.formatter) runner.is_root_runner = False successes, failures, skipped = runner.run(self.context) self.num_successe...
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end for_statement identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifie...
Handles the execution of Example Group
def init_widget(self): super(QtKeyEvent, self).init_widget() d = self.declaration widget = self.widget self._keyPressEvent = widget.keyPressEvent self._keyReleaseEvent = widget.keyReleaseEvent self.set_enabled(d.enabled) self.set_keys(d.keys)
module function_definition identifier parameters identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier id...
The KeyEvent uses the parent_widget as it's widget
def _populate_warcinfo(self, extra_fields=None): self._warcinfo_record.set_common_fields( WARCRecord.WARCINFO, WARCRecord.WARC_FIELDS) info_fields = NameValueRecord(wrap_width=1024) info_fields['Software'] = self._params.software_string \ or self.DEFAULT_SOFTWARE_STRING ...
module function_definition identifier parameters identifier default_parameter identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call identifier argu...
Add the metadata to the Warcinfo record.
def make_basic_ngpu(nb_classes=10, input_shape=(None, 28, 28, 1), **kwargs): model = make_basic_cnn() layers = model.layers model = MLPnGPU(nb_classes, layers, input_shape) return model
module function_definition identifier parameters default_parameter identifier integer default_parameter identifier tuple none integer integer integer dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier attribute id...
Create a multi-GPU model similar to the basic cnn in the tutorials.
def getMedia(self, uri): r = self.doQuery('media/' + uri) if r.status_code == 200: content_type = 'application/octet-stream' if 'content-type' in r.headers: content_type = r.headers['content-type'] cache_control = None if 'cache-control' in...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier if_statement comparison_operator attribute identifier identifier integer blo...
Return a tuple with a media and his content-type. Don't cache anything !
def render_to_string(self, *args, **kwargs): try: template_name, args = args[0], args[1:] except IndexError: raise TypeError('name of template required') return self.get_template(template_name).render(*args, **kwargs)
module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block try_statement block expression_statement assignment pattern_list identifier identifier expression_list subscript identifier integer subscript identifier slice integer except_clause identif...
Load and render a template into a unicode string.
def local_check (self): log.debug(LOG_CHECK, "Checking %s", unicode(self)) assert not self.extern[1], 'checking strict extern URL' log.debug(LOG_CHECK, "checking connection") try: self.check_connection() self.set_content_type() self.add_size_info() ...
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end call identifier argument_list identifier assert_statement not_operator subscript attribute identifier identifier integer stri...
Local check function can be overridden in subclasses.
def about_action(self): name = self.action.metavar or self.action.dest type_name = self.action.type.__name__ if self.action.type else '' if self.action.help or type_name: extra = ' (%s)' % (self.action.help or 'type: %s' % type_name) else: extra = '' retur...
module function_definition identifier parameters identifier block expression_statement assignment identifier boolean_operator attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier expression_statement assignment identifier conditional_expression attribute attribute at...
Simple string describing the action.
def load_modules(self): if self.INTERFACES_MODULE is None: raise NotImplementedError("A module containing interfaces modules " "should be setup in INTERFACES_MODULE !") else: for module, permission in self.modules.items(): i =...
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end else_clause block fo...
Should instance interfaces and set them to interface, following `modules`
def write_file(self, name, path=None): if path is None: path = name self.zf.write(path, name)
module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identif...
Write the contents of a file from the disk to the XPI.
def _make_chunk_iter(stream, limit, buffer_size): if isinstance(stream, (bytes, bytearray, text_type)): raise TypeError('Passed a string or byte object instead of ' 'true iterator or stream.') if not hasattr(stream, 'read'): for item in stream: if item: ...
module function_definition identifier parameters identifier identifier identifier block if_statement call identifier argument_list identifier tuple identifier identifier identifier block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start s...
Helper for the line and chunk iter functions.
def parse_rule(rule: str, raise_error=False): parser = Parser(raise_error) return parser.parse(rule)
module function_definition identifier parameters typed_parameter identifier type identifier default_parameter identifier false block expression_statement assignment identifier call identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier
Parses policy to a tree of Check objects.
def CheckLineLength(filename, linenumber, clean_lines, errors): line = clean_lines.raw_lines[linenumber] if len(line) > _lint_state.linelength: return errors( filename, linenumber, 'linelength', 'Lines should be <= %d characters long' % ...
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier if_statement comparison_operator call identifier argument_list identifier attribute identifier identifier block return_statem...
Check for lines longer than the recommended length
def rpy_matrix(roll, pitch, yaw): return np.dot(Rz_matrix(yaw), np.dot(Ry_matrix(pitch), Rx_matrix(roll)))
module function_definition identifier parameters identifier identifier identifier block return_statement call attribute identifier identifier argument_list call identifier argument_list identifier call attribute identifier identifier argument_list call identifier argument_list identifier call identifier argument_list i...
Returns a rotation matrix described by the extrinsinc roll, pitch, yaw coordinates
def _get_contract_exception_dict(contract_msg): start_token = "[START CONTRACT MSG: " stop_token = "[STOP CONTRACT MSG]" if contract_msg.find(start_token) == -1: return { "num": 0, "msg": "Argument `*[argument_name]*` is not valid", "type": RuntimeError, ...
module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end if_statement comparison_operator call attribute identifier identifier argume...
Generate message for exception.
def context(self): "Internal property that returns the stylus compiler" if self._context is None: with io.open(path.join(path.abspath(path.dirname(__file__)), "compiler.js")) as compiler_file: compiler_source = compiler_file.read() self._context = self.backend.compile(compiler_source) re...
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end if_statement comparison_operator attribute identifier identifier none block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list call attribu...
Internal property that returns the stylus compiler
def _formatinfo(format): size = struct.calcsize(format) return size, len(struct.unpack(format, B('\x00') * size))
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement expression_list identifier call identifier argument_list call attribute identifier identifier argument_list identifier binary_operat...
Calculate the size and number of items in a struct format.
def parse_dos_time(stamp): sec, stamp = stamp & 0x1F, stamp >> 5 mn, stamp = stamp & 0x3F, stamp >> 6 hr, stamp = stamp & 0x1F, stamp >> 5 day, stamp = stamp & 0x1F, stamp >> 5 mon, stamp = stamp & 0x0F, stamp >> 4 yr = (stamp & 0x7F) + 1980 return (yr, mon, day, hr, mn, sec * 2)
module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier expression_list binary_operator identifier integer binary_operator identifier integer expression_statement assignment pattern_list identifier identifier expression_list binary_operator id...
Parse standard 32-bit DOS timestamp.
def on_close_grid(self, event): if self.parent.grid_frame: self.parent.grid_frame.onSave(None) self.parent.grid_frame.Destroy()
module function_definition identifier parameters identifier identifier block if_statement attribute attribute identifier identifier identifier block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list none expression_statement call attribute attribute attrib...
If there is an open grid, save its data and close it.
def _read_data(self, count): frame = bytearray(count) frame[0] = PN532_SPI_DATAREAD self._gpio.set_low(self._cs) self._busy_wait_ms(2) response = self._spi.transfer(frame) self._gpio.set_high(self._cs) return response
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment subscript identifier integer identifier expression_statement call attribute attribute identifier identifier identifier argument...
Read a specified count of bytes from the PN532.
def accept(self, pub): try: with salt.utils.files.fopen(self.path, 'r') as fp_: expiry = int(fp_.read()) except (OSError, IOError): log.error( 'Request to sign key for minion \'%s\' on hyper \'%s\' ' 'denied: no authorization', self...
module function_definition identifier parameters identifier identifier block try_statement block with_statement with_clause with_item as_pattern call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier string string_start string_content string_end as_p...
Accept the provided key
def cli_certify_core_integer( config, min_value, max_value, value, ): def parser(v): try: v = load_json_pickle(v, config) except Exception: pass try: return int(v) except Exception as err: six.raise_from( CertifierTy...
module function_definition identifier parameters identifier identifier identifier identifier block function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier call identifier argument_list identifier identifier except_clause identifier block pass_statement t...
Console script for certify_int
def set(self, param, value): self.raw_dict[param] = value self.manifest.set(self.feature_name, param, value)
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier ...
sets the param to the value provided
def _generate_output_dir(settings, path): relpath = os.path.relpath(settings.root,path) count = relpath.count(os.sep) + 1 return relpath+os.path.sep, count
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier expression_statement assignment identifier binary_operator call attribute identifier ...
This is a separate function, so that it can be more easily tested
def run(*args): if not args: args = sys.argv[1:] if len(args) < 2: print('Usage: runenv <envfile> <command> <params>') sys.exit(0) os.environ.update(create_env(args[0])) os.environ['_RUNENV_WRAPPED'] = '1' runnable_path = args[1] if not runnable_path.startswith(('/', '.')...
module function_definition identifier parameters list_splat_pattern identifier block if_statement not_operator identifier block expression_statement assignment identifier subscript attribute identifier identifier slice integer if_statement comparison_operator call identifier argument_list identifier integer block expre...
Load given `envfile` and run `command` with `params`
def to_range(obj, score=None, id=None, strand=None): from jcvi.utils.range import Range if score or id: _score = score if score else obj.score _id = id if id else obj.id return Range(seqid=obj.seqid, start=obj.start, end=obj.end, \ score=_score, id=_id) elif strand: ...
module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none block import_from_statement dotted_name identifier identifier identifier dotted_name identifier if_statement boolean_operator identifier identifier block expr...
Given a gffutils object, convert it to a range object
def save_info_df(self): logger.debug("running save_info_df") info_df = self.info_df top_level_dict = {'info_df': info_df, 'metadata': self._prm_packer()} jason_string = json.dumps(top_level_dict, default=lambda info_df: json.loads( ...
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier dictionary pair st...
Saves the DataFrame with info about the runs to a JSON file
def from_bucket(self, bucket, native=False): bucket = str(bucket) if self._step == 'weekly': year, week = bucket[:4], bucket[4:] normal = datetime(year=int(year), month=1, day=1) + timedelta(weeks=int(week)) else: normal = datetime.strptime(bucket, self.FORMATS[self._step]) if native: ...
module function_definition identifier parameters identifier identifier default_parameter identifier false block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block express...
Calculate the timestamp given a bucket.
def build_item( title, key=None, synonyms=None, description=None, img_url=None, alt_text=None ): item = { "info": {"key": key or title, "synonyms": synonyms or []}, "title": title, "description": description, "image": { "imageUri": img_url or "", "accessib...
module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier dictionary pair string string_start strin...
Builds an item that may be added to List or Carousel
def filename(self): if self.buildver: buildver = '-' + self.buildver else: buildver = '' pyver = '.'.join(self.pyver) abi = '.'.join(self.abi) arch = '.'.join(self.arch) version = self.version.replace('-', '_') return '%s-%s%s-%s-%s-%s.whl'...
module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end attribute identifier identifier else_clause block expression_statement assignment identifier strin...
Build and return a filename from the various components.
def update_label(signature, post_data): current_tag_infos = MPost2Label.get_by_uid(signature).objects() if 'tags' in post_data: pass else: return False tags_arr = [x.strip() for x in post_data['tags'].split(',')] for tag_name in tags_arr: if tag_name == '': pass ...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier identifier argument_list if_statement comparison_operator string string_start string_content string_end identifier block pa...
Update the label when updating.
def from_db_value(self, value, expression, connection, context): if value is None: return value return self.parse_seconds(value)
module function_definition identifier parameters identifier identifier identifier identifier identifier block if_statement comparison_operator identifier none block return_statement identifier return_statement call attribute identifier identifier argument_list identifier
Handle data loaded from database.
def visit_VariableDeclaration(self, node): var_name = node.assignment.left.identifier.name var_is_mutable = node.assignment.left.is_mutable var_symbol = VariableSymbol(var_name, var_is_mutable) if self.table[var_name] is not None: raise SementicError(f"Variable `{var_name}` i...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute attribute attribute attribute identifier identifier identifier identifier identifier expression_statement assignment identifier attribute attribute attribute identifier identifier identifier...
Visitor for `VariableDeclaration` AST node.
def _GetAFF4AttributeForReportType(report_type ): if report_type == rdf_stats.ClientGraphSeries.ReportType.GRR_VERSION: return aff4_stats.ClientFleetStats.SchemaCls.GRRVERSION_HISTOGRAM elif report_type == rdf_stats.ClientGraphSeries.ReportType.OS_TYPE: return aff4_stats.Cl...
module function_definition identifier parameters identifier block if_statement comparison_operator identifier attribute attribute attribute identifier identifier identifier identifier block return_statement attribute attribute attribute identifier identifier identifier identifier elif_clause comparison_operator identif...
Returns the corresponding AFF4 attribute for the given report type.
def date_from_number(self, value): if not isinstance(value, numbers.Real): return None delta = datetime.timedelta(days=value) return self._null_date + delta
module function_definition identifier parameters identifier identifier block if_statement not_operator call identifier argument_list identifier attribute identifier identifier block return_statement none expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument ident...
Converts a float value to corresponding datetime instance.
def name(self): if self._name: return self._name return self.code.replace('_', ' ').capitalize()
module function_definition identifier parameters identifier block if_statement attribute identifier identifier block return_statement attribute identifier identifier return_statement call attribute call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end stri...
Give back tab name if is set else generate name by code
def description(self, platform, key): patterns = self._dict_dscr.get(platform, None) description = patterns.get(key, None) return description
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier none expression_statement assignment identifier call attribute identifier identifier argument_list identif...
Return the patter description.
def _openResources(self): with Image.open(self._fileName) as image: self._array = np.asarray(image) self._bands = image.getbands() self._attributes = dict(image.info) self._attributes['Format'] = image.format self._attributes['Mode'] = image.mode ...
module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list attribute identifier identifier as_pattern_target identifier block expression_statement assignment attribute identifier identifier call attribute identifie...
Uses open the underlying file
def _childgroup_by_name(self, children, grid): children = self._dict_children(children) result = [] for row in grid: child_row = [] row_is_void = True width_sum = 0 for name, width in row: width_sum += width if width...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment ident...
Group the children ordering them by name
def drange(start: Decimal, stop: Decimal, num: int): delta = stop - start step = delta / (num - 1) yield from (start + step * Decimal(tick) for tick in range(0, num))
module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier block expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier binary_opera...
A simplified version of numpy.linspace with default options
def __GetRequestField(self, method_description, body_type): body_field_name = self.__BodyFieldName(body_type) if body_field_name in method_description.get('parameters', {}): body_field_name = self.__names.FieldName( '%s_resource' % body_field_name) while body_field_na...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier call attribute identifier identifier argument_list string string_start string_conte...
Determine the request field for this method.
def search(query, stats): log.debug("Search query: {0}".format(query)) issues = [] for batch in range(MAX_BATCHES): response = stats.parent.session.get( "{0}/rest/api/latest/search?{1}".format( stats.parent.url, urllib.urlencode({ ...
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier list for_statement identifier c...
Perform issue search for given stats instance
def _intro_text(self): try: cls_docstring = self._clsdict['__doc__'] except KeyError: cls_docstring = '' if cls_docstring is None: return '' return textwrap.dedent(cls_docstring).strip()
module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end except_clause identifier block expression_statement assignment identifier string string_start string_en...
Docstring of the enumeration, formatted for documentation page.
def post_build(self, p, pay): p += pay if self.auxdlen != 0: print("NOTICE: A properly formatted and complaint V3 Group Record should have an Auxiliary Data length of zero (0).") print(" Subsequent Group Records are lost!") return p
module function_definition identifier parameters identifier identifier identifier block expression_statement augmented_assignment identifier identifier if_statement comparison_operator attribute identifier identifier integer block expression_statement call identifier argument_list string string_start string_content str...
Called implicitly before a packet is sent.
def cross(v1, v2): return ( v1[1] * v2[2] - v1[2] * v2[1], v1[2] * v2[0] - v1[0] * v2[2], v1[0] * v2[1] - v1[1] * v2[0], )
module function_definition identifier parameters identifier identifier block return_statement tuple binary_operator binary_operator subscript identifier integer subscript identifier integer binary_operator subscript identifier integer subscript identifier integer binary_operator binary_operator subscript identifier int...
Computes the cross product of two vectors.
def first_spark_call(): tb = traceback.extract_stack() if len(tb) == 0: return None file, line, module, what = tb[len(tb) - 1] sparkpath = os.path.dirname(file) first_spark_frame = len(tb) - 1 for i in range(0, len(tb)): file, line, fun, what = tb[i] if file.startswith(sp...
module function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator call identifier argument_list identifier integer block return_statement none expression_statement assignment pattern_list identifier ident...
Return a CallSite representing the first Spark call in the current call stack.
def to_python(self, value): if not value: return [] return map(super(CommaSepFloatField, self).to_python, value.split(','))
module function_definition identifier parameters identifier identifier block if_statement not_operator identifier block return_statement list return_statement call identifier argument_list attribute call identifier argument_list identifier identifier identifier call attribute identifier identifier argument_list string ...
Normalize data to a list of floats.
def reacquire(self): if self.local.token is None: raise LockError("Cannot reacquire an unlocked lock") if self.timeout is None: raise LockError("Cannot reacquire a lock with no timeout") return self.do_reacquire()
module function_definition identifier parameters identifier block if_statement comparison_operator attribute attribute identifier identifier identifier none block raise_statement call identifier argument_list string string_start string_content string_end if_statement comparison_operator attribute identifier identifier ...
Resets a TTL of an already acquired lock back to a timeout value.
def namedb_get_name_from_name_hash128( cur, name_hash128, block_number ): unexpired_query, unexpired_args = namedb_select_where_unexpired_names( block_number ) select_query = "SELECT name FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id " + \ "WHERE nam...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier expression_statement assignment identifier binary_operator binary_operator binary_operator string string_start string_conten...
Given the hexlified 128-bit hash of a name, get the name.
def file_plus_index(fname): exts = {".vcf": ".idx", ".bam": ".bai", ".vcf.gz": ".tbi", ".bed.gz": ".tbi", ".fq.gz": ".gbi"} ext = splitext_plus(fname)[-1] if ext in exts: return [fname, fname + exts[ext]] else: return [fname]
module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair s...
Convert a file name into the file plus required indexes.
def _write_object(self, path, value): ensure_directory_exists(os.path.dirname(path)) with open(path, 'w') as f: f.write(value)
module function_definition identifier parameters identifier identifier identifier block expression_statement call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier with_statement with_clause with_item as_pattern call identifier argument_list identifier string st...
write out `object` to file at `path`
def optimise_levenberg_marquardt(x, a, c, damping=0.001, tolerance=0.001): x_new = x x_old = x-1 f_old = f(x_new, a, c) while np.abs(x_new - x_old).sum() > tolerance: x_old = x_new x_tmp = levenberg_marquardt_update(x_old, a, c, damping) f_new = f(x_tmp, a, c) if f_new < ...
module function_definition identifier parameters identifier identifier identifier default_parameter identifier float default_parameter identifier float block expression_statement assignment identifier identifier expression_statement assignment identifier binary_operator identifier integer expression_statement assignmen...
Optimise value of x using levenberg-marquardt