Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
365,800
def editproject(self, project_id, **kwargs): data = {"id": project_id} if kwargs: data.update(kwargs) request = requests.put( .format(self.projects_url, project_id), headers=self.headers, data=data, verify=self.verify_ssl, auth=self.auth, timeout=se...
Edit an existing project. :param name: new project name :param path: custom repository name for new project. By default generated based on name :param default_branch: they default branch :param description: short project description :param issues_enabled: :param merge_re...
365,801
def stackexchange_request(self, path, callback, access_token=None, post_args=None, **kwargs): url = self._API_URL + path all_args = {} if access_token: all_args["access_token"] = access_token all_args.update(kwargs) if all_args: ...
Make a request to the StackExchange API, passing in the path, a callback, the access token, optional post arguments and keyword arguments to be added as values in the request body or URI
365,802
def _compute_term2(self, C, mag, rrup): c78_factor = (C[] * np.exp(C[] * mag)) ** 2 R = np.sqrt(rrup ** 2 + c78_factor) return C[] * np.log(R) + (C[] + C[] * mag) * rrup
This computes the term f2 in equation 32, page 1021
365,803
def getSrcBlockParents(self, url, block): params={:block} return cjson.decode(self.callDBSService(url, , params, {}))
List block at src DBS
365,804
def _converged(self): diff = self.local_prior - self.local_posterior_ max_diff = np.max(np.fabs(diff)) if self.verbose: _, mse = self._mse_converged() diff_ratio = np.sum(diff ** 2) / np.sum(self.local_posterior_ ** 2) logger.info( % ...
Check convergence based on maximum absolute difference Returns ------- converged : boolean Whether the parameter estimation converged. max_diff : float Maximum absolute difference between prior and posterior.
365,805
def killall(self, everywhere=False): with self._NAILGUN_KILL_LOCK: for proc in self._iter_nailgun_instances(everywhere): logger.info(.format(pid=proc.pid)) proc.terminate()
Kills all nailgun servers started by pants. :param bool everywhere: If ``True``, kills all pants-started nailguns on this machine; otherwise restricts the nailguns killed to those started for the current build root.
365,806
def total_length(self): if not self._captions: return 0 return int(self._captions[-1].end_in_seconds) - int(self._captions[0].start_in_seconds)
Returns the total length of the captions.
365,807
def _render_condition(field, field_type, comparators): field_type = field_type.upper() negated_conditions, normal_conditions = [], [] for comparator in comparators: condition = comparator.get("condition").upper() negated = "NOT " if comparator.get("negate") else "" value = co...
Render a single query condition. Parameters ---------- field : str The field the condition applies to field_type : str The data type of the field. comparators : array_like An iterable of logic operators to use. Returns ------- str a condition string.
365,808
def _identify_dict(core): if not core: return {}, 1, (), int core = core.copy() key = sorted(core.keys(), key=chaospy.poly.base.sort_key)[0] shape = numpy.array(core[key]).shape dtype = numpy.array(core[key]).dtype dim = len(key) return core, dim, shape, dtype
Specification for a dictionary.
365,809
def rotate_about(self, p, theta): result = self.clone() result.translate(-p.x, -p.y) result.rotate(theta) result.translate(p.x, p.y) return result
Rotate counter-clockwise around a point, by theta degrees. Positive y goes *up,* as in traditional mathematics. The new position is returned as a new Point.
365,810
def delete(self, filename): folder = "Packages" if is_package(filename) else "Scripts" path = os.path.join(self.connection["mount_point"], folder, filename) if os.path.isdir(path): shutil.rmtree(path) elif os.path.isfile(path): os.remove(path)
Delete a file from the repository. This method will not delete a script from a migrated JSS. Please remove migrated scripts with jss.Script.delete. Args: filename: String filename only (i.e. no path) of file to delete. Will handle deleting scripts vs. packages ...
365,811
def set_granularity(self, level): if level in self.MFCC_GRANULARITY_MAP.keys(): margin_key, mask_key, length_key, shift_key = self.MFCC_GRANULARITY_MAP[level] self[self.DTW_MARGIN] = self[margin_key] self[self.MFCC_MASK_NONSPEECH] = self[mask_key] self[se...
Set the values for :data:`~aeneas.runtimeconfiguration.RuntimeConfiguration.MFCC_WINDOW_LENGTH` and :data:`~aeneas.runtimeconfiguration.RuntimeConfiguration.MFCC_WINDOW_SHIFT` matching the given granularity level. Currently supported levels: * ``1`` (paragraph) ...
365,812
def skip_incremental(self, *criteria): if not self.incremental: return False key = make_key(*criteria) if key is None: return False if self.check_tag(key): return True self.set_tag(key, None) return False
Perform an incremental check on a set of criteria. This can be used to execute a part of a crawler only once per an interval (which is specified by the ``expire`` setting). If the operation has already been performed (and should thus be skipped), this will return ``True``. If the operat...
365,813
def handleError(self, error_code, message): self._fail = True self.reason = error_code self._error = message
Log and set the controller state.
365,814
def registry_storage(cls): if cls.__registry_storage__ is None: raise ValueError() if isinstance(cls.__registry_storage__, WTaskRegistryBase) is False: raise TypeError("Property is invalid (must derived from WTaskRegistryBase)") return cls.__registry_storage__
Get registry storage :return: WTaskRegistryBase
365,815
def delete(self): check_bind(self) if self.id is None: raise ServerError("{} object does not exist yet".format(self.__class__.name)) elif not self.__class__._has_schema_method("destroy"): raise MethodNotSupported("{} do not support deletion.".format(self.__class_...
Delete this object from the One Codex server.
365,816
def dimension_set(self, p_dim, s_dim=None, dimensions=None, extant=set()): if not dimensions: dimensions = self.primary_dimensions key = p_dim.name if s_dim: key += + s_dim.name if key in extant or p_dim == s_dim: return ...
Return a dict that describes the combination of one or two dimensions, for a plot :param p_dim: :param s_dim: :param dimensions: :param extant: :return:
365,817
def output_format_lock(self, packages, **kwargs): self._output_config[] = PLAIN text = tmp_packages = OrderedDict() columns = self._config.get_columns() widths = {} for _pkg in packages.values(): _pkg_name = _pkg.package_name _params = _p...
Text to lock file
365,818
def print_obj(arg, frame, format=None, short=False): try: if not frame: obj = eval(arg, None, None) else: obj = eval(arg, frame.f_globals, frame.f_locals) pass except: return + arg + what = arg if format: ...
Return a string representation of an object
365,819
def window_flattop(N, mode=,precision=None): r assert mode in [, ] t = arange(0, N) if mode == : x = 2*pi*t/float(N) else: if N ==1: return ones(1) x = 2*pi*t/float(N-1) a0 = 0.21557895 a1 = 0.41663158 a2 = 0.277263158 a3 = 0.083578947 a4...
r"""Flat-top tapering window Returns symmetric or periodic flat top window. :param N: window length :param mode: way the data are normalised. If mode is *symmetric*, then divide n by N-1. IF mode is *periodic*, divide by N, to be consistent with octave code. When using windows for fil...
365,820
def salt_ssh(project, target, module, args=None, kwargs=None): cmd = [] cmd.extend(generate_salt_cmd(target, module, args, kwargs)) cmd.append() cmd.append( % project.roster_path) cmd.append( % project.salt_ssh_config_dir) cmd.append() cmd.append() cmd = .join(cmd) logger.debug(...
Execute a `salt-ssh` command
365,821
def build_dated_queryset(self): qs = self.get_dated_queryset() months = self.get_date_list(qs) [self.build_month(dt) for dt in months]
Build pages for all years in the queryset.
365,822
def get_resampled_coordinates(lons, lats): num_coords = len(lons) assert num_coords == len(lats) lons1 = numpy.array(lons) lats1 = numpy.array(lats) lons2 = numpy.concatenate((lons1[1:], lons1[:1])) lats2 = numpy.concatenate((lats1[1:], lats1[:1])) distances = geodetic.geodetic_distanc...
Resample polygon line segments and return the coordinates of the new vertices. This limits distortions when projecting a polygon onto a spherical surface. Parameters define longitudes and latitudes of a point collection in the form of lists or numpy arrays. :return: A tuple of two numpy ar...
365,823
def complete_use(self, text, *_): return [t + " " for t in REGIONS if t.startswith(text)]
Autocomplete for use
365,824
def add_tags(self, md5, tags): if not tags: return tag_set = set(self.get_tags(md5)) if self.get_tags(md5) else set() if isinstance(tags, str): tags = [tags] for tag in tags: tag_set.add(tag) self.data_store.store_work_results({: list(tag_set)}, ,...
Add tags to this sample
365,825
def get_info(self, component): work_results = self._get_work_results(, component) return self.data_store.clean_for_serialization(work_results)
Get the information about this component
365,826
def _find_highest_supported_command(self, *segment_classes, **kwargs): return_parameter_segment = kwargs.get("return_parameter_segment", False) parameter_segment_name = "{}I{}S".format(segment_classes[0].TYPE[0], segment_classes[0].TYPE[2:]) version_map = dict((clazz.VERSION, clazz) fo...
Search the BPD for the highest supported version of a segment.
365,827
def is_pointer(type_): return does_match_definition(type_, cpptypes.pointer_t, (cpptypes.const_t, cpptypes.volatile_t)) \ or does_match_definition(type_, cpptypes.pointer_t, ...
returns True, if type represents C++ pointer type, False otherwise
365,828
def normalize_url(url): if not url: return url matched = _windows_path_prefix.match(url) if matched: return path2url(url) p = six.moves.urllib.parse.urlparse(url) if p.scheme == : if p.netloc == and p.path != : url = path2url(os.path.abspath(u...
Normalize url
365,829
def command(self): print() args = self.parser.parse_args() verify_common_args(args) client = clientfromkwargs(**args) delta = do_ofximport(args.file, client) client.push(expected_delta=delta)
Manually import an OFX into a nYNAB budget
365,830
def get_manifests(self, repo_name, digest=None): if not hasattr(self, ): self.manifests = {} schemaVersions = [, , ] for schemaVersion in schemaVersions: manifest = self._get_manifest(repo_name, digest, schemaVersion) if manifest is not None: se...
get_manifests calls get_manifest for each of the schema versions, including v2 and v1. Version 1 includes image layers and metadata, and version 2 must be parsed for a specific manifest, and the 2nd call includes the layers. If a digest is not provided latest is used. Parameters ...
365,831
def getShocks(self): employed = self.eStateNow == 1.0 N = int(np.sum(employed)) newly_unemployed = drawBernoulli(N,p=self.UnempPrb,seed=self.RNG.randint(0,2**31-1)) self.eStateNow[employed] = 1.0 - newly_unemployed
Determine which agents switch from employment to unemployment. All unemployed agents remain unemployed until death. Parameters ---------- None Returns ------- None
365,832
def jsonrpc_map(self): result = "<h1>JSON-RPC map</h1><pre>{0}</pre>".format("\n\n".join([ "{0}: {1}".format(fname, f.__doc__) for fname, f in self.dispatcher.items() ])) return Response(result)
Map of json-rpc available calls. :return str:
365,833
def view_dot_graph(graph, filename=None, view=False): import graphviz as gv src = gv.Source(graph) if view: return src.render(filename, view=view) else: try: __IPYTHON__ except NameError: return src else: im...
View the given DOT source. If view is True, the image is rendered and viewed by the default application in the system. The file path of the output is returned. If view is False, a graphviz.Source object is returned. If view is False and the environment is in a IPython session, an IPython image objec...
365,834
def wait_for_port(host, port=22, timeout=900, gateway=None): start = time.time() test_ssh_host = host test_ssh_port = port if gateway: ssh_gateway = gateway[] ssh_gateway_port = 22 if in ssh_gateway: ssh_gateway, ssh_gateway_port = ssh_gateway.split()...
Wait until a connection to the specified port can be made on a specified host. This is usually port 22 (for SSH), but in the case of Windows installations, it might be port 445 (for psexec). It may also be an alternate port for SSH, depending on the base image.
365,835
def apply_rcparams(self): from matplotlib import rcParams for key, val in self.rcParams.items(): try: rcParams[key] = val except Exception as e: msg = ( "raised an Exception: {}") raise PlotnineError(...
Set the rcParams
365,836
def _compute_static_prob(tri, com): sv = [(v - com) / np.linalg.norm(v - com) for v in tri] a = np.arccos(min(1, max(-1, np.dot(sv[0], sv[1])))) b = np.arccos(min(1, max(-1, np.dot(sv[1], sv[2])))) c = np.arccos(min(1, max(-1, np.dot(sv[2], sv[0])))) s = (a + b + c) / 2.0 try: ...
For an object with the given center of mass, compute the probability that the given tri would be the first to hit the ground if the object were dropped with a pose chosen uniformly at random. Parameters ---------- tri: (3,3) float, the vertices of a triangle cm: (3,) float, the center of mass ...
365,837
def for_category(self, category, context=None): assert self.installed(), "Actions not enabled on this application" actions = self._state["categories"].get(category, []) if context is None: context = self.context return [a for a in actions if a.available(context)]
Returns actions list for this category in current application. Actions are filtered according to :meth:`.Action.available`. if `context` is None, then current action context is used (:attr:`context`)
365,838
def browse_stations_categories(self): response = self._call( mc_calls.BrowseStationCategories ) station_categories = response.body.get(, {}).get(, []) return station_categories
Get the categories from Browse Stations. Returns: list: Station categories that can contain subcategories.
365,839
def define_options(self, names, parser_options=None): def copy_option(options, name): return {k: v for k, v in options[name].items()} if parser_options is None: parser_options = {} options = {} for name in names: try: option = ...
Given a list of option names, this returns a list of dicts defined in all_options and self.shared_options. These can then be used to populate the argparser with
365,840
def print_smart_tasks(): print("Printing information about smart tasks") tasks = api(gateway.get_smart_tasks()) if len(tasks) == 0: exit(bold("No smart tasks defined")) container = [] for task in tasks: container.append(api(task).task_control.raw) print(jsonify(container))
Print smart tasks as JSON
365,841
def pretty_constants(self): for i in range(1, len(self.consts)): t, v = self.pretty_const(i) if t: yield (i, t, v)
the sequence of tuples (index, pretty type, value) of the constant pool entries.
365,842
def get_objective_requisite_assignment_session(self, *args, **kwargs): if not self.supports_objective_requisite_assignment(): raise Unimplemented() try: from . import sessions except ImportError: raise OperationFailed() try: sessio...
Gets the session for managing objective requisites. return: (osid.learning.ObjectiveRequisiteAssignmentSession) - an ObjectiveRequisiteAssignmentSession raise: OperationFailed - unable to complete request raise: Unimplemented - supports_objective_requisite_assi...
365,843
def check_file_path(self, path): if os.path.exists(path) is not True: msg = "File Not Found {}".format(path) raise OSError(msg)
Ensure file exists at the provided path :type path: string :param path: path to directory to check
365,844
def double_prompt_for_plaintext_password(): password = 1 password_repeat = 2 while password != password_repeat: password = getpass.getpass() password_repeat = getpass.getpass() if password != password_repeat: sys.stderr.write() return password
Get the desired password from the user through a double prompt.
365,845
def send_many(self, outputs_array, fee=None, change_addr=None, id=None, endpoint=None): params = [outputs_array] if fee: params.append(fee) if fee and change_addr: params.append(change_addr) elif not fee and change_addr: params.append(0) ...
Args: outputs_array: (dict) array, the data structure of each element in the array is as follows: {"asset": <asset>,"value": <value>,"address": <address>} asset: (str) asset identifier (for NEO: 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', for GAS: '602...
365,846
def _validate_currency(self, currency): if currency not in self.major_currencies: raise InvalidCurrencyError( {}\ .format(currency, tuple(self.major_currencies)) )
Check if the given order book is valid. :param currency: Major currency name in lowercase. :type currency: str | unicode :raise InvalidCurrencyError: If an invalid major currency is given.
365,847
def dumps(value,encoding=None): q = deque() _rdumpq(q,0,value,encoding) return "".join(q)
dumps(object,encoding=None) -> string This function dumps a python object as a tnetstring.
365,848
def cancel(self, CorpNum, ItemCode, MgtKey, Memo=None, UserID=None): if MgtKey == None or MgtKey == "": raise PopbillException(-99999999, "๊ด€๋ฆฌ๋ฒˆํ˜ธ๊ฐ€ ์ž…๋ ฅ๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.") if ItemCode == None or ItemCode == "": raise PopbillException(-99999999, "๋ช…์„ธ์„œ ์ข…๋ฅ˜ ์ฝ”๋“œ๊ฐ€ ์ž…๋ ฅ๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.") ...
๋ฐœํ–‰์ทจ์†Œ args CorpNum : ํŒ๋นŒํšŒ์› ์‚ฌ์—…์ž๋ฒˆํ˜ธ ItemCode : ๋ช…์„ธ์„œ ์ข…๋ฅ˜ ์ฝ”๋“œ [121 - ๊ฑฐ๋ž˜๋ช…์„ธ์„œ], [122 - ์ฒญ๊ตฌ์„œ], [123 - ๊ฒฌ์ ์„œ], [124 - ๋ฐœ์ฃผ์„œ], [125 - ์ž…๊ธˆํ‘œ], [126 - ์˜์ˆ˜์ฆ] MgtKey : ํŒŒํŠธ๋„ˆ ๋ฌธ์„œ๊ด€๋ฆฌ๋ฒˆํ˜ธ Memo : ์ฒ˜๋ฆฌ๋ฉ”๋ชจ UserID : ํŒ๋นŒํšŒ์› ์•„์ด๋””...
365,849
def gcp_fixed_k(V,E,K): model = Model("gcp - fixed k") x,z = {},{} for i in V: for k in range(K): x[i,k] = model.addVar(vtype="B", name="x(%s,%s)"%(i,k)) for (i,j) in E: z[i,j] = model.addVar(vtype="B", name="z(%s,%s)"%(i,j)) for i in V: model.addCons(quick...
gcp_fixed_k -- model for minimizing number of bad edges in coloring a graph Parameters: - V: set/list of nodes in the graph - E: set/list of edges in the graph - K: number of colors to be used Returns a model, ready to be solved.
365,850
def get_dvcs_info(): cmd = "git rev-list --count HEAD" commit_count = str( int(subprocess.check_output(shlex.split(cmd)).decode("utf8").strip()) ) cmd = "git rev-parse HEAD" commit = str(subprocess.check_output(shlex.split(cmd)).decode("utf8").strip()) return {Constants.COMMIT_FIELD...
Gets current repository info from git
365,851
def security_rule_present(name, access, direction, priority, protocol, security_group, resource_group, destination_address_prefix=None, destination_port_range=None, source_address_prefix=None, source_port_range=None, description=None, destination_address_prefixes=None...
.. versionadded:: 2019.2.0 Ensure a security rule exists. :param name: Name of the security rule. :param access: 'allow' or 'deny' :param direction: 'inbound' or 'outbound' :param priority: Integer between 100 and 4096 used for ordering rule application. :pa...
365,852
def bake(self): command_list = self.command.split() command, args = command_list[0], command_list[1:] self._sh_command = getattr(sh, command) self._sh_command = self._sh_command.bake( args, _env=self.env, _out=LOG.out, _err=LOG.error)
Bake a ``shell`` command so it's ready to execute and returns None. :return: None
365,853
def tagMap(self): if self.tagSet: return Set.tagMap.fget(self) else: return self.componentType.tagMapUnique
Return a :class:`~pyasn1.type.tagmap.TagMap` object mapping ASN.1 tags to ASN.1 objects contained within callee.
365,854
def sync_via_get(self, owner, id, **kwargs): kwargs[] = True if kwargs.get(): return self.sync_via_get_with_http_info(owner, id, **kwargs) else: (data) = self.sync_via_get_with_http_info(owner, id, **kwargs) return data
Sync files (via GET) Update all files within a dataset that have originally been added via URL (e.g. via /datasets endpoints or on data.world). Check-out or tutorials for tips on how to add Google Sheets, GitHub and S3 files via URL and how to use webhooks or scripts to keep them always in sync. This m...
365,855
def close(self): self._socket.close() if self._async_socket_cache: self._async_socket_cache.close() self._async_socket_cache = None
Close the sockets
365,856
def install(self): try: if self.args.server is not None: server = ServerLists(self.server_type) DynamicImporter( , server.name, args=self.args, configure=self.configure ...
install the server
365,857
def verify_message(address, message, signature): bitcoin_message = BitcoinMessage(message) verified = VerifyMessage(address, bitcoin_message, signature) return verified
Verify message was signed by the address :param address: signing address :param message: message to check :param signature: signature being tested :return:
365,858
def top(self): if self.vMerge is None or self.vMerge == ST_Merge.RESTART: return self._tr_idx return self._tc_above.top
The top-most row index in the vertical span of this cell.
365,859
def _register_handler(handler, file_formats): if not isinstance(handler, BaseFileHandler): raise TypeError( .format( type(handler))) if isinstance(file_formats, str): file_formats = [file_formats] if not is_list_of(file_formats, str): raise TypeError(...
Register a handler for some file extensions. Args: handler (:obj:`BaseFileHandler`): Handler to be registered. file_formats (str or list[str]): File formats to be handled by this handler.
365,860
def astat(args): p = OptionParser(astat.__doc__) p.add_option("--cutoff", default=1000, type="int", help="Length cutoff [default: %default]") p.add_option("--genome", default="", help="Genome name [default: %default]") p.add_option("--arrDist", default=False, actio...
%prog astat coverage.log Create coverage-rho scatter plot.
365,861
def fit(sim_mat, D_len, cidx): min_energy = np.inf for j in range(3): inds = [np.argmin([sim_mat[idy].get(idx, 0) for idx in cidx]) for idy in range(D_len) if idy in sim_mat] cidx = [] energy = 0 for i in np.unique(inds): indsi = np.where(inds == i)[...
Algorithm maximizes energy between clusters, which is distinction in this algorithm. Distance matrix contains mostly 0, which are overlooked due to search of maximal distances. Algorithm does not try to retain k clusters. D: numpy array - Symmetric distance matrix k: int - number of clusters
365,862
def set_span_from_ids(self, span_list): this_span = Cspan() this_span.create_from_ids(span_list) self.node.append(this_span.get_node())
Sets the span for the term from list of ids @type span_list: [] @param span_list: list of wf ids forming span
365,863
def apply_status_code(self, status_code): self._check_ended() if not status_code: return if status_code >= 500: self.add_fault_flag() elif status_code == 429: self.add_throttle_flag() self.add_error_flag() elif status_code...
When a trace entity is generated under the http context, the status code will affect this entity's fault/error/throttle flags. Flip these flags based on status code.
365,864
def get_system_device_models(auth, url): get_system_device_model_url = f_url = url + get_system_device_model_url r = requests.get(f_url, auth=auth, headers=HEADERS) try: if r.status_code == 200: system_device_model = (json.loads(r.text)) return system_devi...
Takes string no input to issue RESTUL call to HP IMC\n :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dictionaries where each dictionary represents a single ...
365,865
def parse_frequency(variant, info_key): raw_annotation = variant.INFO.get(info_key) raw_annotation = None if raw_annotation == else raw_annotation frequency = float(raw_annotation) if raw_annotation else None return frequency
Parse any frequency from the info dict Args: variant(cyvcf2.Variant) info_key(str) Returns: frequency(float): or None if frequency does not exist
365,866
def _process_templatedata(self, node, **_): value = re.sub(, r, node.data) value = re.sub(, r, value) self.output.write( + value + )
Processes a `TemplateData` node, this is just a bit of as-is text to be written to the output.
365,867
def get_context_loop_positions(context): try: loop_counter = context[][] except KeyError: return 0, 0 try: page = context[] except KeyError: return loop_counter, loop_counter total_loop_counter = ((page.number - 1) * page.paginator.per_page + ...
Return the paginated current position within a loop, and the non-paginated position.
365,868
def pwd_phasebin(phases, mags, binsize=0.002, minbin=9): bins = np.arange(0.0, 1.0, binsize) binnedphaseinds = npdigitize(phases, bins) binnedphases, binnedmags = [], [] for x in npunique(binnedphaseinds): thisbin_inds = binnedphaseinds == x thisbin_phases = phases[thisbin_inds]...
This bins the phased mag series using the given binsize.
365,869
def sql(line, cell=None): if cell is None: _sql_parser.print_help() else: return handle_magic_line(line, cell, _sql_parser)
Create a SQL module with one or more queries. Use %sql --help for more details. The supported syntax is: %%sql [--module <modulename>] [<optional Python code for default argument values>] [<optional named queries>] [<optional unnamed query>] At least one query should be present. Named queries should star...
365,870
def bind_arguments(func, args, kwargs): ( args, kwargs, missing, extra, extra_positional, arg_spec, vararg_var, kwarg_var, ) = _parse_signature(func)(args, kwargs) values = {} for (name, _has_default, _default), value in zip(arg_spec, ...
Bind the arguments provided into a dict. When passed a function, a tuple of arguments and a dict of keyword arguments `bind_arguments` returns a dict of names as the function would see it. This can be useful to implement a cache decorator that uses the function arguments to build the cache key based o...
365,871
def compute_Pi_V(self, CDR3_seq, V_usage_mask): Pi_V = np.zeros((4, len(CDR3_seq)*3)) alignment_lengths = [] for V_in in V_usage_mask: try: cutV_gen_seg = self.cutV_genomic_CDR3_segs[V_in] except IndexError: ...
Compute Pi_V. This function returns the Pi array from the model factors of the V genomic contributions, P(V)*P(delV|V). This corresponds to V_{x_1}. For clarity in parsing the algorithm implementation, we include which instance attributes are used in the method as 'param...
365,872
def single_column_accuracy_comparison(): pointRange = 1 numTrials = 10 args = [] resultsDir = os.path.dirname(os.path.realpath(__file__)) for t in range(numTrials): for useLocation in [0, 1]: args.append( {"numObjects": 100, "numLocations": 10, "numFeatures": 10, ...
Plot accuracy of the ideal observer (with and without locations) as the number of sensations increases.
365,873
def send_with_options(self, *, args=None, kwargs=None, delay=None, **options): message = self.message_with_options(args=args, kwargs=kwargs, **options) return self.broker.enqueue(message, delay=delay)
Asynchronously send a message to this actor, along with an arbitrary set of processing options for the broker and middleware. Parameters: args(tuple): Positional arguments that are passed to the actor. kwargs(dict): Keyword arguments that are passed to the actor. d...
365,874
def by_pdb(self, pdb_id, take_top_percentile = 30.0, cut_off = None, matrix = None, sequence_identity_cut_off = None, silent = None): self.log(.format(pdb_id), silent, colortext.pcyan) matrix = matrix or self.matrix cut_off = cut_off or self.cut_off sequence_identity_...
Returns a list of all PDB files which contain protein sequences similar to the protein sequences of pdb_id. Only protein chains are considered in the matching so e.g. some results may have DNA or RNA chains or ligands while some may not.
365,875
def _setup_arch(self, arch_mode=None): self.arch_info = None if self.binary.architecture == ARCH_X86: self._setup_x86_arch(arch_mode) else: self._setup_arm_arch(arch_mode)
Set up architecture.
365,876
def create(self, source, destination, gateway_ip, comment=None): self.items.append(dict( source=source, destination=destination, gateway_ip=gateway_ip, comment=comment))
Add a new policy route to the engine. :param str source: network address with /cidr :param str destination: network address with /cidr :param str gateway: IP address, must be on source network :param str comment: optional comment
365,877
def stop_channels(self): if self.shell_channel.is_alive(): self.shell_channel.stop() if self.sub_channel.is_alive(): self.sub_channel.stop() if self.stdin_channel.is_alive(): self.stdin_channel.stop() if self.hb_channel.is_alive(): ...
Stops all the running channels for this kernel.
365,878
def draw(self, milliseconds, surface): super(CollidableObj, self).draw(milliseconds, surface)
Render the bounds of this collision ojbect onto the specified surface.
365,879
def ticker_pitch(ax=None): ax, _ = __get_axes(ax=ax) ax.yaxis.set_major_formatter(FMT_MIDI_HZ)
Set the y-axis of the given axes to MIDI frequencies Parameters ---------- ax : matplotlib.pyplot.axes The axes handle to apply the ticker. By default, uses the current axes handle.
365,880
def store_image(cls, http_client, link_hash, src, config): image = cls.read_localfile(link_hash, src, config) if image: return image if src.startswith(): image = cls.write_localfile_base64(link_hash, src, config) return im...
\ Writes an image src http string to disk as a temporary file and returns the LocallyStoredImage object that has the info you should need on the image
365,881
def send(self, template, email, _vars=None, options=None, schedule_time=None, limit=None): _vars = _vars or {} options = options or {} data = {: template, : email, : _vars, : options.copy()} if limit: data[] = limit.cop...
Remotely send an email template to a single email address. http://docs.sailthru.com/api/send @param template: template string @param email: Email value @param _vars: a key/value hash of the replacement vars to use in the send. Each var may be referenced as {varname} within the template i...
365,882
def heal(self, channel=0, method="linear", fill_value=np.nan, verbose=True): warnings.warn("heal", category=wt_exceptions.EntireDatasetInMemoryWarning) timer = wt_kit.Timer(verbose=False) with timer: if isinstance(channel, int): channel_index = c...
Remove nans from channel using interpolation. Parameters ---------- channel : int or str (optional) Channel to heal. Default is 0. method : {'linear', 'nearest', 'cubic'} (optional) The interpolation method. Note that cubic interpolation is only possi...
365,883
def session_commit(self, session): self.logger.debug("skipped - session_commit") return self.logger.debug("%s - session_commit" % session.meepo_unique_id) self._session_pub(session) signal("session_commit").send(session) self._session_d...
Send session_commit signal in sqlalchemy ``before_commit``. This marks the success of session so the session may enter commit state.
365,884
def cli(env, identifier, postinstall, key, image): vsi = SoftLayer.VSManager(env.client) vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, ) keys = [] if key: for single_key in key: resolver = SoftLayer.SshKeyManager(env.client).resolve_ids key_id = helpers.re...
Reload operating system on a virtual server.
365,885
def send_email(self, **kwargs): endpoint = self.messages_endpoint data = { : kwargs.pop(, False), : kwargs.pop(, ), : kwargs.pop(, self.api_key), } if not data.get(, None): raise ValueError() if kwargs....
Sends an email using Mandrill's API. Returns a Requests :class:`Response` object. At a minimum kwargs must contain the keys to, from_email, and text. Everything passed as kwargs except for the keywords 'key', 'async', and 'ip_pool' will be sent as key-value pairs in the message object. ...
365,886
def _canBeExpanded( self, headVerbRoot, headVerbWID, suitableNomAdvExpansions, expansionVerbs, widToToken ): nom/adv if len(suitableNomAdvExpansions)==1 and expansionVerbs: suitableExpansionVerbs = \ [expVerb for expVerb in expansion...
Teeb kindlaks, kas kontekst on verbiahela laiendamiseks piisavalt selge/yhene: 1) Nii 'nom/adv' kandidaate kui ka Vinf kandidaate on tรคpselt รผks; 2) Nom/adv ei kuulu mingi suurema fraasi kooseisu (meetodi _isLikelyNotPhrase() abil); Kui tingimused tรคidetud, tagastab lisatava v...
365,887
def mmols(self): mmols_dict = {} mmol_dir = os.path.join(self.parent_dir, ) if not os.path.exists(mmol_dir): os.makedirs(mmol_dir) mmol_file_names = [.format(self.code, i) for i in range(1, self.number_of_mmols + 1)] mmol_files = [os.path.join(mmol_dir, x) fo...
Dict of filepaths for all mmol files associated with code. Notes ----- Downloads mmol files if not already present. Returns ------- mmols_dict : dict, or None. Keys : int mmol number Values : str Filepath for the c...
365,888
def constant_image_value(image, crs=, scale=1): return getinfo(ee.Image(image).reduceRegion( reducer=ee.Reducer.first(), scale=scale, geometry=ee.Geometry.Rectangle([0, 0, 10, 10], crs, False)))
Extract the output value from a calculation done with constant images
365,889
def get_auth_stdin(refresh_token_filename, manual_login=False): refresh_token_cache = RefreshTokenCache(refresh_token_filename) return get_auth( CredentialsPrompt(), refresh_token_cache, manual_login=manual_login )
Simple wrapper for :func:`get_auth` that prompts the user using stdin. Args: refresh_token_filename (str): Path to file where refresh token will be cached. manual_login (bool): If true, prompt user to log in through a browser and enter authorization code manually. Defaults t...
365,890
def _set_uplink_switch(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=uplink_switch.uplink_switch, is_container=, presence=False, yang_name="uplink-switch", rest_name="uplink-switch", parent=self, path_helper=self._path_helper, extmethods=self._extme...
Setter method for uplink_switch, mapped from YANG variable /uplink_switch (container) If this variable is read-only (config: false) in the source YANG file, then _set_uplink_switch is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_uplink_...
365,891
def remove(self, name, func): was_empty = self._empty() if name in self.hooks and func in self.hooks[name]: self.hooks[name].remove(func) if self.app and not was_empty and self._empty(): self.app.reset()
Remove a callback from a hook.
365,892
def get_slice_location(dcmdata, teil=None): slice_location = None if hasattr(dcmdata, ): try: slice_location = float(dcmdata.SliceLocation) except Exception as exc: logger.info("It is not possible to use SliceLocation") logger.debug(trac...
get location of the slice :param dcmdata: dicom data structure :param teil: filename. Used when slice location doesnt exist :return:
365,893
def set_helper(self, helper):
.. todo:: Document this.
365,894
def copy(self, parent=None): new = Structure(None, parent=parent) new.key = self.key new.type_ = self.type_ new.val_guaranteed = self.val_guaranteed new.key_guaranteed = self.key_guaranteed for child in self.children: new.children.append(child.copy(ne...
Copies an existing structure and all of it's children
365,895
def resolve_sound(self, sound): sound = sound if isinstance(sound, Sound) else self.system[sound] if sound.name in self.data: return .join([x[] for x in self.data[sound.name]]) raise KeyError(":td:resolve_sound: No sound could be found.")
Function tries to identify a sound in the data. Notes ----- The function tries to resolve sounds to take a sound with less complex features in order to yield the next approximate sound class, if the transcription data are sound classes.
365,896
def data_interp(self, i, currenttime): if self.active.value is True: while self.get_data.value is True: logger.debug("Waiting for DataController to release cache file so I can read from it...") timer.sleep(2) pass if self.need_data(i+...
Method to streamline request for data from cache, Uses linear interpolation bewtween timesteps to get u,v,w,temp,salt
365,897
def expose_event(self, widget, event): x, y, width, height = event.area self.logger.debug("surface is %s" % self.surface) if self.surface is not None: win = widget.get_window() cr = win.cairo_create() cr.rectangle(x, y, width, height) ...
When an area of the window is exposed, we just copy out of the server-side, off-screen surface to that area.
365,898
def linestyle(i,a=5,b=3): lines=[,,,] points=[,,,,,,,,,,,,,,,,,] colors=[,,,,,] ls_string = colors[sc.mod(i,6)]+lines[sc.mod(i,4)]+points[sc.mod(i,18)] mark_i = a+sc.mod(i,b) return ls_string,int(mark_i)
provide one out of 25 unique combinations of style, color and mark use in combination with markevery=a+mod(i,b) to add spaced points, here a would be the base spacing that would depend on the data density, modulated with the number of lines to be plotted (b) Parameters ---------- i : integer ...
365,899
def condor_submit(cmd): is_running = subprocess.call(, shell=True) == 0 if not is_running: raise CalledProcessError() sub_cmd = \ + cmd.split()[0] + log.info( + sub_cmd) return subprocess.call(sub_cmd + + cmd, shell=True)
Submits cmd to HTCondor queue Parameters ---------- cmd: string Command to be submitted Returns ------- int returncode value from calling the submission command.