code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def multiple_sources(stmt): '''Return True if statement is supported by multiple sources. Note: this is currently not used and replaced by BeliefEngine score cutoff ''' sources = list(set([e.source_api for e in stmt.evidence])) if len(sources) > 1: return True return False
Return True if statement is supported by multiple sources. Note: this is currently not used and replaced by BeliefEngine score cutoff
def add_identity(cls, db, identity, backend): """ Load and identity list from backend in Sorting Hat """ uuid = None try: uuid = api.add_identity(db, backend, identity['email'], identity['name'], identity['username']) logger.debug("Ne...
Load and identity list from backend in Sorting Hat
def publish(self, *args, **kwargs): ''' Publish a message. Will return the id of the message if publisher confirmations are enabled, else will return 0. ''' if self.channel.confirm._enabled: self._msg_id += 1 super(RabbitBasicClass, self).publish(*args, **kwar...
Publish a message. Will return the id of the message if publisher confirmations are enabled, else will return 0.
def set_logger(log_level, path, logger_name='giganews'): """Convenience function to quickly configure any level of logging to a file. :type log_level: int :param log_level: A log level as specified in the `logging` module :type path: string :param path: Path to the log file. The file will be c...
Convenience function to quickly configure any level of logging to a file. :type log_level: int :param log_level: A log level as specified in the `logging` module :type path: string :param path: Path to the log file. The file will be created if it doesn't already exist.
def assertNotCookie(self, name, value=None, attrs={}, *args, **kwargs): """ Negation of :meth:`assertCookie`. """ return not self.assertCookie(name, value, attrs)
Negation of :meth:`assertCookie`.
def write(self, filepath, skip_unknown=False): """Write the metadata fields to filepath.""" fp = codecs.open(filepath, 'w', encoding='utf-8') try: self.write_file(fp, skip_unknown) finally: fp.close()
Write the metadata fields to filepath.
def list_auth_methods(self): """List all enabled auth methods. Supported methods: GET: /sys/auth. Produces: 200 application/json :return: The JSON response of the request. :rtype: dict """ api_path = '/v1/sys/auth' response = self._adapter.get( ...
List all enabled auth methods. Supported methods: GET: /sys/auth. Produces: 200 application/json :return: The JSON response of the request. :rtype: dict
def digest(self): """Return final digest value. """ if self._digest is None: if self._buf: self._add_block(self._buf) self._buf = EMPTY ctx = self._blake2s(0, 1, True) for t in self._thread: ctx.update(t.digest()...
Return final digest value.
def dup(self, other=None, **kwds): '''Duplicate attributes of dict or other typedef. ''' if other is None: d = _dict_typedef.kwds() else: d = other.kwds() d.update(kwds) self.reset(**d)
Duplicate attributes of dict or other typedef.
def cli(env, identifier, passwords=False, price=False): """Get details for a virtual server.""" vsi = SoftLayer.VSManager(env.client) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' vs_id = helpers.resolve_id(vsi.resolve_ids, identifier,...
Get details for a virtual server.
def proximal(self): """Return the `proximal factory` of the functional. See Also -------- odl.solvers.nonsmooth.proximal_operators.proximal_convex_conj_l1 : `proximal factory` for the L1-norms convex conjugate. """ if self.pointwise_norm.exponent == np.inf: ...
Return the `proximal factory` of the functional. See Also -------- odl.solvers.nonsmooth.proximal_operators.proximal_convex_conj_l1 : `proximal factory` for the L1-norms convex conjugate.
def bookWS(symbols=None, on_data=None): '''https://iextrading.com/developer/docs/#book51''' symbols = _strToList(symbols) sendinit = ({'symbols': symbols, 'channels': ['book']},) return _stream(_wsURL('deep'), sendinit, on_data)
https://iextrading.com/developer/docs/#book51
def get_groupnames(self, sgs): """Get servicegroups list :return: comma separated list of servicegroups :rtype: str """ return ','.join([sgs[sg].get_name() for sg in self.servicegroups])
Get servicegroups list :return: comma separated list of servicegroups :rtype: str
def murnaghan( vol, e0, b0, bp, v0 ): """ Calculate the energy as a function of volume, using the Murnaghan equation of state [Murnaghan, Proc. Nat. Acad. Sci. 30, 244 (1944)] https://en.wikipedia.org/wiki/Murnaghan_equation_of_state cf. Fu and Ho, Phys. Rev. B 28, 5480 (1983). Args: vo...
Calculate the energy as a function of volume, using the Murnaghan equation of state [Murnaghan, Proc. Nat. Acad. Sci. 30, 244 (1944)] https://en.wikipedia.org/wiki/Murnaghan_equation_of_state cf. Fu and Ho, Phys. Rev. B 28, 5480 (1983). Args: vol (float): this volume. e0 (float): energ...
def intersection(self, catalogue, output_fh): """Returns `output_fh` populated with CSV results giving the intersection in n-grams of the witnesses of labelled sets of works in `catalogue`. :param catalogue: catalogue matching filenames to labels :type catalogue: `Catalogue` ...
Returns `output_fh` populated with CSV results giving the intersection in n-grams of the witnesses of labelled sets of works in `catalogue`. :param catalogue: catalogue matching filenames to labels :type catalogue: `Catalogue` :param output_fh: object to output results to ...
def term_with_coeff(term, coeff): """ Change the coefficient of a PauliTerm. :param PauliTerm term: A PauliTerm object :param Number coeff: The coefficient to set on the PauliTerm :returns: A new PauliTerm that duplicates term but sets coeff :rtype: PauliTerm """ if not isinstance(coeff...
Change the coefficient of a PauliTerm. :param PauliTerm term: A PauliTerm object :param Number coeff: The coefficient to set on the PauliTerm :returns: A new PauliTerm that duplicates term but sets coeff :rtype: PauliTerm
def _set_grace_period_memory(self, v, load=False): """ Setter method for grace_period_memory, mapped from YANG variable /rbridge_id/resource_monitor/memory/grace_period_memory (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_grace_period_memory is considered as a...
Setter method for grace_period_memory, mapped from YANG variable /rbridge_id/resource_monitor/memory/grace_period_memory (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_grace_period_memory is considered as a private method. Backends looking to populate this variable...
def process_tokens(words, normalize_plurals=True): """Normalize cases and remove plurals. Each word is represented by the most common case. If a word appears with an "s" on the end and without an "s" on the end, the version with "s" is assumed to be a plural and merged with the version without "s" ...
Normalize cases and remove plurals. Each word is represented by the most common case. If a word appears with an "s" on the end and without an "s" on the end, the version with "s" is assumed to be a plural and merged with the version without "s" (except if the word ends with "ss"). Parameters -...
def get_namespace(self, namespace, lowercase=True, trim_namespace=True): """Returns a dictionary containing a subset of configuration options that match the specified namespace/prefix. Example usage: app.config['IMAGE_STORE_TYPE']='fs' app.config['IMAGE_STORE_PATH']='/var/app...
Returns a dictionary containing a subset of configuration options that match the specified namespace/prefix. Example usage: app.config['IMAGE_STORE_TYPE']='fs' app.config['IMAGE_STORE_PATH']='/var/app/images' app.config['IMAGE_STORE_BASE_URL']='http://img.website.com' ...
def _generate_union_class_reflection_attributes(self, ns, data_type): """ Adds a class attribute for each union member assigned to a validator. Also adds an attribute that is a map from tag names to validators. """ class_name = fmt_class(data_type.name) for field in data...
Adds a class attribute for each union member assigned to a validator. Also adds an attribute that is a map from tag names to validators.
def all(self, func): """ :param func: :type func: (K, T) -> bool :rtype: bool Usage: >>> TDict(k1=1, k2=2, k3=3).all(lambda k, v: v > 0) True >>> TDict(k1=1, k2=2, k3=3).all(lambda k, v: v > 1) False """ return all...
:param func: :type func: (K, T) -> bool :rtype: bool Usage: >>> TDict(k1=1, k2=2, k3=3).all(lambda k, v: v > 0) True >>> TDict(k1=1, k2=2, k3=3).all(lambda k, v: v > 1) False
def is_primitive(val): """ Checks if the passed value is a primitive type. >>> is_primitive(1) True >>> is_primitive("abc") True >>> is_primitive(True) True >>> is_primitive({}) False >>> is_primitive([]) False >>> is_primitive(set([])) :param val: value to...
Checks if the passed value is a primitive type. >>> is_primitive(1) True >>> is_primitive("abc") True >>> is_primitive(True) True >>> is_primitive({}) False >>> is_primitive([]) False >>> is_primitive(set([])) :param val: value to check :return: True if value i...
def new(self): # type: () -> None ''' Create a new Rock Ridge Child Link record. Parameters: None. Returns: Nothing. ''' if self._initialized: raise pycdlibexception.PyCdlibInternalError('CL record already initialized!') sel...
Create a new Rock Ridge Child Link record. Parameters: None. Returns: Nothing.
def print_gce_info(zone, project, instance_name, data): """ outputs information about our Rackspace instance """ try: instance_info = _get_gce_compute().instances().get( project=project, zone=zone, instance=instance_name ).execute() log_yellow(pformat(...
outputs information about our Rackspace instance
def greplines(pattern, lines): """Given a list of strings *lines* return the lines that match pattern. """ res = [] for line in lines: match = re.search(pattern, line) if match is not None: res.append(line) return res
Given a list of strings *lines* return the lines that match pattern.
def idle_task(self): '''run periodic tasks''' now = time.time() if now - self.last_chan_check >= 1: self.last_chan_check = now self.update_channels()
run periodic tasks
def metadata_response(self, request, full_url, headers): """ Mock response for localhost metadata http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html """ parsed_url = urlparse(full_url) tomorrow = datetime.datetime.utcnow() + datetime.time...
Mock response for localhost metadata http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html
def integral(A=None,dF=None,F=None,axis = 0,trapez = False,cumulative = False): ''' Turns an array A of length N (the function values in N points) and an array dF of length N-1 (the masses of the N-1 intervals) into an array of length N (the integral \int A dF at N points, with first entry 0) :...
Turns an array A of length N (the function values in N points) and an array dF of length N-1 (the masses of the N-1 intervals) into an array of length N (the integral \int A dF at N points, with first entry 0) :param A: Integrand (optional, default ones, length N) :param dF: Integrator (optional, d...
def p_reference_variable_string_offset(p): 'reference_variable : reference_variable LBRACE expr RBRACE' p[0] = ast.StringOffset(p[1], p[3], lineno=p.lineno(2))
reference_variable : reference_variable LBRACE expr RBRACE
def create_csr(path=None, text=False, **kwargs): ''' Create a certificate signing request. path: Path to write the certificate to. text: If ``True``, return the PEM text without writing to a file. Default ``False``. algorithm: The hashing algorithm to be used for s...
Create a certificate signing request. path: Path to write the certificate to. text: If ``True``, return the PEM text without writing to a file. Default ``False``. algorithm: The hashing algorithm to be used for signing this request. Defaults to sha256. kwargs: ...
def tfhub_cache_dir(default_cache_dir=None, use_temp=False): """Returns cache directory. Returns cache directory from either TFHUB_CACHE_DIR environment variable or --tfhub_cache_dir or default, if set. Args: default_cache_dir: Default cache location to use if neither TFHUB_CACHE_DIR ...
Returns cache directory. Returns cache directory from either TFHUB_CACHE_DIR environment variable or --tfhub_cache_dir or default, if set. Args: default_cache_dir: Default cache location to use if neither TFHUB_CACHE_DIR environment variable nor --tfhub_cache_dir are ...
def transform(self, stims, validation='strict', *args, **kwargs): ''' Executes the transformation on the passed stim(s). Args: stims (str, Stim, list): One or more stimuli to process. Must be one of: - A string giving the path to a file that can be read ...
Executes the transformation on the passed stim(s). Args: stims (str, Stim, list): One or more stimuli to process. Must be one of: - A string giving the path to a file that can be read in as a Stim (e.g., a .txt file, .jpg image, etc.) ...
def apply_K(df, k): """Apply the geometric factors to the dataset and compute (apparent) resistivities/conductivities """ if 'k' not in df.columns: df['k'] = k if 'rho_a' not in df.columns: df['rho_a'] = df['r'] * df['k'] if 'sigma_a' not in df.columns: df['sigma_a'] = ...
Apply the geometric factors to the dataset and compute (apparent) resistivities/conductivities
def get_package_version(path): '''Extracts the version''' with open(VERSION_FILE, "rt") as f: verstrline = f.read() VERSION = r"^version = ['\"]([^'\"]*)['\"]" results = re.search(VERSION, verstrline, re.M) if results: version = results.group(1) else: raise RuntimeError...
Extracts the version
async def add_ssh_key(self, user, key): """Add a public SSH key to this model. :param str user: The username of the user :param str key: The public ssh key """ key_facade = client.KeyManagerFacade.from_connection(self.connection()) return await key_facade.AddKeys([key],...
Add a public SSH key to this model. :param str user: The username of the user :param str key: The public ssh key
def __is_subproperty_of (parent_property, p): """ As is_subfeature_of, for subproperties. """ if __debug__: from .property import Property assert isinstance(parent_property, Property) assert isinstance(p, Property) return is_subfeature_of (parent_property, p.feature)
As is_subfeature_of, for subproperties.
def vel_disp(self, kwargs_mass, kwargs_light, kwargs_anisotropy, kwargs_apertur): """ computes the averaged LOS velocity dispersion in the slit (convolved) :param kwargs_mass: mass model parameters (following lenstronomy lens model conventions) :param kwargs_light: deflector light param...
computes the averaged LOS velocity dispersion in the slit (convolved) :param kwargs_mass: mass model parameters (following lenstronomy lens model conventions) :param kwargs_light: deflector light parameters (following lenstronomy light model conventions) :param kwargs_anisotropy: anisotropy par...
def kill(self, ti): """ Kill (cancel) a Qubole command :param ti: Task Instance of the dag, used to determine the Quboles command id :return: response from Qubole """ if self.cmd is None: if not ti and not self.task_instance: raise Exception("U...
Kill (cancel) a Qubole command :param ti: Task Instance of the dag, used to determine the Quboles command id :return: response from Qubole
def check_background_commands_complete(self): """Check whether any background commands are running or to be run. If none are, return True. If any are, return False. """ unstarted_command_exists = False self.shutit_obj.log('In check_background_commands_complete: all background objects: ' + str(self.background...
Check whether any background commands are running or to be run. If none are, return True. If any are, return False.
def standalone(body): """ Returns complete html document given markdown html """ with open(_ROOT + '/html.dat', 'r') as html_template: head = html_title() html = "".join(html_template.readlines()) \ .replace("{{HEAD}}", head) \ .replace("{{BODY}}", body) ...
Returns complete html document given markdown html
def cross_entropy(ref, other, allow_nan_stats=True, name=None): """Computes the (Shannon) cross entropy. Denote two distributions by `P` (`ref`) and `Q` (`other`). Assuming `P, Q` are absolutely continuous with respect to one another and permit densities `p(x) dr(x)` and `q(x) dr(x)`, (Shanon...
Computes the (Shannon) cross entropy. Denote two distributions by `P` (`ref`) and `Q` (`other`). Assuming `P, Q` are absolutely continuous with respect to one another and permit densities `p(x) dr(x)` and `q(x) dr(x)`, (Shanon) cross entropy is defined as: ```none H[P, Q] = E_p[-log q(X)] = -int_F p(x) log ...
def fetch_file(uri, file=None, username=None, password=None): """ Fetch a file based on the URI provided. If you do not pass in a file pointer a tempfile.NamedTemporaryFile, or None if the file could not be retrieved is returned. The URI can be either an HTTP url, or "s3://bucket_name/key_name" ...
Fetch a file based on the URI provided. If you do not pass in a file pointer a tempfile.NamedTemporaryFile, or None if the file could not be retrieved is returned. The URI can be either an HTTP url, or "s3://bucket_name/key_name"
def fold(self, elems): """ Perform constant folding. If the result of applying the operator to the elements would be a fixed constant value, returns the result of applying the operator to the operands. Otherwise, returns an instance of ``Instructions`` containing the ins...
Perform constant folding. If the result of applying the operator to the elements would be a fixed constant value, returns the result of applying the operator to the operands. Otherwise, returns an instance of ``Instructions`` containing the instructions necessary to apply the operator. ...
def get_max_ballcount(cls, ball_diam, rolling_radius, min_gap=0.): """ The maximum number of balls given ``rolling_radius`` and ``ball_diam`` :param min_gap: minimum gap between balls (measured along vector between spherical centers) :type min_gap: :class:`float`...
The maximum number of balls given ``rolling_radius`` and ``ball_diam`` :param min_gap: minimum gap between balls (measured along vector between spherical centers) :type min_gap: :class:`float` :return: maximum ball count :rtype: :class:`int`
def clear_cache(self): """ Clear any in-memory cached values and short-lived on-disk materializations from MemoryCache """ for maybe_fn in self.__dict__.values(): # clear cache associated with all memoization decorators, # GTF and SequenceData objects ...
Clear any in-memory cached values and short-lived on-disk materializations from MemoryCache
def deploy(self, job_name, command='', blocksize=1): instances = [] """Deploy the template to a resource group.""" self.client.resource_groups.create_or_update( self.resource_group, { 'location': self.location, } ) template_pa...
Deploy the template to a resource group.
def rest_post(url, data, timeout, show_error=False): '''Call rest post method''' try: response = requests.post(url, headers={'Accept': 'application/json', 'Content-Type': 'application/json'},\ data=data, timeout=timeout) return response except Exception as ex...
Call rest post method
def EQ100(T, A=0, B=0, C=0, D=0, E=0, F=0, G=0, order=0): r'''DIPPR Equation # 100. Used in calculating the molar heat capacities of liquids and solids, liquid thermal conductivity, and solid density. All parameters default to zero. As this is a straightforward polynomial, no restrictions on parameters ...
r'''DIPPR Equation # 100. Used in calculating the molar heat capacities of liquids and solids, liquid thermal conductivity, and solid density. All parameters default to zero. As this is a straightforward polynomial, no restrictions on parameters apply. Note that high-order polynomials like this may need...
def fillna(self, value): """Returns Index with missing values replaced with value. Parameters ---------- value : {int, float, bytes, bool} Scalar value to replace missing values with. Returns ------- Index With missing values replaced. ...
Returns Index with missing values replaced with value. Parameters ---------- value : {int, float, bytes, bool} Scalar value to replace missing values with. Returns ------- Index With missing values replaced.
def get_port_channel_detail_output_lacp_aggr_member_interface_type(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_port_channel_detail = ET.Element("get_port_channel_detail") config = get_port_channel_detail output = ET.SubElement(get_port_ch...
Auto Generated Code
def Or(a: Bool, b: Bool) -> Bool: """Create an or expression. :param a: :param b: :return: """ union = a.annotations + b.annotations return Bool(z3.Or(a.raw, b.raw), annotations=union)
Create an or expression. :param a: :param b: :return:
def skills_name_show(self, name, **kwargs): "https://developer.zendesk.com/rest_api/docs/chat/skills#get-skill-by-name" api_path = "/api/v2/skills/name/{name}" api_path = api_path.format(name=name) return self.call(api_path, **kwargs)
https://developer.zendesk.com/rest_api/docs/chat/skills#get-skill-by-name
def _nodetool(cmd): ''' Internal cassandra nodetool wrapper. Some functions are not available via pycassa so we must rely on nodetool. ''' nodetool = __salt__['config.option']('cassandra.nodetool') host = __salt__['config.option']('cassandra.host') return __salt__['cmd.run_stdout']('{0} -h {...
Internal cassandra nodetool wrapper. Some functions are not available via pycassa so we must rely on nodetool.
def _set_post(self, v, load=False): """ Setter method for post, mapped from YANG variable /diag/post (container) If this variable is read-only (config: false) in the source YANG file, then _set_post is considered as a private method. Backends looking to populate this variable should do so via ca...
Setter method for post, mapped from YANG variable /diag/post (container) If this variable is read-only (config: false) in the source YANG file, then _set_post is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_post() directly.
def get_question_content(self, number: str) -> str: """ 取得課程中特定題目內容 """ try: # 操作所需資訊 params = { 'hwId': number } # 取得資料 response = self.__session.get( self.__url + '/showHomework', params=params,...
取得課程中特定題目內容
def rfind(values, value): """ :return: the highest index in values where value is found, or -1 """ if isinstance(values, STRING_TYPES): try: return values.rfind(value) except TypeError: # Python 3 compliance: search for str values in bytearray return values.r...
:return: the highest index in values where value is found, or -1
def disableGyro(self): """ Specifies the device should NOT write gyro values to the FIFO, is not applied until enableFIFO is called. :return: """ logger.debug("Disabling gyro sensor") self.fifoSensorMask &= ~self.enableGyroMask self._gyroEnabled = False s...
Specifies the device should NOT write gyro values to the FIFO, is not applied until enableFIFO is called. :return:
def add_team(self, team, sync=True): """ add a team to this OS instance. :param team: the team to add on this OS instance :param sync: If sync=True(default) synchronize with Ariane server. If sync=False, add the team object on list to be added on next save(). :return: ...
add a team to this OS instance. :param team: the team to add on this OS instance :param sync: If sync=True(default) synchronize with Ariane server. If sync=False, add the team object on list to be added on next save(). :return:
def _rotate_and_chop(self, verts, normal, axis=[0, 0, 1]): r""" Method to rotate a set of vertices (or coords) to align with an axis points must be coplanar and normal must be given Chops axis coord to give vertices back in 2D Used to prepare verts for printing or calculating con...
r""" Method to rotate a set of vertices (or coords) to align with an axis points must be coplanar and normal must be given Chops axis coord to give vertices back in 2D Used to prepare verts for printing or calculating convex hull in order to arrange them in hull order for calcula...
def primitive_form(obj, **kwargs): '''Return obj, if possible, in a form composed of primitive or builtin objects.''' if isinstance(obj, type): return obj return Type.dispatch(obj).primitive_form(**kwargs)
Return obj, if possible, in a form composed of primitive or builtin objects.
def properties(self): ''' Android Properties, extracted from `adb shell getprop` Returns: dict of props, for example: {'ro.bluetooth.dun': 'true'} ''' props = {} for line in self.adb_shell(['getprop']).splitlines(): m ...
Android Properties, extracted from `adb shell getprop` Returns: dict of props, for example: {'ro.bluetooth.dun': 'true'}
def score(package_path): """ Runs pylint on a package and returns a score Lower score is better :param package_path: path of the package to score :return: number of score """ python_files = find_files(package_path, '*.py') total_counter = Counter() for python_file in python_files:...
Runs pylint on a package and returns a score Lower score is better :param package_path: path of the package to score :return: number of score
def BLASTquery(query,database,program,filter=None,\ format_type=None, expect=None,\ nucl_reward=None, nucl_penalty=None,\ gapcosts=None, matrix=None,\ hitlist_size=None, descriptions=None,\ alignments=None,\ ncbi_gi=None, threshol...
Performs a blast query online. As in https://ncbi.github.io/blast-cloud/ :param query: Search query. Allowed values: Accession, GI, or FASTA. :param database: BLAST database. Allowed values: nt, nr, refseq_rna, refseq_protein, swissprot, pdbaa, pdbnt :param program: BLAST program. Allowed values: bla...
def min_weighted_vertex_cover(G, weight=None, sampler=None, **sampler_args): """Returns an approximate minimum weighted vertex cover. Defines a QUBO with ground states corresponding to a minimum weighted vertex cover and uses the sampler to sample from it. A vertex cover is a set of vertices such that...
Returns an approximate minimum weighted vertex cover. Defines a QUBO with ground states corresponding to a minimum weighted vertex cover and uses the sampler to sample from it. A vertex cover is a set of vertices such that each edge of the graph is incident with at least one vertex in the set. A minim...
def _sample_points(X, centers, oversampling_factor, random_state): r""" Sample points independently with probability .. math:: p_x = \frac{\ell \cdot d^2(x, \mathcal{C})}{\phi_X(\mathcal{C})} """ # re-implement evaluate_cost here, to avoid redundant computation distances = pairwise_di...
r""" Sample points independently with probability .. math:: p_x = \frac{\ell \cdot d^2(x, \mathcal{C})}{\phi_X(\mathcal{C})}
def get_safe_variables(self,query,var_dict): ''' Create a list of safe variables: variables bounded to constants or that occur in a positive goal ''' variables_bounded_to_constants = [] for constraint in query.constraints: if (constraint.get_left_side().is_variable() and ...
Create a list of safe variables: variables bounded to constants or that occur in a positive goal
def parse_cg(self): """Parse the call graph.""" # skip call graph header line = self.readline() while self._cg_header_re.match(line): line = self.readline() # process call graph entries entry_lines = [] # An EOF in readline terminates the program wit...
Parse the call graph.
def get_data(self): """Returns the x, y, w, h, data as a tuple.""" return self.x, self.y, self.w, self.h
Returns the x, y, w, h, data as a tuple.
def _make_candidate_from_result(self, result): """ Make a Candidate from a Google geocoder results dictionary. """ candidate = Candidate() candidate.match_addr = result['formatted_address'] candidate.x = result['geometry']['location']['lng'] candidate.y = result['geometry']['loca...
Make a Candidate from a Google geocoder results dictionary.
def _to_milliseconds(self, time): """ Converts a datetime-like object to epoch, in milliseconds Timezone-naive datetime objects are assumed to be in UTC Parameters ---------- time : dt.datetime | pd.Timestamp | int Returns ------- int ...
Converts a datetime-like object to epoch, in milliseconds Timezone-naive datetime objects are assumed to be in UTC Parameters ---------- time : dt.datetime | pd.Timestamp | int Returns ------- int epoch milliseconds
def get_all_domains(self, max_domains=None, next_token=None): """ Returns a :py:class:`boto.resultset.ResultSet` containing all :py:class:`boto.sdb.domain.Domain` objects associated with this connection's Access Key ID. :keyword int max_domains: Limit the returned ...
Returns a :py:class:`boto.resultset.ResultSet` containing all :py:class:`boto.sdb.domain.Domain` objects associated with this connection's Access Key ID. :keyword int max_domains: Limit the returned :py:class:`ResultSet <boto.resultset.ResultSet>` to the specified ...
def main(): """Simply merge all trajectories in the working directory""" folder = os.getcwd() print('Merging all files') merge_all_in_folder(folder, delete_other_files=True, # We will only keep one trajectory dynamic_imports=FunctionParameter, ...
Simply merge all trajectories in the working directory
def get_issues(self, milestone=github.GithubObject.NotSet, state=github.GithubObject.NotSet, assignee=github.GithubObject.NotSet, mentioned=github.GithubObject.NotSet, labels=github.GithubObject.NotSet, sort=github.GithubObject.NotSet, direction=github.GithubObject.NotSet, since=github.GithubObject.NotSet, creator=gith...
:calls: `GET /repos/:owner/:repo/issues <http://developer.github.com/v3/issues>`_ :param milestone: :class:`github.Milestone.Milestone` or "none" or "*" :param state: string. `open`, `closed`, or `all`. If this is not set the GitHub API default behavior will be used. At the moment this is to return only...
def resolve_reference(target_reference, project): """ Given a target_reference, made in context of 'project', returns the AbstractTarget instance that is referred to, as well as properties explicitly specified for this reference. """ # Separate target name from properties override assert isinsta...
Given a target_reference, made in context of 'project', returns the AbstractTarget instance that is referred to, as well as properties explicitly specified for this reference.
def nfa_dot_importer(input_file: str) -> dict: """ Imports a NFA from a DOT file. Of .dot files are recognized the following attributes • nodeX shape=doublecircle -> accepting node; • nodeX root=true -> initial node; • edgeX label="a" -> action in alphabet; • fakeX style=invisi...
Imports a NFA from a DOT file. Of .dot files are recognized the following attributes • nodeX shape=doublecircle -> accepting node; • nodeX root=true -> initial node; • edgeX label="a" -> action in alphabet; • fakeX style=invisible -> dummy invisible nodes pointing t...
def user_dj(uid, offset=0, limit=30): """获取用户电台数据 :param uid: 用户的ID,可通过登录或者其他接口获取 :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 30 """ if uid is None: raise ParamsError() r = NCloudBot() r.method = 'USER_DJ' r.data = {'offset': offset, 'limit': li...
获取用户电台数据 :param uid: 用户的ID,可通过登录或者其他接口获取 :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 30
def path_shift(self, shift=1): """ Shift path segments from :attr:`path` to :attr:`script_name` and vice versa. :param shift: The number of path segments to shift. May be negative to change the shift direction. (default: 1) """ script, path = path...
Shift path segments from :attr:`path` to :attr:`script_name` and vice versa. :param shift: The number of path segments to shift. May be negative to change the shift direction. (default: 1)
def _tag_from_regex(self, tags_regex, service_name): """ Use a named regexp on the current service_name to create extra tags Example HAProxy service name: be_edge_http_sre-prod_elk Example named regexp: be_edge_http_(?P<team>[a-z]+)\\-(?P<env>[a-z]+)_(?P<app>.*) Resulting tags: [...
Use a named regexp on the current service_name to create extra tags Example HAProxy service name: be_edge_http_sre-prod_elk Example named regexp: be_edge_http_(?P<team>[a-z]+)\\-(?P<env>[a-z]+)_(?P<app>.*) Resulting tags: ['team:sre','env:prod','app:elk']
def c_if(self, classical, val): """Add classical control on register classical and value val.""" if not isinstance(classical, ClassicalRegister): raise QiskitError("c_if must be used with a classical register") if val < 0: raise QiskitError("control value should be non-ne...
Add classical control on register classical and value val.
def set_pkg_source_info(self, doc, text): """Sets the package's source information, if not already set. text - Free form text. Raises CardinalityError if already defined. Raises OrderError if no package previously defined. """ self.assert_package_exists() if not s...
Sets the package's source information, if not already set. text - Free form text. Raises CardinalityError if already defined. Raises OrderError if no package previously defined.
def get_contrasts(self, names=None, variables=None, **kwargs): ''' Return contrast information for the current block. Args: names (list): Optional list of names of contrasts to return. If None (default), all contrasts are returned. variables (bool): Optional list...
Return contrast information for the current block. Args: names (list): Optional list of names of contrasts to return. If None (default), all contrasts are returned. variables (bool): Optional list of strings giving the names of design matrix columns to us...
def cleanup(self): """Clean up temporary tag checkout dir.""" shutil.rmtree(self.temp_tagdir) # checkout_from_tag might operate on a subdirectory (mostly # 'gitclone'), so cleanup the parent dir as well parentdir = os.path.dirname(self.temp_tagdir) # ensure we don't remov...
Clean up temporary tag checkout dir.
def _check_state(self): """Check if this instance can model and/or can invert """ if(self.grid is not None and self.configs.configs is not None and self.assignments['forward_model'] is not None): self.can_model = True if(self.grid is not None and ...
Check if this instance can model and/or can invert
def listSnapshotDir(kls, path): """Return the set of snapshot directories and non-snapshot directories under the given path.""" snapshotSet = set() nonsnapshotSet = set() try: entryList = os.listdir(path) for e in entryList: if kls.isFilenameInteger(e): snapshotSet .add(e) else: ...
Return the set of snapshot directories and non-snapshot directories under the given path.
def _add_inputs_to_kwargs(args, kwargs, parser): """Convert input system config, flow cell directory and sample yaml to kwargs. Handles back compatibility with previous commandlines while allowing flexible specification of input parameters. """ inputs = [x for x in [args.global_config, args.fc_dir]...
Convert input system config, flow cell directory and sample yaml to kwargs. Handles back compatibility with previous commandlines while allowing flexible specification of input parameters.
def _make_request(self, url, parameters, result_key): """Make http/https request to Google API. Method prepares url parameters, drops None values, and gets default values. Finally makes request using protocol assigned to client and returns data. :param url: url part - specifies...
Make http/https request to Google API. Method prepares url parameters, drops None values, and gets default values. Finally makes request using protocol assigned to client and returns data. :param url: url part - specifies API endpoint :param parameters: dictionary of url parame...
def search(self, *query, **kwargs): ''' Searches based on tags specified by users Parameters --------- query: str tags to search on. If multiple terms, provided in comma delimited string format prefix: str start of archive name. Pro...
Searches based on tags specified by users Parameters --------- query: str tags to search on. If multiple terms, provided in comma delimited string format prefix: str start of archive name. Providing a start string improves search speed.
def translate(self, package, into=None): """From a binary package, translate to a local binary distribution.""" if not package.local: raise ValueError('BinaryTranslator cannot translate remote packages.') if not isinstance(package, self._package_type): return None if not package.compatible(s...
From a binary package, translate to a local binary distribution.
def enabled(name, **kwargs): ''' Return True if the named service is enabled, false otherwise A service is considered enabled if in your service directory: - an executable ./run file exist - a file named "down" does not exist .. versionadded:: 2015.5.7 name Service name CLI Ex...
Return True if the named service is enabled, false otherwise A service is considered enabled if in your service directory: - an executable ./run file exist - a file named "down" does not exist .. versionadded:: 2015.5.7 name Service name CLI Example: .. code-block:: bash ...
def reverse(self, request, view_name): """ Returns the URL of this tenant. """ http_type = 'https://' if request.is_secure() else 'http://' domain = get_current_site(request).domain url = ''.join((http_type, self.schema_name, '.', domain, reverse(view_name))) r...
Returns the URL of this tenant.
def _encode_message(cls, message): """ Encode a single message. The magic number of a message is a format version number. The only supported magic number right now is zero. Format:: Message => Crc MagicByte Attributes Key Value Crc => int32 Mag...
Encode a single message. The magic number of a message is a format version number. The only supported magic number right now is zero. Format:: Message => Crc MagicByte Attributes Key Value Crc => int32 MagicByte => int8 Attributes => int8 ...
def find_root_in_path(graph, path_nodes): """Find the 'root' of the path -> The node with the lowest out degree, if multiple: root is the one with the highest out degree among those with lowest out degree :param pybel.BELGraph graph: A BEL Graph :param list[tuple] path_nodes: A list of nodes i...
Find the 'root' of the path -> The node with the lowest out degree, if multiple: root is the one with the highest out degree among those with lowest out degree :param pybel.BELGraph graph: A BEL Graph :param list[tuple] path_nodes: A list of nodes in their order in a path :return: A pair of th...
def from_cli_single_ifo(opt, length, delta_f, low_frequency_cutoff, ifo, **kwargs): """ Get the PSD for a single ifo when using the multi-detector CLI """ single_det_opt = copy_opts_for_single_ifo(opt, ifo) return from_cli(single_det_opt, length, delta_f, low_frequency_cutoff, ...
Get the PSD for a single ifo when using the multi-detector CLI
def _xml_to_dict(xmltree): ''' Convert an XML tree into a dict ''' if sys.version_info < (2, 7): children_len = len(xmltree.getchildren()) else: children_len = len(xmltree) if children_len < 1: name = xmltree.tag if '}' in name: comps = name.split('}'...
Convert an XML tree into a dict
def background(color): """Set the background color.""" if color not in background_colors: return if is_win32: last_bg = background_colors[color][1] set_color_win32(last_fg | last_bg) else: set_color_ansi(background_colors[color][0])
Set the background color.
def _format_newlines(prefix, formatted_node, options): """ Convert newlines into U+23EC characters, followed by an actual newline and then a tree prefix so as to position the remaining text under the previous line. """ replacement = u''.join([ options.NEWLINE, u'\n', pref...
Convert newlines into U+23EC characters, followed by an actual newline and then a tree prefix so as to position the remaining text under the previous line.
def update(self, arx, xarchive=None, arf=None, evals=None): """checks for better solutions in list `arx`. Based on the smallest corresponding value in `arf`, alternatively, `update` may be called with a `BestSolution` instance like ``update(another_best_solution)`` in which case ...
checks for better solutions in list `arx`. Based on the smallest corresponding value in `arf`, alternatively, `update` may be called with a `BestSolution` instance like ``update(another_best_solution)`` in which case the better solution becomes the current best. `xarchive` is u...
def register_view(self, view): """Called when the View was registered Can be used e.g. to connect signals. Here, the destroy signal is connected to close the application """ super(StateEditorController, self).register_view(view) view.prepare_the_labels() # the preparation of th...
Called when the View was registered Can be used e.g. to connect signals. Here, the destroy signal is connected to close the application
def _download_query(self, as_of): """Formulate the specific query needed for download Not intended to be called by developers directly. :param as_of: Date in 'YYYYMMDD' format :type as_of: string """ c = self.institution.client() q = c.credit_card_account_query(...
Formulate the specific query needed for download Not intended to be called by developers directly. :param as_of: Date in 'YYYYMMDD' format :type as_of: string
def user(self, name): """ Get a user's anime list and details. This returns an encapsulated data type. :param str name: The username to query :rtype: :class:`Pymoe.Mal.Objects.User` :return: A :class:`Pymoe.Mal.Objects.User` Object """ anime_data = requests.get(s...
Get a user's anime list and details. This returns an encapsulated data type. :param str name: The username to query :rtype: :class:`Pymoe.Mal.Objects.User` :return: A :class:`Pymoe.Mal.Objects.User` Object