code
stringlengths
51
2.34k
sequence
stringlengths
186
3.94k
docstring
stringlengths
11
171
def LoadCheckFromFile(file_path, check_id, overwrite_if_exists=True): configs = LoadConfigsFromFile(file_path) conf = configs.get(check_id) check = Check(**conf) check.Validate() CheckRegistry.RegisterCheck( check, source="file:%s" % file_path, overwrite_if_exists=overwrite_if_exists) logg...
module function_definition identifier parameters identifier identifier default_parameter identifier true block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement...
Load a single check from a file.
def as_for_ip(self, ip): if not Investigate.IP_PATTERN.match(ip): raise Investigate.IP_ERR uri = self._uris["as_for_ip"].format(ip) resp_json = self.get_parse(uri) return resp_json
module function_definition identifier parameters identifier identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block raise_statement attribute identifier identifier expression_statement assignment identifier call attribute subscript attribute id...
Gets the AS information for a given IP address.
def setFaces(variant): global FACES if variant == CHALDEAN_FACES: FACES = tables.CHALDEAN_FACES else: FACES = tables.TRIPLICITY_FACES
module function_definition identifier parameters identifier block global_statement identifier if_statement comparison_operator identifier identifier block expression_statement assignment identifier attribute identifier identifier else_clause block expression_statement assignment identifier attribute identifier identifi...
Sets the default faces variant
def add_general_optgroup(parser): g = parser.add_argument_group("General Options") g.add_argument("-q", "--quiet", dest="silent", action="store_true", default=False) g.add_argument("-v", "--verbose", nargs=0, action=_opt_cb_verbose) g.add_argument("-o", "--output", dest="output", defa...
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_...
option group for general-use features of all javatool CLIs
def signal_wrapper(f): @wraps(f) def wrapper(*args, **kwds): args = map(convert, args) kwds = {convert(k): convert(v) for k, v in kwds.items()} return f(*args, **kwds) return wrapper
module function_definition identifier parameters identifier block decorated_definition decorator call identifier argument_list identifier function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_...
Decorator converts function's arguments from dbus types to python.
def uninstall(self, xmlpath): from os import path fullpath = path.abspath(path.expanduser(xmlpath)) if fullpath in self.installed: repo = RepositorySettings(self, fullpath) if repo.name.lower() in self.repositories: del self.repositories[repo.name.lower()]...
module function_definition identifier parameters identifier identifier block import_from_statement dotted_name identifier dotted_name identifier expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier if_statement compar...
Uninstalls the repository with the specified XML path from the server.
def _parse_docstring(fh): find_fades = re.compile(r'\b(fades)\b:').search for line in fh: if line.startswith("'"): quote = "'" break if line.startswith('"'): quote = '"' break else: return {} if line[1] == quote: endquote = ...
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier for_statement identifier identifier block if_statement call attribute identifier identifier a...
Parse the docstrings of a script to find marked dependencies.
def _check_index_in_compilations(context: BaseContext, index: str): compilations = 'compilations' if compilations not in context.shared_data: return False return index in context.shared_data[compilations]
module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier block expression_statement assignment identifier string string_start string_content string_end if_statement comparison_operator identifier attribute identifier identifier block return_s...
Store compilation flag at specified index in context's shared data.
def do_annealing_poly(start:Number, end:Number, pct:float, degree:Number)->Number: "Helper function for `anneal_poly`." return end + (start-end) * (1-pct)**degree
module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier type identifier block expression_statement string string_start string_content string_end return_sta...
Helper function for `anneal_poly`.
def add_text(self, text, x, y, side='left', size=None, rotation=None, ha='left', va='center', family=None, **kws): axes = self.axes if side == 'right': axes = self.get_right_axes() dynamic_size = False if size is None: size = self...
module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier string string_start string_content string_end default_parameter identifier none default_parameter identifier none default_parameter identifier string string_start string_content string_end default_p...
add text at supplied x, y position
def portalAdmin(self): from ..manageportal import PortalAdministration return PortalAdministration(admin_url="https://%s/portaladmin" % self.portalHostname, securityHandler=self._securityHandler, proxy_url=self._proxy_url, ...
module function_definition identifier parameters identifier block import_from_statement relative_import import_prefix dotted_name identifier dotted_name identifier return_statement call identifier argument_list keyword_argument identifier binary_operator string string_start string_content string_end attribute identifie...
gets a reference to a portal administration class
def update_pos(pos_dict, start_key, nbr=2): "Update the `pos_dict` by moving all positions after `start_key` by `nbr`." for key,idx in pos_dict.items(): if str.lower(key) >= str.lower(start_key): pos_dict[key] += nbr return pos_dict
module function_definition identifier parameters identifier identifier default_parameter identifier integer block expression_statement string string_start string_content string_end for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement comparison_operator ...
Update the `pos_dict` by moving all positions after `start_key` by `nbr`.
def _request_with_error_ignored(self, rd): try: return self._request(rd) except Exception as err: LOG.warning(six.text_type(err))
module function_definition identifier parameters identifier identifier block try_statement block return_statement call attribute identifier identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list c...
Send smt request, log and ignore any errors.
def crpss(self): crps_f = self.crps() crps_c = self.crps_climo() return 1.0 - float(crps_f) / float(crps_c)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list return_statement binary_operator float binary_operator call identi...
Calculate the continous ranked probability skill score from existing data.
def _get_axis(self, name_or_index: AxisIdentifier) -> int: if isinstance(name_or_index, int): if name_or_index < 0 or name_or_index >= self.ndim: raise ValueError("No such axis, must be from 0 to {0}".format(self.ndim-1)) return name_or_index elif isinstance(name_...
module function_definition identifier parameters identifier typed_parameter identifier type identifier type identifier block if_statement call identifier argument_list identifier identifier block if_statement boolean_operator comparison_operator identifier integer comparison_operator identifier attribute identifier ide...
Get a zero-based index of an axis and check its existence.
def slice(self, start=0, end=0): tmp = Gauged.map_new() if tmp is None: raise MemoryError if not Gauged.map_concat(tmp, self.ptr, start, end, 0): Gauged.map_free(tmp) raise MemoryError return SparseMap(tmp)
module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier none block raise_statement identifier if_s...
Slice the map from [start, end)
def logout(request, template_name=None, next_page=None, redirect_field_name=REDIRECT_FIELD_NAME, current_app=None, extra_context=None): auth_logout(request) if next_page is not None: next_page = resolve_url(next_page) if (redirect_field_name in request.POST or ...
module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier identifier default_parameter identifier none default_parameter identifier none block expression_statement call identifier argument_list identifier if_statement com...
Logs out the user.
def asgate(self) -> Gate: gate = identity_gate(self.qubits) for elem in self.elements: gate = elem.asgate() @ gate return gate
module function_definition identifier parameters identifier type identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier for_statement identifier attribute identifier identifier block expression_statement assignment identifier binary_operator call attrib...
Return the action of this circuit as a gate
def index_service(self, service_id): from hypermap.aggregator.models import Service service = Service.objects.get(id=service_id) if not service.is_valid: LOGGER.debug('Not indexing service with id %s in search engine as it is not valid' % service.id) return LOGGER.debug('Indexing service...
module function_definition identifier parameters identifier identifier block import_from_statement dotted_name identifier identifier identifier dotted_name identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier...
Index a service in search engine.
def filepattern(self, *args, **kwargs): return [p.filepattern(*args, **kwargs) for p in self.problems]
module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block return_statement list_comprehension call attribute identifier identifier argument_list list_splat identifier dictionary_splat identifier for_in_clause identifier attribute identifier ident...
Returns a list of filepatterns, one for each problem.
def _install_requirements(path): locations = [os.path.join(path, "_blueprint"), os.path.join(path, "_base"), path] success = True for location in locations: try: with open(os.path.join(location, "requirements.txt")): puts("\nRequirements file found at {0}".format(os.path....
module function_definition identifier parameters identifier block expression_statement assignment identifier list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list ident...
Install a blueprint's requirements.txt
def validate_path_to_api_path(path, paths, basePath='', context=None, **kwargs): if context is None: context = {} try: api_path = match_path_to_api_path( path_definitions=paths, target_path=path, base_path=basePath, context=context, ) e...
module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_end default_parameter identifier none dictionary_splat_pattern identifier block if_statement comparison_operator identifier none block expression_statement assignment identifier dictionary try_...
Given a path, find the api_path it matches.
def user_saw_task(self, username, courseid, taskid): self._database.user_tasks.update({"username": username, "courseid": courseid, "taskid": taskid}, {"$setOnInsert": {"username": username, "courseid": courseid, "taskid": taskid, ...
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list dictionary pair string string_start string_content string_end identifier pair string string_start string_co...
Set in the database that the user has viewed this task
def _get_database(self, options): database_name = options.get('database') if not database_name: if len(settings.DATABASES) > 1: errmsg = "Because this project contains more than one database, you"\ " must specify the --database option." rai...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement not_operator identifier block if_statement comparison_operator call identifier argument_li...
Get the database to restore.
def getXML(self): s = '' for element in self._svgElements: s += element.getXML() return s
module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_end for_statement identifier attribute identifier identifier block expression_statement augmented_assignment identifier call attribute identifier identifier argument_list return_statem...
Retrieves the pysvg elements that make up the turtles path and returns them as String in an xml representation.
def _get_rpt_fmt(fld, val, itemid2name=None): if fld.startswith("ratio_"): return "{N}/{TOT}".format(N=val[0], TOT=val[1]) elif fld in set(['study_items', 'pop_items', 'alt_ids']): if itemid2name is not None: val = [itemid2name.get(v, v) for v in val] ...
module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block return_statement call attribute string string_start string_content string_end identifier argu...
Return values in a format amenable to printing in a table.
def apply(self, builder): if 'theme' in self.attributes: builder.apply_theme( self.attributes['theme'], builder.theme_options, )
module function_definition identifier parameters identifier identifier block if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement call attribute identifier identifier argument_list subscript attribute identifier identifier string strin...
Apply the Slide Configuration to a Builder.
def _get_first_all_link_record(self): _LOGGER.debug("Starting: _get_first_all_link_record") _LOGGER.info('Requesting ALL-Link Records') if self.aldb.status == ALDBStatus.LOADED: self._next_all_link_rec_nak_retries = 3 self._handle_get_next_all_link_record_nak(None) ...
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end if_statement compa...
Request first ALL-Link record.
def run(data): sample = data[0][0] work_dir = dd.get_work_dir(sample) out_dir = os.path.join(work_dir, "mirge") lib = _find_lib(sample) mirge = _find_mirge(sample) bowtie = _find_bowtie(sample) sps = dd.get_species(sample) species = SPS.get(sps, "") if not species: raise Valu...
module function_definition identifier parameters identifier block expression_statement assignment identifier subscript subscript identifier integer integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute a...
Proxy function to run the tool
def listen_now_dismissed_items(self): response = self._call( mc_calls.ListenNowGetDismissedItems ) dismissed_items = response.body.get('items', []) return dismissed_items
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string...
Get a listing of items dismissed from Listen Now tab.
def _get_login_shell(proc_cmd): login_shell = os.environ.get('SHELL', '') if login_shell: proc_cmd = login_shell else: proc_cmd = proc_cmd[1:] return (os.path.basename(proc_cmd).lower(), proc_cmd)
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 string string_start string_end if_statement identifier block expression_statement assignment ...
Form shell information from the SHELL environment variable if possible.
def _link_vertex_and_edge_types(self): for edge_class_name in self._edge_class_names: edge_element = self._elements[edge_class_name] if (EDGE_SOURCE_PROPERTY_NAME not in edge_element.properties or EDGE_DESTINATION_PROPERTY_NAME not in edge_element.properties): ...
module function_definition identifier parameters identifier block for_statement identifier attribute identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier if_statement parenthesized_expression boolean_operator comparison_operator identifier attribute...
For each edge, link it to the vertex types it connects to each other.
def parse(self): super(AcisIO, self).parse() for row in self.data: if 'meta' in row: row = row['meta'] if 'll' in row: row['longitude'], row['latitude'] = row['ll'] del row['ll']
module function_definition identifier parameters identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list for_statement identifier attribute identifier identifier block if_statement comparison_operator string string_start string_content string_end...
Convert ACIS 'll' value into separate latitude and longitude.
def packagePlugin(self, dir=os.getcwd(), extraArgs=[]): distDir = os.path.join(os.path.abspath(dir), 'dist') self.runUAT([ 'BuildPlugin', '-Plugin=' + self.getPluginDescriptor(dir), '-Package=' + distDir ] + extraArgs)
module function_definition identifier parameters identifier default_parameter identifier call attribute identifier identifier argument_list default_parameter identifier list block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute attribute ...
Packages a build of the Unreal plugin in the specified directory, suitable for use as a prebuilt Engine module
def size_request(self, widget, requisition): requisition.width, requisition.height = self.get_desired_size() return True
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment pattern_list attribute identifier identifier attribute identifier identifier call attribute identifier identifier argument_list return_statement true
Callback function to request our desired size.
def send_message(client, message): print(message) client.send("HTTP/1.1 200 OK\r\n\r\n{}".format(message).encode("utf-8")) client.close()
module function_definition identifier parameters identifier identifier block expression_statement call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute call attribute string string_start string_content escape_sequence escape_sequence escape_seque...
Send message to client and close the connection.
def send_comment_email(email, package_owner, package_name, commenter): link = '{CATALOG_URL}/package/{owner}/{pkg}/comments'.format( CATALOG_URL=CATALOG_URL, owner=package_owner, pkg=package_name) subject = "New comment on {package_owner}/{package_name}".format( package_owner=package_owner, pack...
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argume...
Send email to owner of package regarding new comment
def create_log(self): return EventLog( self.networkapi_url, self.user, self.password, self.user_ldap)
module function_definition identifier parameters identifier block return_statement call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier
Get an instance of log services facade.
def _1_0set_screen_config(self, size_id, rotation, config_timestamp, timestamp=X.CurrentTime): return _1_0SetScreenConfig( display=self.display, opcode=self.display.get_extension_major(extname), drawable=self, timestamp=timestamp, config_timestamp=config_timestamp, si...
module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier attribute identifier identifier block return_statement call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier call attribute attribute ...
Sets the screen to the specified size and rotation.
def isHouse1Asc(self): house1 = self.getHouse(const.HOUSE1) asc = self.getAngle(const.ASC) dist = angle.closestdistance(house1.lon, asc.lon) return abs(dist) < 0.0003
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier ex...
Returns true if House1 is the same as the Asc.
def _set_cdn_defaults(self): if self._cdn_enabled is FAULT: self._cdn_enabled = False self._cdn_uri = None self._cdn_ttl = DEFAULT_CDN_TTL self._cdn_ssl_uri = None self._cdn_streaming_uri = None self._cdn_ios_uri = None self._cdn_log_retention = False
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier identifier block expression_statement assignment attribute identifier identifier false expression_statement assignment attribute identifier identifier none expression_statement assignment a...
Sets all the CDN-related attributes to default values.
def calc_weight_of_multiple_paths(path_scores, impact_div=12): number_of_paths = len(path_scores) if number_of_paths > 1: score_total = 0.0 highest_score = 0.0 for score in path_scores.Scores: score_total += score if highest_score < score: highest_...
module function_definition identifier parameters identifier default_parameter identifier integer block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier integer block expression_statement assignment identifier float expression_statement assig...
Caluculate the weight of multipe paths.
def read_config_files(files): config = ConfigObj() for _file in files: _config = read_config_file(_file) if bool(_config) is True: config.merge(_config) config.filename = _config.filename return config
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator call identifier argume...
Read and merge a list of config files.
def update_combobox(self): index = self.current_scheme_index self.schemes_combobox.blockSignals(True) names = self.get_option("names") try: names.pop(names.index(u'Custom')) except ValueError: pass custom_names = self.get_option("custom_names", [])...
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list true expression_statement assignment identifier call attribute identifier identifier a...
Recreates the combobox contents.
def index(self): if self.bank is None: raise IndexError('Pedalboard not contains a bank') return self.bank.pedalboards.index(self)
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block raise_statement call identifier argument_list string string_start string_content string_end return_statement call attribute attribute attribute identifier identifier identifier i...
Returns the first occurrence of the pedalboard in your bank
def getDynMeth(name): cname, fname = name.rsplit('.', 1) clas = getDynLocal(cname) if clas is None: return None return getattr(clas, fname, None)
module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end integer expression_statement assignment identifier call identifier argument_list identifie...
Retrieve and return an unbound method by python path.
def battery_voltage(self): msb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_VOLTAGE_MSB_REG) lsb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_VOLTAGE_LSB_REG) voltage_bin = msb << 4 | lsb & 0x0f return voltage_bin * 1.1
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list id...
Returns voltage in mV
def _session_key(self): if not hasattr(self, "_cached_session_key"): session_id_bytes = self.get_secure_cookie("session_id") session_id = None if session_id_bytes: try: session_id = session_id_bytes.decode('utf-8') except: ...
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 identifier call attribute identifier identifier argument_list string string_start string_content string...
Gets the redis key for a session
def trim_empty_columns(self): if self.nrows != 0 and self.ncols != 0: last_col = -1 for row in self.rows: for i in range(last_col + 1, len(row)): if not self.is_cell_empty(row[i]): last_col = i ncols = last_col + 1 self.rows = [row[:ncols] for row in self.rows] ...
module function_definition identifier parameters identifier block if_statement boolean_operator comparison_operator attribute identifier identifier integer comparison_operator attribute identifier identifier integer block expression_statement assignment identifier unary_operator integer for_statement identifier attribu...
Removes all trailing empty columns.
def startup(api=None): def startup_wrapper(startup_function): apply_to_api = hug.API(api) if api else hug.api.from_object(startup_function) apply_to_api.add_startup_handler(startup_function) return startup_function return startup_wrapper
module function_definition identifier parameters default_parameter identifier none block function_definition identifier parameters identifier block expression_statement assignment identifier conditional_expression call attribute identifier identifier argument_list identifier identifier call attribute attribute identifi...
Runs the provided function on startup, passing in an instance of the api
def first_sunday(self, year, month): date = datetime(year, month, 1, 0) days_until_sunday = 6 - date.weekday() return date + timedelta(days=days_until_sunday)
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier integer integer expression_statement assignment identifier binary_operator integer call attribute identifier identifier argument_list ret...
Get the first sunday of a month.
def _deserialize(self, stream): self.version, self.entries, self._extension_data, conten_sha = read_cache(stream) return self
module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list attribute identifier identifier attribute identifier identifier attribute identifier identifier identifier call identifier argument_list identifier return_statement identifier
Initialize this instance with index values read from the given stream
def cache_result(cache_key, timeout): def decorator(f): cache_name = settings.WAFER_CACHE @functools.wraps(f) def wrapper(*args, **kw): cache = caches[cache_name] result = cache.get(cache_key) if result is None: result = f(*args, **kw) ...
module function_definition identifier parameters identifier identifier block function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier decorated_definition decorator call attribute identifier identifier argument_list identifier function_definit...
A decorator for caching the result of a function.
def dir_empty(d): flist = glob.glob(os.path.join(d,'*')) return (len(flist) == 0)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end return_statement parenthesized_...
Return True if given directory is empty, false otherwise.
def cache(self, f): if self._memory is None: logger.debug("Joblib is not installed: skipping cacheing.") return f assert f if 'self' in inspect.getargspec(f).args: ignore = ['self'] else: ignore = None disk_cached = self._memory.cac...
module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement identifier assert_statement iden...
Cache a function using the context's cache directory.
def _warn_unsafe_for_prod(self): safe_settings_list = [ ('DEBUG', False), ('DEBUG_GMN', False), ('STAND_ALONE', False), ('DATABASES.default.ATOMIC_REQUESTS', True), ('SECRET_KEY', '<Do not modify this placeholder value>'), ('STATIC_SERVER',...
module function_definition identifier parameters identifier block expression_statement assignment identifier list tuple string string_start string_content string_end false tuple string string_start string_content string_end false tuple string string_start string_content string_end false tuple string string_start string...
Warn on settings that are not safe for production.
def XXX_REMOVEME(func): @wraps(func) def decorator(self, *args, **kwargs): msg = "~~~~~~~ XXX REMOVEME marked method called: {}.{}".format( self.__class__.__name__, func.func_name) raise RuntimeError(msg) return func(self, *args, **kwargs) return decorator
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 expression_statement assignment identifier call attribute...
Decorator for dead code removal
def make_inst2(): I,d = multidict({1:45, 2:20, 3:30 , 4:30}) J,M = multidict({1:35, 2:50, 3:40}) c = {(1,1):8, (1,2):9, (1,3):14 , (2,1):6, (2,2):12, (2,3):9 , (3,1):10, (3,2):13, (3,3):16 , (4,1):9, (4,2):7, (4,3):5 , } return I,J,c,d,M
module function_definition identifier parameters block expression_statement assignment pattern_list identifier identifier call identifier argument_list dictionary pair integer integer pair integer integer pair integer integer pair integer integer expression_statement assignment pattern_list identifier identifier call i...
creates example data set 2
def _fetch_socket_data(self, parsed_url): self.log.debug("Fetching haproxy stats from socket: %s" % parsed_url.geturl()) if parsed_url.scheme == 'tcp': sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) splitted_loc = parsed_url.netloc.split(':') host = splitted...
module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end call attribute identifier identifier argument_list if_statement comparison_operator attr...
Hit a given stats socket and return the stats lines
def target_to_ipv4_long(target): splitted = target.split('-') if len(splitted) != 2: return None try: start_packed = inet_pton(socket.AF_INET, splitted[0]) end_packed = inet_pton(socket.AF_INET, splitted[1]) except socket.error: return None if end_packed < start_packe...
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator call identifier argument_list identifier integer block return_statement none try_...
Attempt to return a IPv4 long-range list from a target string.
def _getHeaders(self, updateParams=None): if not updateParams: updateParams = {} policies = self.defaultPolicies if len(updateParams) > 0: for k,v in updateParams.items(): k = k.replace('-','_') c = globals()[k](v) try: policies[k] = c.update_policy(self.defaultPolicies[k]) except Excep...
module function_definition identifier parameters identifier default_parameter identifier none block if_statement not_operator identifier block expression_statement assignment identifier dictionary expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator call identifier...
create headers list for flask wrapper
def total_memory(self, image='ubuntu'): try: ret = subprocess.check_output( f, shell=True, stdin=subprocess.DEVNULL) self.tot_mem = int(ret.split()[1]) except Exception: self.tot_mem = None return self.tot_mem
module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier true keyword_argument iden...
Get the available ram fo the docker machine in Kb
def check_owner_permission(payload, allow_user_owner): for entity_type in ['users', 'groups']: for perm_type in ['add', 'remove']: for perms in payload.get(entity_type, {}).get(perm_type, {}).values(): if 'owner' in perms: if entity_type == 'users' and allow_u...
module function_definition identifier parameters identifier identifier block for_statement identifier list string string_start string_content string_end string string_start string_content string_end block for_statement identifier list string string_start string_content string_end string string_start string_content stri...
Raise ``PermissionDenied``if ``owner`` found in ``data``.
def _trivialgraph_default_namer(thing, is_edge=True): if is_edge: if thing.name is None or thing.name.startswith('tmp'): return '' else: return '/'.join([thing.name, str(len(thing))]) elif isinstance(thing, Const): return str(thing.val) elif isinstance(thing, ...
module function_definition identifier parameters identifier default_parameter identifier true block if_statement identifier block if_statement boolean_operator comparison_operator attribute identifier identifier none call attribute attribute identifier identifier identifier argument_list string string_start string_cont...
Returns a "good" string for thing in printed graphs.
def _sort_kw_matches(skw_matches, limit=0): sorted_keywords = list(skw_matches.items()) sorted(sorted_keywords, key=cmp_to_key(_skw_matches_comparator)) return limit and sorted_keywords[:limit] or sorted_keywords
module function_definition identifier parameters identifier default_parameter identifier integer block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list expression_statement call identifier argument_list identifier keyword_argument identifier cal...
Return a resized version of keywords to the given length.
def unit_normal(pt_a, pt_b, pt_c): x_val = np.linalg.det([[1, pt_a[1], pt_a[2]], [1, pt_b[1], pt_b[2]], [1, pt_c[1], pt_c[2]]]) y_val = np.linalg.det([[pt_a[0], 1, pt_a[2]], [pt_b[0], 1, pt_b[2]], [pt_c[0], 1, pt_c[2]]]) z_val = np.linalg.det([[pt_a[0], pt_a[1], 1], [pt_b[0], pt_b[1], 1], [pt_c[0], pt_c[1],...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list list list integer subscript identifier integer subscript identifier integer list integer subscript identifier integer...
unit normal vector of plane defined by points pt_a, pt_b, and pt_c
def pack(self, value=None): if isinstance(value, Match): return value.pack() elif value is None: self._update_match_length() packet = super().pack() return self._complete_last_byte(packet) raise PackException(f'Match can\'t unpack "{value}".')
module function_definition identifier parameters identifier default_parameter identifier none block if_statement call identifier argument_list identifier identifier block return_statement call attribute identifier identifier argument_list elif_clause comparison_operator identifier none block expression_statement call a...
Pack and complete the last byte by padding.
def parse(self, lines): cur_entry = None for line in lines: kv_ = _key_value(line) if len(kv_) > 1: key, value = kv_ if key.lower() == "host": cur_entry = value self.hosts_.add(value) self.lin...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier none for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator call identifier argument_list identi...
Parse lines from ssh config file
def cdx_clamp(cdx_iter, from_ts, to_ts): if from_ts and len(from_ts) < 14: from_ts = pad_timestamp(from_ts, PAD_14_DOWN) if to_ts and len(to_ts) < 14: to_ts = pad_timestamp(to_ts, PAD_14_UP) for cdx in cdx_iter: if from_ts and cdx[TIMESTAMP] < from_ts: continue if...
module function_definition identifier parameters identifier identifier identifier block if_statement boolean_operator identifier comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier call identifier argument_list identifier identifier if_statement boolean_...
Clamp by start and end ts
def construct(self, force=False): message = super().construct(force=force) if self.tags: raw_tags = [] for tag, value in self.tags.items(): if value == True: raw_tags.append(tag) else: raw_tags.append(tag + T...
module function_definition identifier parameters identifier default_parameter identifier false block expression_statement assignment identifier call attribute call identifier argument_list identifier argument_list keyword_argument identifier identifier if_statement attribute identifier identifier block expression_state...
Construct raw IRC message and return it.
def formatter(self, key, value): template = "PUTVAL {host}/fedmsg/fedmsg_wallboard-{key} " +\ "interval={interval} {timestamp}:{value}" timestamp = int(time.time()) interval = self.hub.config['collectd_interval'] return template.format( host=self.host, ...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call identifier argument_list call att...
Format messages for collectd to consume.
def _unzip_handle(handle): if isinstance(handle, basestring): handle = _gzip_open_filename(handle) else: handle = _gzip_open_handle(handle) return handle
module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier else_clause block expression_statement assignment identifier call identifier argument_list identifi...
Transparently unzip the file handle
def run(self): while True: path, params = self.path_queue.get() errors = run(path, **params) self.result_queue.put(errors) self.path_queue.task_done()
module function_definition identifier parameters identifier block while_statement true block expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call identifier argument_list identifier dict...
Run tasks from queue.
def update_battery(self): if self.sk8 is None: return battery = self.sk8.get_battery_level() self.lblBattery.setText('Battery: {}%'.format(battery))
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block return_statement expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute ...
Updates the battery level in the UI for the connected SK8, if any
def list_joysticks(): print('Available joysticks:') print() for jid in range(pygame.joystick.get_count()): j = pygame.joystick.Joystick(jid) print('({}) {}'.format(jid, j.get_name()))
module function_definition identifier parameters block expression_statement call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list for_statement identifier call identifier argument_list call attribute attribute identifier identifier identifier argu...
Print a list of available joysticks
def dilated_attention_1d(x, hparams, attention_type="masked_dilated_1d", q_padding="VALID", kv_padding="VALID", gap_size=2): x, x_shape, is_4d = maybe_reshape_4d_to_3d(x) with tf.variable_sco...
module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_content string_end default_parameter identi...
Dilated 1d self attention.
def on_default_shell_changed(self, combo): citer = combo.get_active_iter() if not citer: return shell = combo.get_model().get_value(citer, 0) if shell == USER_SHELL_VALUE: self.settings.general.reset('default-shell') else: self.settings.general...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement not_operator identifier block return_statement expression_statement assignment identifier call attribute call attribute identifier ident...
Changes the activity of default_shell in dconf
def __check_http_err(self, status_code): if status_code == 403: raise exceptions.APIAuthenticationError(self.api_key) elif status_code == 503: raise exceptions.APITimeoutError() else: return False
module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier integer block raise_statement call attribute identifier identifier argument_list attribute identifier identifier elif_clause comparison_operator identifier integer block raise_statement call attribut...
Raises an exception if we get a http error
def all_pkgs_by_name_regex(self, regex_name, flags=0): reg = re.compile(regex_name, flags) return [pkg for pkg in self.all_pkgs().keys() if reg.match(pkg)]
module function_definition identifier parameters identifier identifier default_parameter identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier return_statement list_comprehension identifier for_in_clause identifier call attribute cal...
Return a list of packages that match regex_name.
def lincon(self, x, theta=0.01): if x[0] < 0: return np.NaN return theta * x[1] + x[0]
module function_definition identifier parameters identifier identifier default_parameter identifier float block if_statement comparison_operator subscript identifier integer integer block return_statement attribute identifier identifier return_statement binary_operator binary_operator identifier subscript identifier in...
ridge like linear function with one linear constraint
def construct_url(ip_address: str) -> str: if 'http://' not in ip_address and 'https://' not in ip_address: ip_address = '{}{}'.format('http://', ip_address) if ip_address[-1] == '/': ip_address = ip_address[:-1] return ip_address
module function_definition identifier parameters typed_parameter identifier type identifier type identifier block if_statement boolean_operator comparison_operator string string_start string_content string_end identifier comparison_operator string string_start string_content string_end identifier block expression_state...
Construct the URL with a given IP address.
def __up_cmp(self, obj1, obj2): if obj1.update_order > obj2.update_order: return 1 elif obj1.update_order < obj2.update_order: return -1 else: return 0
module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block return_statement integer elif_clause comparison_operator attribute identifier identifier attribute identifier identifier block re...
Defines how our updatable objects should be sorted
def _refresh_channel(self): self.channel = salt.transport.client.ReqChannel.factory(self.opts) return self.channel
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute attribute attribute attribute identifier identifier identifier identifier identifier argument_list attribute identifier identifier return_statement attribute identifier identi...
Reset the channel, in the event of an interruption
def resize(self, new_data_size): resize_bytes( self.__fileobj, self.data_size, new_data_size, self.data_offset) self._update_size(new_data_size)
module function_definition identifier parameters identifier identifier block expression_statement call identifier argument_list attribute identifier identifier attribute identifier identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier
Resize the file and update the chunk sizes
def __get_queue_opts(queue=None, backend=None): if queue is None: queue = __opts__.get('runner_queue', {}).get('queue') if backend is None: backend = __opts__.get('runner_queue', {}).get('backend', 'pgjsonb') return {'backend': backend, 'queue': queue}
module function_definition identifier parameters default_parameter identifier none default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list string string_start string_conten...
Get consistent opts for the queued runners
def CheckPreviousBarline(self, staff): measure_before_last = self.getMeasureAtPosition(-2, staff) last_measure = self.getMeasureAtPosition(-1, staff) if last_measure is not None and measure_before_last is not None: bline1 = measure_before_last.GetBarline("right") bline2 =...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list unary_operator integer identifier expression_statement assignment identifier call attribute identifier identifier argument_list unary_operator intege...
method which checks the bar before the current for changes we need to make to it's barlines
async def weather_type_classe(self): data = await self.retrieve(url=API_WEATHER_TYPE) self.weather_type = dict() for _type in data['data']: self.weather_type[_type['idWeatherType']] = _type['descIdWeatherTypePT'] return self.weather_type
module function_definition identifier parameters identifier block expression_statement assignment identifier await call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list for_statement identif...
Retrieve translation for weather type.
def attach_model(subscription, rgname, vmssvm_model, diskname, lun): disk_id = '/subscriptions/' + subscription + '/resourceGroups/' + rgname + \ '/providers/Microsoft.Compute/disks/' + diskname disk_model = {'lun': lun, 'createOption': 'Attach', 'caching': 'None', 'managedDisk': {'sto...
module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier binary_operator binary_operator binary_operator binary_operator binary_operator string string_start string_content string_end identifier string string_start string_con...
Attach a data disk to a VMSS VM model
def make_multi_cols(self, num_class, name): cols = ['c' + str(i) + '_' for i in xrange(num_class)] cols = map(lambda x: x + name, cols) return cols
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier list_comprehension binary_operator binary_operator string string_start string_content string_end call identifier argument_list identifier string string_start string_content string_end for_i...
make cols for multi-class predictions
def save_direction(self, rootpath, raw=False, as_int=False): self.save_array(self.direction, None, 'ang', rootpath, raw, as_int=as_int)
module function_definition identifier parameters identifier identifier default_parameter identifier false default_parameter identifier false block expression_statement call attribute identifier identifier argument_list attribute identifier identifier none string string_start string_content string_end identifier identif...
Saves the direction of the slope to a file
def _write_service_config(self): with open(self.config_path, 'w') as output: output.write(json.dumps(self.data, sort_keys=True, indent=4))
module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call identifier argument_list attribute identifier identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argum...
Will write the config out to disk.
def sort_by_priority(iterable, reverse=False, default_priority=10): return sorted(iterable, reverse=reverse, key=lambda o: getattr(o, 'priority', default_priority))
module function_definition identifier parameters identifier default_parameter identifier false default_parameter identifier integer block return_statement call identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier lambda lambda_parameters identifier call identifier argum...
Return a list or objects sorted by a priority value.
def _getPOS( self, token, onlyFirst = True ): if onlyFirst: return token[ANALYSIS][0][POSTAG] else: return [ a[POSTAG] for a in token[ANALYSIS] ]
module function_definition identifier parameters identifier identifier default_parameter identifier true block if_statement identifier block return_statement subscript subscript subscript identifier identifier integer identifier else_clause block return_statement list_comprehension subscript identifier identifier for_i...
Returns POS of the current token.
def _any_pandas_objects(terms): return any(isinstance(term.value, pd.core.generic.PandasObject) for term in terms)
module function_definition identifier parameters identifier block return_statement call identifier generator_expression call identifier argument_list attribute identifier identifier attribute attribute attribute identifier identifier identifier identifier for_in_clause identifier identifier
Check a sequence of terms for instances of PandasObject.
def generate(env): static_obj, shared_obj = SCons.Tool.createObjBuilders(env) for suffix in ASSuffixes: static_obj.add_action(suffix, SCons.Defaults.ASAction) static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter) for suffix in ASPPSuffixes: static_obj.add_action(suffix, ...
module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argu...
Add Builders and construction variables for nasm to an Environment.
def CheckBlobsExist(self, blob_ids, cursor=None): if not blob_ids: return {} exists = {blob_id: False for blob_id in blob_ids} query = ("SELECT blob_id " "FROM blobs " "FORCE INDEX (PRIMARY) " "WHERE blob_id IN {}".format( mysql_utils.Placeholder...
module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement not_operator identifier block return_statement dictionary expression_statement assignment identifier dictionary_comprehension pair identifier false for_in_clause identifier identifier expression_s...
Checks if given blobs exist.
def deserialize(self, data, status_code): if status_code == 204: return data return serializer.Serializer().deserialize( data)['body']
module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier integer block return_statement identifier return_statement subscript call attribute call attribute identifier identifier argument_list identifier argument_list identifier string string_sta...
Deserializes a JSON string into a dictionary.
def announce(self, discovery): try: url = self.__discovery_url() logger.debug("making announce request to %s" % (url)) response = None response = self.client.put(url, data=self.to_json(discovery), ...
module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string...
With the passed in Discovery class, attempt to announce to the host agent.
def all_files(file_or_directory): 'return all files under file_or_directory.' if os.path.isdir(file_or_directory): return [os.path.join(dirname, filename) for dirname, dirnames, filenames in os.walk(file_or_directory) for filename in filenames] else: return [f...
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end if_statement call attribute attribute identifier identifier identifier argument_list identifier block return_statement list_comprehension call attribute attribute identifier identifier id...
return all files under file_or_directory.
def parse_config(app): try: plot_gallery = eval(app.builder.config.plot_gallery) except TypeError: plot_gallery = bool(app.builder.config.plot_gallery) src_dir = app.builder.srcdir abort_on_example_error = app.builder.config.abort_on_example_error lang = app.builder.config.highlight_...
module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier call identifier argument_list attribute attribute attribute identifier identifier identifier identifier except_clause identifier block expression_statement assignment identifier call identifi...
Process the Sphinx Gallery configuration