Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
363,700
def find_classes(self, name=".*", no_external=False): for cname, c in self.classes.items(): if no_external and isinstance(c.get_vm_class(), ExternalClass): continue if re.match(name, cname): yield c
Find classes by name, using regular expression This method will return all ClassAnalysis Object that match the name of the class. :param name: regular expression for class name (default ".*") :param no_external: Remove external classes from the output (default False) :rtype: gen...
363,701
def _ss_matrices(self,beta): T = np.identity(self.state_no) Z = self.X R = np.identity(self.state_no) Q = np.identity(self.state_no) for i in range(0,self.state_no): Q[i][i] = self.latent_variables.z_list[i].prior.transform(beta[i]) r...
Creates the state space matrices required Parameters ---------- beta : np.array Contains untransformed starting values for latent variables Returns ---------- T, Z, R, Q : np.array State space matrices used in KFS algorithm
363,702
def linearRegressionAnalysis(series): n = safeLen(series) sumI = sum([i for i, v in enumerate(series) if v is not None]) sumV = sum([v for i, v in enumerate(series) if v is not None]) sumII = sum([i * i for i, v in enumerate(series) if v is not None]) sumIV = sum([i * v for i, v in enumerate(se...
Returns factor and offset of linear regression function by least squares method.
363,703
def select_elements(self, json_string, expr): load_input_json = self.string_to_json(json_string) match = jsonselect.match(sel=expr, obj=load_input_json) ret = list(match) return ret if ret else None
Return list of elements from _json_string_, matching [ http://jsonselect.org/ | JSONSelect] expression. *DEPRECATED* JSON Select query language is outdated and not supported any more. Use other keywords of this library to query JSON. *Args:*\n _json_string_ - JSON string;\n _ex...
363,704
def to_dict(dictish): if hasattr(dictish, ): m = dictish.iterkeys elif hasattr(dictish, ): m = dictish.keys else: raise ValueError(dictish) return dict((k, dictish[k]) for k in m())
Given something that closely resembles a dictionary, we attempt to coerce it into a propery dictionary.
363,705
def depth_soil_density(self, value=None): if value is not None: try: value = float(value) except ValueError: raise ValueError( .format(value)) self._depth_soil_density = value
Corresponds to IDD Field `depth_soil_density` Args: value (float): value for IDD Field `depth_soil_density` Unit: kg/m3 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ...
363,706
def multi_char_literal(chars): num = 0 for index, char in enumerate(chars): shift = (len(chars) - index - 1) * 8 num |= ord(char) << shift return num
Emulates character integer literals in C. Given a string "abc", returns the value of the C single-quoted literal 'abc'.
363,707
def processIqRegistry(self, entity): if entity.getTag() == "iq": iq_id = entity.getId() if iq_id in self.iqRegistry: originalIq, successClbk, errorClbk = self.iqRegistry[iq_id] del self.iqRegistry[iq_id] if entity.getType() == IqP...
:type entity: IqProtocolEntity
363,708
def get_response(cmd, conn): resp = conn.socket().makefile(, -1) resp_dict = dict( code=0, message=, isspam=False, score=0.0, basescore=0.0, report=[], symbols=[], headers={}, ) if cmd == : resp_dict[] = False resp_dic...
Return a response
363,709
def parker_weighting(ray_trafo, q=0.25): src_radius = ray_trafo.geometry.src_radius det_radius = ray_trafo.geometry.det_radius ndim = ray_trafo.geometry.ndim angles = ray_trafo.range.meshgrid[0] min_rot_angle = ray_trafo.geometry.motion_partition.min_pt alen = ray_trafo.geometry....
Create parker weighting for a `RayTransform`. Parker weighting is a weighting function that ensures that oversampled fan/cone beam data are weighted such that each line has unit weight. It is useful in analytic reconstruction methods such as FBP to give a more accurate result and can improve convergenc...
363,710
def _parse_error(self, error): error = str(error) m = re.match(r, error) if m: return int(m.group(2)), m.group(3) m = re.match(r, error) if m: return int(m.group(2)), m.group(3) m = re....
Parses a single GLSL error and extracts the linenr and description Other GLIR implementations may omit this.
363,711
def main() -> None: if not in globals(): print("Run and then rerun this script") return if len(sys.argv) != 2: print("Usage: {} <output_file>".format(os.path.basename(sys.argv[0]))) return outfile_path = os.path.expanduser(sys.argv[1]) try: ...
Main function of this script
363,712
def off(self, evnt, func): foo funcs = self._syn_funcs.get(evnt) if funcs is None: return try: funcs.remove(func) except ValueError: pass
Remove a previously registered event handler function. Example: base.off( 'foo', onFooFunc )
363,713
def models(cls, api_version=DEFAULT_API_VERSION): if api_version == : from .v2017_07_01 import models return models elif api_version == : from .v2018_03_31 import models return models elif api_version == : from .v2018_08_01_pre...
Module depends on the API version: * 2017-07-01: :mod:`v2017_07_01.models<azure.mgmt.containerservice.v2017_07_01.models>` * 2018-03-31: :mod:`v2018_03_31.models<azure.mgmt.containerservice.v2018_03_31.models>` * 2018-08-01-preview: :mod:`v2018_08_01_preview.models<azure.mgmt.container...
363,714
def read_all(self): result = self._data[self._position:] self._position = None return result
Read all remaining data in the packet. (Subsequent read() will return errors.)
363,715
def compute_route_stats_base( trip_stats_subset: DataFrame, headway_start_time: str = "07:00:00", headway_end_time: str = "19:00:00", *, split_directions: bool = False, ) -> DataFrame: if trip_stats_subset.empty: return pd.DataFrame() f = trip_stats_subset.copy() f[["s...
Compute stats for the given subset of trips stats. Parameters ---------- trip_stats_subset : DataFrame Subset of the output of :func:`.trips.compute_trip_stats` split_directions : boolean If ``True``, then separate the stats by trip direction (0 or 1); otherwise aggregate trips ...
363,716
def decode_escapes(s): def decode_match(match): return codecs.decode(match.group(0), ) return ESCAPE_SEQUENCE_RE.sub(decode_match, s)
Unescape libconfig string literals
363,717
def calculate_check_interval( self, max_interval, ewma_factor, max_days=None, max_updates=None, ewma=0, ewma_ts=None, add_partial=None ): if not add_partial: posts_base = self.posts.only().order_by() if ewma_ts: posts_base = posts_base.filter(date_modified__gt=ewma_ts) posts = posts_base if ma...
Calculate interval for checks as average time (ewma) between updates for specified period.
363,718
def create(self, name, *args, **kwargs): try: return super(ImageMemberManager, self).create(name, *args, **kwargs) except Exception as e: if e.http_status == 403: raise exc.UnsharableImage("You cannot share a public image.") else: ...
Need to wrap the default call to handle exceptions.
363,719
def create_thing(self, lid): evt = self.create_thing_async(lid) self._wait_and_except_if_failed(evt) try: with self.__new_things: return self.__new_things.pop(lid) except KeyError as ex: raise raise_from(IOTClientError( % lid), ex)
Create a new Thing with a local id (lid). Returns a [Thing](Thing.m.html#IoticAgent.IOT.Thing.Thing) object if successful or if the Thing already exists Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects...
363,720
def from_text(text): m = Message() reader = _TextReader(text, m) reader.read() return m
Convert the text format message into a message object. @param text: The text format message. @type text: string @raises UnknownHeaderField: @raises dns.exception.SyntaxError: @rtype: dns.message.Message object
363,721
def check_bom(file): lead = file.read(3) if len(lead) == 3 and lead == codecs.BOM_UTF8: return codecs.lookup().name elif len(lead) >= 2 and lead[:2] == codecs.BOM_UTF16_BE: if len(lead) == 3: file.seek(-1, os.SEEK_CUR) return codecs.lookup().n...
Determines file codec from from its BOM record. If file starts with BOM record encoded with UTF-8 or UTF-16(BE/LE) then corresponding encoding name is returned, otherwise None is returned. In both cases file current position is set to after-BOM bytes. The file must be open in binary mode and positioned...
363,722
def valid(): * m_data = __salt__[](, {}) m_data[func].pop(0) if not _mine_function_available(mine_func): continue data[func] = {mine_func: m_data[func]} else: if not _mine_function_available(func): continue ...
List valid entries in mine configuration. CLI Example: .. code-block:: bash salt '*' mine.valid
363,723
def commits(self): return CommitsDataFrame(self._engine_dataframe.getCommits(), self._session, self._implicits)
Returns the current DataFrame joined with the commits DataFrame. It just returns the last commit in a reference (aka the current state). >>> commits_df = refs_df.commits If you want all commits from the references, use the `all_reference_commits` method, but take into account that gett...
363,724
def make_matepairs(fastafile): assert op.exists(fastafile) matefile = fastafile.rsplit(".", 1)[0] + ".mates" if op.exists(matefile): logging.debug("matepairs file `{0}` found".format(matefile)) else: logging.debug("parsing matepairs from `{0}`".format(fastafile)) matefw = o...
Assumes the mates are adjacent sequence records
363,725
def elapsed_time(self): td = (datetime.datetime.now() - self.start_time) sec = td.seconds ms = int(td.microseconds / 1000) return .format(sec % 3600 // 60, sec % 60, ms)
Return elapsed time as min:sec:ms. The .split separates out the millisecond
363,726
def read(self, size): now = time.time() missing_dt = self._sleep_until - now if missing_dt > 0: time.sleep(missing_dt) self._sleep_until = time.time() + self._sleep_time(size) data = (self._wavep.readframes(size) if self._wavep ...
Read bytes from the stream and block until sample rate is achieved. Args: size: number of bytes to read from the stream.
363,727
def url_replace_param(url, name, value): url_components = urlparse(force_str(url)) query_params = parse_qs(url_components.query) query_params[name] = value query = urlencode(query_params, doseq=True) return force_text( urlunparse( [ url_components.scheme, ...
Replace a GET parameter in an URL
363,728
def run_per_switch_cmds(self, switch_cmds): for switch_ip, cmds in switch_cmds.items(): switch = self._switches.get(switch_ip) self.run_openstack_sg_cmds(cmds, switch)
Applies cmds to appropriate switches This takes in a switch->cmds mapping and runs only the set of cmds specified for a switch on that switch. This helper is used for applying/removing ACLs to/from interfaces as this config will vary from switch to switch.
363,729
def _send_size(self): " Report terminal size to server. " rows, cols = _get_size(sys.stdout.fileno()) self._send_packet({ : , : [rows, cols] })
Report terminal size to server.
363,730
def getReffs(self, textId, level=1, subreference=None): text = CtsText( urn=textId, retriever=self.endpoint ) return text.getReffs(level, subreference)
Retrieve the siblings of a textual node :param textId: CtsTextMetadata Identifier :type textId: str :param level: Depth for retrieval :type level: int :param subreference: CapitainsCtsPassage Reference :type subreference: str :return: List of references :...
363,731
def integer_ceil(a, b): quanta, mod = divmod(a, b) if mod: quanta += 1 return quanta
Return the ceil integer of a div b.
363,732
def _help_basic(self): help = % (color.Yellow) help += % (color.Green) help += % (color.LightBlue) help += % (color.Yellow) help += % (color.Green) help += view\ % (color.LightBlue, color.Normal) return help
Help for Workbench Basics
363,733
def _republish_dropped_message(self, reason): self.logger.debug() properties = dict(self._message.properties) or {} if not in properties or not properties[]: properties[] = {} properties[][] = self.name properties[][] = reason properties[][] = \ ...
Republish the original message that was received it is being dropped by the consumer. This for internal use and should not be extended or used directly. :param str reason: The reason the message was dropped
363,734
def convert_episode_to_batch_major(episode): episode_batch = {} for key in episode.keys(): val = np.array(episode[key]).copy() episode_batch[key] = val.swapaxes(0, 1) return episode_batch
Converts an episode to have the batch dimension in the major (first) dimension.
363,735
def rotate_crop(centerij, sz, angle, img=None, mode=, **kwargs): from skimage import transform sz = np.array(sz) crop_half = int(np.ceil(np.sqrt(np.square(sz).sum()))) if centerij[0] >= crop_half or centerij[1] >= crop_half: raise NotImplementedError slicei = slice(centerij[...
rotate and crop if no img, then return crop function :param centerij: :param sz: :param angle: :param img: [h,w,d] :param mode: padding option :return: cropped image or function
363,736
def lookup_string(self, keysym): s = self.keysym_translations.get(keysym) if s is not None: return s import Xlib.XK return Xlib.XK.keysym_to_string(keysym)
Return a string corresponding to KEYSYM, or None if no reasonable translation is found.
363,737
def set_executing(on: bool): my_thread = threading.current_thread() if isinstance(my_thread, threads.CauldronThread): my_thread.is_executing = on
Toggle whether or not the current thread is executing a step file. This will only apply when the current thread is a CauldronThread. This function has no effect when run on a Main thread. :param on: Whether or not the thread should be annotated as executing a step file.
363,738
def create(cls, *args, **kwargs) -> : logger.debug( f) model_cls = repo_factory.get_model(cls) repository = repo_factory.get_repository(cls) try: entity = cls(*args, **kwargs) entity._validate_unique()...
Create a new record in the repository. Also performs unique validations before creating the entity :param args: positional arguments for the entity :param kwargs: keyword arguments for the entity
363,739
def get_config(self, budget): self.logger.debug() sample = None info_dict = {} if len(self.kde_models.keys()) == 0 or np.random.rand() < self.random_fraction: sample = self.configspace.sample_configuration() info_dict[] = False best = np.inf best_vector = None if sample is None...
Function to sample a new configuration This function is called inside Hyperband to query a new configuration Parameters: ----------- budget: float the budget for which this configuration is scheduled returns: config should return a valid configuration
363,740
def find_program(basename): names = [basename] if os.name == : extensions = (, , ) if not basename.endswith(extensions): names = [basename+ext for ext in extensions]+[basename] for name in names: path = is_program_installed(name) if path: ...
Find program in PATH and return absolute path Try adding .exe or .bat to basename on Windows platforms (return None if not found)
363,741
def _make_subvolume(self, **args): from imagemounter.volume import Volume v = Volume(disk=self.disk, parent=self.parent, volume_detector=self.volume_detector, **args) self.volumes.append(v) return v
Creates a subvolume, adds it to this class and returns it.
363,742
def resolve(cls, all_known_repos, name): match = None for repo in all_known_repos: if repo.remote_path == name: return repo if name == repo.short_name: if match is None: match = repo else: ...
We require the list of all remote repo paths to be passed in to this because otherwise we would need to import the spec assembler in this module, which would give us circular imports.
363,743
def finish_displayhook(self): io.stdout.write(self.shell.separate_out2) io.stdout.flush()
Finish up all displayhook activities.
363,744
def get_cache_mode(service, pool_name): validator(value=service, valid_type=six.string_types) validator(value=pool_name, valid_type=six.string_types) out = check_output([, , service, , , ]) if six.PY3: out = out.decode() try: osd_json = json.loads(out) ...
Find the current caching mode of the pool_name given. :param service: six.string_types. The Ceph user name to run the command under :param pool_name: six.string_types :return: int or None
363,745
def mnist_tutorial_cw(train_start=0, train_end=60000, test_start=0, test_end=10000, viz_enabled=VIZ_ENABLED, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, source_samples=SOURCE_SAMPLES, learning_rate=LEARNING_RATE, ...
MNIST tutorial for Carlini and Wagner's attack :param train_start: index of first training set example :param train_end: index of last training set example :param test_start: index of first test set example :param test_end: index of last test set example :param viz_enabled: (boolean) activate plots of adversa...
363,746
def create(gandi, resource, flags, algorithm, public_key): result = gandi.dnssec.create(resource, flags, algorithm, public_key) return result
Create DNSSEC key.
363,747
def _get_front_idxs_from_id(fronts, id): if id == -1: freq_idxs = np.arange(fronts.shape[0], dtype=np.int64) sample_idxs = np.ones(len(freq_idxs), dtype=np.int64) * (fronts.shape[1] - 1) else: freq_idxs, sample_idxs = np.where(fronts == id) return [(f, i) for f...
Return a list of tuples of the form (frequency_idx, sample_idx), corresponding to all the indexes of the given front.
363,748
def main(self): self._setup_task_manager() self._setup_source_and_destination() self.task_manager.blocking_start(waiting_func=self.waiting_func) self.close() self.config.logger.info()
this main routine sets up the signal handlers, the source and destination crashstorage systems at the theaded task manager. That starts a flock of threads that are ready to shepherd crashes from the source to the destination.
363,749
def p_bound_segments(self, p): p[0] = p[1] if len(p) > 2: p[0].extend(p[3])
bound_segments : bound_segment FORWARD_SLASH bound_segments | bound_segment
363,750
def complete_token_filtered(aliases, prefix, expanded): complete_ary = aliases.keys() return [cmd for cmd in complete_ary if cmd.startswith(prefix)]
Find all starting matches in dictionary *aliases* that start with *prefix*, but filter out any matches already in *expanded*
363,751
def patch(self, request): attrs = (, ) missing = [attr for attr in attrs if attr not in request.data] if missing: return Response( status=status.HTTP_400_BAD_REQUEST, data={: u.format(missing=.join(missing))} ) edx_video_i...
Update the status of a video.
363,752
def _validate_edata(self, edata): if edata is None: return True if not (isinstance(edata, dict) or _isiterable(edata)): return False edata = [edata] if isinstance(edata, dict) else edata for edict in edata: if (not isinstance(edict, d...
Validate edata argument of raise_exception_if method.
363,753
def major(self, major: int) -> None: self.filter_negatives(major) self._major = major
param major Major version number property. Must be a non-negative integer.
363,754
def configure_extensions(app): db.init_app(app) app.wsgi_app = ProxyFix(app.wsgi_app) assets.init_app(app) for asset in bundles: for (name, bundle) in asset.iteritems(): assets.register(name, bundle) login_manager.login_view = login_manager.login_message_category = ...
Configure application extensions
363,755
def _update_marshallers(self): self._marshallers = [] for v in self._priority: if v == : self._marshallers.extend(self._builtin_marshallers) elif v == : self._marshallers.extend(self._plugin_marshallers) elif v == : ...
Update the full marshaller list and other data structures. Makes a full list of both builtin and user marshallers and rebuilds internal data structures used for looking up which marshaller to use for reading/writing Python objects to/from file. Also checks for whether the requi...
363,756
def get_json(self, layer, where="1 = 1", fields=[], count_only=False, srid=): params = { : where, : ", ".join(fields), : True, : srid, : "pjson", : self.object_id_field, : count_only ...
Gets the JSON file from ArcGIS
363,757
def tag_arxiv(line): def tagger(match): groups = match.groupdict() if match.group(): groups[] = + groups[] else: groups[] = return u\ u \ u % groups line = re_arxiv_5digits.sub(tagger, line) line = re_arxiv.sub(tagger, l...
Tag arxiv report numbers We handle arXiv in 2 ways: * starting with arXiv:1022.1111 * this format exactly 9999.9999 We also format the output to the standard arxiv notation: * arXiv:2007.12.1111 * arXiv:2007.12.1111v2
363,758
def get_datasets_in_nodes(): data_dir = os.path.join(scriptdir, "..", "usgs", "data") cwic = map(lambda d: d["datasetName"], api.datasets(None, CWIC_LSI_EXPLORER_CATALOG_NODE)[]) ee = map(lambda d: d["datasetName"], api.datasets(None, EARTH_EXPLORER_CATALOG_NODE)[]) hdds = map(lambda d: d["datase...
Get the node associated with each dataset. Some datasets will have an ambiguous node since they exists in more than one node.
363,759
def _analyze(self): for parsed_line in self.parsed_lines: if in parsed_line: if parsed_line[] in self.filter[]: self.noisy_logs.append(parsed_line) else: self.quiet_logs.append(parsed_line) else: ...
Apply the filter to the log file
363,760
def contains_pt(self, pt): obj1, obj2 = self.objects return obj2.contains_pt(pt) and np.logical_not(obj1.contains_pt(pt))
Containment test.
363,761
def setattrs_from_paxos(self, paxos): changes = {} for name in self.paxos_variables: paxos_value = getattr(paxos, name) if paxos_value != getattr(self, name, None): self.print_if_verbose("{} {}: {}".format(self.network_uid, name, paxos_value)) ...
Registers changes of attribute value on Paxos instance.
363,762
def _iter_step_func_decorators(self): for node in self.py_tree.find_all(): for decorator in node.decorators: if decorator.name.value == : yield node, decorator break
Find functions with step decorator in parsed file.
363,763
def decode_bytes(byt, enc=): try: strg = byt.decode(enc) except UnicodeDecodeError as err: strg = "Unable to decode message:\n{}\n{}".format(str(byt), err) except (AttributeError, UnicodeEncodeError): return byt return strg
Given a string or bytes input, return a string. Args: bytes - bytes or string enc - encoding to use for decoding the byte string.
363,764
def tab_complete(self): opts = self._complete_options() if len(opts) == 1: self.set_current_text(opts[0] + os.sep) self.hide_completer()
If there is a single option available one tab completes the option.
363,765
def _advapi32_verify(certificate_or_public_key, signature, data, hash_algorithm, rsa_pss_padding=False): algo = certificate_or_public_key.algorithm if algo == and rsa_pss_padding: hash_length = { : 20, : 28, : 32, : 48, : 64 }.g...
Verifies an RSA, DSA or ECDSA signature via CryptoAPI :param certificate_or_public_key: A Certificate or PublicKey instance to verify the signature with :param signature: A byte string of the signature to verify :param data: A byte string of the data the signature is for :par...
363,766
def figure(path,display=False,close=True): return Figure(path,display=display,close=close)
Can be used with the **with** statement:: import litus import numpy as np import matplotlib.pylab as plt x = np.arange(0,10,0.1) with litus.figure("some_test.png") as f: plt.plot(x,np.cos(x)) # plots to a first plot with litus.figure("some_other_test.p...
363,767
def secure(func_or_obj, check_permissions_for_obj=None): if _allowed_check_permissions_types(func_or_obj): return _secure_method(func_or_obj) else: if not _allowed_check_permissions_types(check_permissions_for_obj): msg = "When securing an object, secure() requires the " + \ ...
This method secures a method or class depending on invocation. To decorate a method use one argument: @secure(<check_permissions_method>) To secure a class, invoke with two arguments: secure(<obj instance>, <check_permissions_method>)
363,768
def general_settings(): import matplotlib as mpl import matplotlib.pyplot as plt mpl.rcParams[] = 7.0 mpl.rcParams[] = 7.0 mpl.rcParams[] = 7.0 mpl.rcParams[] = 7.0 mpl.rcParams["lines.linewidth"] = 1.5 mpl.rcParams["lines.markeredgewidth"] = 3.0 mpl.rcParams["lines.markersize"]...
general settings
363,769
def _commit_change(alias_table, export_path=None, post_commit=True): with open(export_path or GLOBAL_ALIAS_PATH, ) as alias_config_file: alias_table.write(alias_config_file) if post_commit: alias_config_file.seek(0) alias_config_hash = hashlib.sha1(alias_config_file.read...
Record changes to the alias table. Also write new alias config hash and collided alias, if any. Args: alias_table: The alias table to commit. export_path: The path to export the aliases to. Default: GLOBAL_ALIAS_PATH. post_commit: True if we want to perform some extra actions after writ...
363,770
def create_token(self, user_id, permission_obj): headers = { : self.user_agent(), : self.content_type() } headers.update(self.headers()) url = self.portals_url()+.format(user_id) r = requests.post( url, ...
'permission_obj' param should be a string. e.g. '[{"access":"d_u_list","oid":{"id":"1576946496","type":"Domain"}}]' http://docs.exosite.com/portals/#add-user-permission
363,771
def has_pfn(self, url, site=None): curr_pfn = dax.PFN(url, site) return self.hasPFN(curr_pfn)
Wrapper of the pegasus hasPFN function, that allows it to be called outside of specific pegasus functions.
363,772
def simple_value(self, elt, ps, mixed=False): if not _valid_encoding(elt): raise EvaluateException(, ps.Backtrace(elt)) c = _children(elt) if mixed is False: if len(c) == 0: raise EvaluateException(, ps.Backtrace(elt)) for c_elt in c: ...
Get the value of the simple content of this element. Parameters: elt -- the DOM element being parsed ps -- the ParsedSoap object. mixed -- ignore element content, optional text node
363,773
def add_one(self, url: str, url_properties: Optional[URLProperties]=None, url_data: Optional[URLData]=None): self.add_many([AddURLInfo(url, url_properties, url_data)])
Add a single URL to the table. Args: url: The URL to be added url_properties: Additional values to be saved url_data: Additional data to be saved
363,774
def plot_prob_profit_trade(round_trips, ax=None): x = np.linspace(0, 1., 500) round_trips[] = round_trips.pnl > 0 dist = sp.stats.beta(round_trips.profitable.sum(), (~round_trips.profitable).sum()) y = dist.pdf(x) lower_perc = dist.ppf(.025) upper_perc = dist.ppf...
Plots a probability distribution for the event of making a profitable trade. Parameters ---------- round_trips : pd.DataFrame DataFrame with one row per round trip trade. - See full explanation in round_trips.extract_round_trips ax : matplotlib.Axes, optional Axes upon which...
363,775
def is_prev_free(self): flag = self.state.memory.load(self.base + self._chunk_size_t_size, self._chunk_size_t_size) & CHUNK_P_MASK def sym_flag_handler(flag): l.warning("A chunk's P flag is symbolic; assuming it is not set") return self.state.solver.min_int(flag) ...
Returns a concrete state of the flag indicating whether the previous chunk is free or not. Issues a warning if that flag is symbolic and has multiple solutions, and then assumes that the previous chunk is free. :returns: True if the previous chunk is free; False otherwise
363,776
def transform(self, data, test=False): if not type(data) == Variable: if len(data.shape) < 4: data = data[np.newaxis] if len(data.shape) != 4: raise TypeError("Invalid dimensions for image data. Dim = %s.\ Must be 4d ...
Transform image data to latent space. Parameters ---------- data : array-like shape (n_images, image_width, image_height, n_colors) Input numpy array of images. test [optional] : bool Controls the test boolean for batch normaliz...
363,777
def sort_values( self, by, axis=0, ascending=True, inplace=False, kind="quicksort", na_position="last", ): axis = self._get_axis_number(axis) if not is_list_like(by): by = [by] if axis...
Sorts by a column/row or list of columns/rows. Args: by: A list of labels for the axis to sort over. axis: The axis to sort. ascending: Sort in ascending or descending order. inplace: If true, do the operation inplace. kind: How to sort. ...
363,778
def parse(self, args): if args is None: args = self._default_args if isinstance(args, six.string_types): args = shlex.split(args) return args
:param args: arguments :type args: None or string or list of string :return: formatted arguments if specified else ``self.default_args`` :rtype: list of string
363,779
def escape(self, text): return self.__escapable.sub(self.__escape, compat.text_type(text) ).encode()
Replace characters with their character references. Replace characters by their named entity references. Non-ASCII characters, if they do not have a named entity reference, are replaced by numerical character references. The return value is guaranteed to be ASCII.
363,780
def close_session(self): with self._graph.as_default(): self._sess.close() self._sess = None
Close tensorflow session. Exposes for memory management.
363,781
def targetwords(self, index, targetwords, alignment): return [ targetwords[x] for x in alignment[index] ]
Return the aligned targetwords for a specified index in the source words
363,782
def deploy(self): if not os.path.exists(self.path): makedirs(self.path) link(self.vault_path, self.real_path)
Creates a link at the original path of this target
363,783
def intersection_box(box1, box2): b1_x2, b1_y2 = box1.bottom_right() b2_x2, b2_y2 = box2.bottom_right() x, y = max(box1.x, box2.x), max(box1.y, box2.y) x2, y2 = min(b1_x2, b2_x2), min(b1_y2, b2_y2) w, h = max(0, x2-x), max(0, y2-y) return Box(x, y, w, h)
Finds an intersection box that is common to both given boxes. :param box1: Box object 1 :param box2: Box object 2 :return: None if there is no intersection otherwise the new Box
363,784
def ensure_parent_dir_exists(file_path): parent = os.path.dirname(file_path) if parent: os.makedirs(parent, exist_ok=True)
Ensures that the parent directory exists
363,785
def ping_entry(self, entry): entry_url = % (self.ressources.site_url, entry.get_absolute_url()) categories = .join([c.title for c in entry.categories.all()]) try: reply = self.server.weblogUpdates.extendedPing( self.ressources....
Ping an entry to a directory.
363,786
def main() -> None: parser = ArgumentParser( description="Pauses and resumes a process by disk space; LINUX ONLY." ) parser.add_argument( "process_id", type=int, help="Process ID." ) parser.add_argument( "--path", required=True, help="Path to check free s...
Command-line handler for the ``pause_process_by_disk_space`` tool. Use the ``--help`` option for help.
363,787
def get_auth_token(self, user): data = [str(user.id), self.security.hashing_context.hash(encode_string(user._password))] return self.security.remember_token_serializer.dumps(data)
Returns the user's authentication token.
363,788
def register_actions(self, shortcut_manager): self.add_callback_to_shortcut_manager(, partial(self.call_action_callback, "on_save_activate")) self.add_callback_to_shortcut_manager(, partial(self.call_action_callback, "on_save_as_activate")) self.add_callback_to_shortcut_manager(, partia...
Register callback methods for triggered actions :param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings between shortcuts and actions.
363,789
def decode(self, data, password): self.raw = gntp.shim.u(data) parts = self.raw.split() self.info = self._parse_info(self.raw) self._validate_password(password) self.headers = self._parse_dict(parts[0]) for i, part in enumerate(parts): if i == 0: continue if part.strip() == : continue ...
Decode existing GNTP Registration message :param string data: Message to decode
363,790
def _get_audio_object_type(self, r): audioObjectType = r.bits(5) if audioObjectType == 31: audioObjectTypeExt = r.bits(6) audioObjectType = 32 + audioObjectTypeExt return audioObjectType
Raises BitReaderError
363,791
def create(self, customer_name, street, city, region, postal_code, iso_country, friendly_name=values.unset, emergency_enabled=values.unset, auto_correct_address=values.unset): data = values.of({ : customer_name, : street, : city, ...
Create a new AddressInstance :param unicode customer_name: The name to associate with the new address :param unicode street: The number and street address of the new address :param unicode city: The city of the new address :param unicode region: The state or region of the new address ...
363,792
def get_all_network_interfaces(self, filters=None): params = {} if filters: self.build_filter_params(params, filters) return self.get_list(, params, [(, NetworkInterface)], verb=)
Retrieve all of the Elastic Network Interfaces (ENI's) associated with your account. :type filters: dict :param filters: Optional filters that can be used to limit the results returned. Filters are provided in the form of a dictionary consisting ...
363,793
def iter(self, columnnames, order=, sort=True): from .tableiter import tableiter return tableiter(self, columnnames, order, sort)
Return a tableiter object. :class:`tableiter` lets one iterate over a table by returning in each iteration step a reference table containing equal values for the given columns. By default a sort is done on the given columns to get the correct iteration order. `order` ...
363,794
def list_records_for_build_config_set(id, page_size=200, page_index=0, sort="", q=""): data = list_records_for_build_config_set_raw(id, page_size, page_index, sort, q) if data: return utils.format_json_list(data)
Get a list of BuildRecords for the given BuildConfigSetRecord
363,795
def install_agent(agent_key, agent_version=1): ** work_dir = os.path.join(__opts__[], ) if not os.path.isdir(work_dir): os.mkdir(work_dir) install_file = tempfile.NamedTemporaryFile(dir=work_dir, suffix=, ...
Function downloads Server Density installation agent, and installs sd-agent with agent_key. Optionally the agent_version would select the series to use (defaults on the v1 one). CLI Example: .. code-block:: bash salt '*' serverdensity_device.install_agent c2bbdd6689ff46282bdaa07555641498 ...
363,796
def police_priority_map_conform_map_pri7_conform(self, **kwargs): config = ET.Element("config") police_priority_map = ET.SubElement(config, "police-priority-map", xmlns="urn:brocade.com:mgmt:brocade-policer") name_key = ET.SubElement(police_priority_map, "name") name_key.text = ...
Auto Generated Code
363,797
def human2bytes(s): symbols = (, , , , , , , , ) letter = s[-1:].strip().upper() num = s[:-1] assert num.isdigit() and letter in symbols, s num = float(num) prefix = {symbols[0]: 1} for i, s in enumerate(symbols[1:]): prefix[s] = 1 << (i + 1) * 10 return int(num * prefix[let...
>>> human2bytes('1M') 1048576 >>> human2bytes('1G') 1073741824
363,798
def run(app=None, server=, host=, port=8080, interval=1, reloader=False, quiet=False, plugins=None, debug=None, **kargs): if NORUN: return if reloader and not os.environ.get(): import subprocess lockfile = None try: ...
Start a server instance. This method blocks until the server terminates. :param app: WSGI application or target string supported by :func:`load_app`. (default: :func:`default_app`) :param server: Server adapter to use. See :data:`server_names` keys for valid names or pass ...
363,799
def turn_physical_on(self,ro=None,vo=None): self._roSet= True self._voSet= True if not ro is None: self._ro= ro if not vo is None: self._vo= vo return None
NAME: turn_physical_on PURPOSE: turn on automatic returning of outputs in physical units INPUT: ro= reference distance (kpc) vo= reference velocity (km/s) OUTPUT: (none) HISTORY: 2016-01-19 - Written - Bovy (UofT)