code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def asdatetime(self, naive=True): """Return this datetime_tz as a datetime object. Args: naive: Return *without* any tz info. Returns: This datetime_tz as a datetime object. """ args = list(self.timetuple()[0:6])+[self.microsecond] if not naive: args.append(self.tzinfo) r...
Return this datetime_tz as a datetime object. Args: naive: Return *without* any tz info. Returns: This datetime_tz as a datetime object.
def processPointOfSalePayment(request): ''' This view handles the callbacks from point-of-sale transactions. Please note that this will only work if you have set up your callback URL in Square to point to this view. ''' print('Request data is: %s' % request.GET) # iOS transactions put all r...
This view handles the callbacks from point-of-sale transactions. Please note that this will only work if you have set up your callback URL in Square to point to this view.
def create_preauth(byval, key, by='name', expires=0, timestamp=None): """ Generates a zimbra preauth value :param byval: The value of the targeted user (according to the by-parameter). For example: The account name, if "by" is "name". :param key: The domain preauth key (you can retrieve that using z...
Generates a zimbra preauth value :param byval: The value of the targeted user (according to the by-parameter). For example: The account name, if "by" is "name". :param key: The domain preauth key (you can retrieve that using zmprov gd) :param by: What type is the byval-parameter? Valid parameters are...
def proc_file(infile: str, outfile: str, opts: Namespace) -> bool: """ Process infile. :param infile: input file to be processed :param outfile: target output file. :param opts: :return: """ g = fhir_json_to_rdf(infile, opts.uribase, opts.graph, add_ontology_header=not opts.noontology, ...
Process infile. :param infile: input file to be processed :param outfile: target output file. :param opts: :return:
def transform_annotation(self, ann, duration): '''Apply the vector transformation. Parameters ---------- ann : jams.Annotation The input annotation duration : number > 0 The duration of the track Returns ------- data : dict ...
Apply the vector transformation. Parameters ---------- ann : jams.Annotation The input annotation duration : number > 0 The duration of the track Returns ------- data : dict data['vector'] : np.ndarray, shape=(dimension,) ...
def writes(mdict, filename='data.h5', truncate_existing=False, truncate_invalid_matlab=False, options=None, **keywords): """ Writes data into an HDF5 file (high level). High level function to store one or more Python types (data) to specified pathes in an HDF5 file. The paths are specified as PO...
Writes data into an HDF5 file (high level). High level function to store one or more Python types (data) to specified pathes in an HDF5 file. The paths are specified as POSIX style paths where the directory name is the Group to put it in and the basename is the name to write it to. There are vario...
def _translate_nd(self, source: mx.nd.NDArray, source_length: int, restrict_lexicon: Optional[lexicon.TopKLexicon], raw_constraints: List[Optional[constrained.RawConstraintList]], raw_avoid_list: List[Optional[...
Translates source of source_length, given a bucket_key. :param source: Source ids. Shape: (batch_size, bucket_key, num_factors). :param source_length: Bucket key. :param restrict_lexicon: Lexicon to use for vocabulary restriction. :param raw_constraints: A list of optional constraint li...
def tasks(self, name): '''Get all the tasks that match a name''' found = self[name] if isinstance(found, Shovel): return [v for _, v in found.items()] return [found]
Get all the tasks that match a name
def any(self, predicate=None): '''Determine if the source sequence contains any elements which satisfy the predicate. Only enough of the sequence to satisfy the predicate once is consumed. Note: This method uses immediate execution. Args: predicate: An optional sin...
Determine if the source sequence contains any elements which satisfy the predicate. Only enough of the sequence to satisfy the predicate once is consumed. Note: This method uses immediate execution. Args: predicate: An optional single argument function used to test each ...
def get_bare_quoted_string(value): """bare-quoted-string = DQUOTE *([FWS] qcontent) [FWS] DQUOTE A quoted-string without the leading or trailing white space. Its value is the text between the quote marks, with whitespace preserved and quoted pairs decoded. """ if value[0] != '"': raise...
bare-quoted-string = DQUOTE *([FWS] qcontent) [FWS] DQUOTE A quoted-string without the leading or trailing white space. Its value is the text between the quote marks, with whitespace preserved and quoted pairs decoded.
def iau2000b(jd_tt): """Compute Earth nutation based on the faster IAU 2000B nutation model. `jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats Returns a tuple ``(delta_psi, delta_epsilon)`` measured in tenths of a micro-arcsecond. Each is either a float, or a NumPy array with ...
Compute Earth nutation based on the faster IAU 2000B nutation model. `jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats Returns a tuple ``(delta_psi, delta_epsilon)`` measured in tenths of a micro-arcsecond. Each is either a float, or a NumPy array with the same dimensions as the...
def satisfaction_rating_show(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/satisfaction_ratings#show-satisfaction-rating" api_path = "/api/v2/satisfaction_ratings/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/satisfaction_ratings#show-satisfaction-rating
def Message(msg, id=260, ok=None): """Original doc: Display a MESSAGE string. Return when the user clicks the OK button or presses Return. The MESSAGE string can be at most 255 characters long. """ return psidialogs.message(message=msg, ok=ok)
Original doc: Display a MESSAGE string. Return when the user clicks the OK button or presses Return. The MESSAGE string can be at most 255 characters long.
def configure(self, ns, mappings=None, **kwargs): """ Apply mappings to a namespace. """ if mappings is None: mappings = dict() mappings.update(kwargs) for operation, definition in mappings.items(): try: configure_func = self._fin...
Apply mappings to a namespace.
def fix_hp_addrs(server): """ Works around hpcloud's peculiar "all ip addresses are returned as private even though one is public" bug. This is also what the official hpfog gem does in the ``Fog::Compute::HP::Server#public_ip_address`` method. :param dict server: Contains the server ID, a list of...
Works around hpcloud's peculiar "all ip addresses are returned as private even though one is public" bug. This is also what the official hpfog gem does in the ``Fog::Compute::HP::Server#public_ip_address`` method. :param dict server: Contains the server ID, a list of public IP addresses, and a li...
def initialize(self, configfile=None): """ Initialize the module """ method = "initialize" A = None metadata = {method: configfile} send_array(self.socket, A, metadata) A, metadata = recv_array( self.socket, poll=self.poll, poll_timeout=self...
Initialize the module
def auth(self, request): """ let's auth the user to the Service :param request: request object :return: callback url :rtype: string that contains the url to redirect after auth """ service = UserService.objects.get(user=request.user, name='Service...
let's auth the user to the Service :param request: request object :return: callback url :rtype: string that contains the url to redirect after auth
def display(self): """A unicode value with the object's data, to be used for displaying the object in your application.""" if self.degree and self.school: disp = self.degree + u' from ' + self.school else: disp = self.degree or self.school or None ...
A unicode value with the object's data, to be used for displaying the object in your application.
def run(self, files, stack): "Clean your text" for filename, post in files.items(): post.content = self.bleach.clean(post.content, *self.args, **self.kwargs)
Clean your text
def analyze(self): """ Run an analysis on all of the items in this library section. See See :func:`~plexapi.base.PlexPartialObject.analyze` for more details. """ key = '/library/sections/%s/analyze' % self.key self._server.query(key, method=self._server._session.put)
Run an analysis on all of the items in this library section. See See :func:`~plexapi.base.PlexPartialObject.analyze` for more details.
def get_variant_by_name(self, name, variant_info=None): """Get the genotype of a marker using it's name. Args: name (str): The name of the marker. variant_info (pandas.Series): The marker information (e.g. seek). Returns: list: A list of Genotypes (only one ...
Get the genotype of a marker using it's name. Args: name (str): The name of the marker. variant_info (pandas.Series): The marker information (e.g. seek). Returns: list: A list of Genotypes (only one for PyPlink, see note below). Note ==== ...
def scan_temperature(self, measure, temperature, rate, delay=1): """Performs a temperature scan. Measures until the target temperature is reached. :param measure: A callable called repeatedly until stability at target temperature is reached. :param temperature: The target t...
Performs a temperature scan. Measures until the target temperature is reached. :param measure: A callable called repeatedly until stability at target temperature is reached. :param temperature: The target temperature in kelvin. :param rate: The sweep rate in kelvin per minu...
def fullinfo_get(self, tids, session, fields=[]): '''taobao.topats.trades.fullinfo.get 异步批量获取交易订单详情api 使用指南:http://open.taobao.com/dev/index.php/ATS%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97 - 1.提供异步批量获取订单详情功能 - 2.一次调用最多支持40个订单 - 3.提交任务会进行初步任务校验,如果成功会返回任务号和创建时间,如果失败就报错 ...
taobao.topats.trades.fullinfo.get 异步批量获取交易订单详情api 使用指南:http://open.taobao.com/dev/index.php/ATS%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97 - 1.提供异步批量获取订单详情功能 - 2.一次调用最多支持40个订单 - 3.提交任务会进行初步任务校验,如果成功会返回任务号和创建时间,如果失败就报错 - 4.可以接收淘宝发出的任务完成消息,也可以过一段时间来取结果。获取结果接口为taobao.topats.re...
def blocking_start(self, waiting_func=None): """this function starts the task manager running to do tasks. The waiting_func is normally used to do something while other threads are running, but here we don't have other threads. So the waiting func will never get called. I can see want...
this function starts the task manager running to do tasks. The waiting_func is normally used to do something while other threads are running, but here we don't have other threads. So the waiting func will never get called. I can see wanting this function to be called at least once aft...
def read_namespaced_service(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_service # noqa: E501 read the specified Service # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True ...
read_namespaced_service # noqa: E501 read the specified Service # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_service(name, namespace, async_req=True) >>> ...
def register_download_command(self, download_func): """ Add 'download' command for downloading a project to a directory. For non empty directories it will download remote files replacing local files. :param download_func: function to run when user choses this option """ d...
Add 'download' command for downloading a project to a directory. For non empty directories it will download remote files replacing local files. :param download_func: function to run when user choses this option
def make_date(df:DataFrame, date_field:str): "Make sure `df[field_name]` is of the right date type." field_dtype = df[date_field].dtype if isinstance(field_dtype, pd.core.dtypes.dtypes.DatetimeTZDtype): field_dtype = np.datetime64 if not np.issubdtype(field_dtype, np.datetime64): df[date...
Make sure `df[field_name]` is of the right date type.
def has_firewall(vlan): """Helper to determine whether or not a VLAN has a firewall. :param dict vlan: A dictionary representing a VLAN :returns: True if the VLAN has a firewall, false if it doesn't. """ return bool( vlan.get('dedicatedFirewallFlag', None) or vlan.get('highAvailabil...
Helper to determine whether or not a VLAN has a firewall. :param dict vlan: A dictionary representing a VLAN :returns: True if the VLAN has a firewall, false if it doesn't.
def MiddleClick(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse middle click at point x, y. x: int. y: int. waitTime: float. """ SetCursorPos(x, y) screenWidth, screenHeight = GetScreenSize() mouse_event(MouseEventFlag.MiddleDown | MouseEventFlag.Ab...
Simulate mouse middle click at point x, y. x: int. y: int. waitTime: float.
def is_parent_of_catalog(self, id_, catalog_id): """Tests if an ``Id`` is a direct parent of a catalog. arg: id (osid.id.Id): an ``Id`` arg: catalog_id (osid.id.Id): the ``Id`` of a catalog return: (boolean) - ``true`` if this ``id`` is a parent of ``catalog_id,`` ...
Tests if an ``Id`` is a direct parent of a catalog. arg: id (osid.id.Id): an ``Id`` arg: catalog_id (osid.id.Id): the ``Id`` of a catalog return: (boolean) - ``true`` if this ``id`` is a parent of ``catalog_id,`` ``false`` otherwise raise: NotFound - ``catalog_id...
def sign_with_privkey( digest: bytes, privkey: Ed25519PrivateKey, global_pubkey: Ed25519PublicPoint, nonce: int, global_commit: Ed25519PublicPoint, ) -> Ed25519Signature: """Create a CoSi signature of `digest` with the supplied private key. This function needs to know the global public key a...
Create a CoSi signature of `digest` with the supplied private key. This function needs to know the global public key and global commitment.
def tran_hash(self, a, b, c, n): """implementation of the tran53 hash function""" return (((TRAN[(a+n)&255]^TRAN[b]*(n+n+1))+TRAN[(c)^TRAN[n]])&255)
implementation of the tran53 hash function
def options(self, request, *args, **kwargs): """ Handles responding to requests for the OPTIONS HTTP verb """ response = HttpResponse() response['Allow'] = ', '.join(self.allowed_methods) response['Content-Length'] = 0 return response
Handles responding to requests for the OPTIONS HTTP verb
def hull(script, reorient_normal=True): """ Calculate the convex hull with Qhull library http://www.qhull.org/html/qconvex.htm The convex hull of a set of points is the boundary of the minimal convex set containing the given non-empty finite set of points. Args: script: the FilterScrip...
Calculate the convex hull with Qhull library http://www.qhull.org/html/qconvex.htm The convex hull of a set of points is the boundary of the minimal convex set containing the given non-empty finite set of points. Args: script: the FilterScript object or script filename to write ...
def h2o_mean_absolute_error(y_actual, y_predicted, weights=None): """ Mean absolute error regression loss. :param y_actual: H2OFrame of actual response. :param y_predicted: H2OFrame of predicted response. :param weights: (Optional) sample weights :returns: mean absolute error loss (best is 0.0)...
Mean absolute error regression loss. :param y_actual: H2OFrame of actual response. :param y_predicted: H2OFrame of predicted response. :param weights: (Optional) sample weights :returns: mean absolute error loss (best is 0.0).
def needle(reads): """ Run a Needleman-Wunsch alignment and return the two sequences. @param reads: An iterable of two reads. @return: A C{Reads} instance with the two aligned sequences. """ from tempfile import mkdtemp from shutil import rmtree dir = mkdtemp() file1 = join(dir, '...
Run a Needleman-Wunsch alignment and return the two sequences. @param reads: An iterable of two reads. @return: A C{Reads} instance with the two aligned sequences.
def db_check(name, table=None, **connection_args): ''' Repairs the full database or just a given table CLI Example: .. code-block:: bash salt '*' mysql.db_check dbname salt '*' mysql.db_check dbname dbtable ''' ret = [] if table is None: #...
Repairs the full database or just a given table CLI Example: .. code-block:: bash salt '*' mysql.db_check dbname salt '*' mysql.db_check dbname dbtable
def dependency(app_label, model): """ Returns a Django 1.7+ style dependency tuple for inclusion in migration.dependencies[] """ from django.db.migrations import swappable_dependency return swappable_dependency(get_model_name(app_label, model))
Returns a Django 1.7+ style dependency tuple for inclusion in migration.dependencies[]
def rmtree(path): """Remove the given recursively. :note: we use shutil rmtree but adjust its behaviour to see whether files that couldn't be deleted are read-only. Windows will not remove them in that case""" def onerror(func, path, exc_info): # Is the error an access error ? os.c...
Remove the given recursively. :note: we use shutil rmtree but adjust its behaviour to see whether files that couldn't be deleted are read-only. Windows will not remove them in that case
def add_parameters(self,template_file,in_file=None,pst_path=None): """ add new parameters to a control file Parameters ---------- template_file : str template file in_file : str(optional) model input file. If None, template_file.replace('....
add new parameters to a control file Parameters ---------- template_file : str template file in_file : str(optional) model input file. If None, template_file.replace('.tpl','') is used pst_path : str(optional) the path ...
def pb_id(self, pb_id: str): """Set the PB Id for this device.""" # FIXME(BMo) instead of creating the object to check if the PB exists # use a method on PB List? # ProcessingBlock(pb_id) self.set_state(DevState.ON) self._pb_id = pb_id
Set the PB Id for this device.
def to_struct_file(self, f): """ write a PEST-style structure file Parameters ---------- f : (str or file handle) file to write the GeoStruct information to """ if isinstance(f, str): f = open(f,'w') f.write("STRUCTURE {0}\n".format(self....
write a PEST-style structure file Parameters ---------- f : (str or file handle) file to write the GeoStruct information to
def __read(path): ''' Reads a File with contents in correct JSON format. Returns the data as Python objects. path - (string) path to the file ''' try: with open(path, 'r') as data_file: data = data_file.read() data = json.loads(...
Reads a File with contents in correct JSON format. Returns the data as Python objects. path - (string) path to the file
def _route_action(self, action, email): """ Given an action and an email (can be None), figure out what to do with the validated inputs. :param str action: The action. Must be one of self.valid_actions. :type email: str or None :param email: Either an email address, or N...
Given an action and an email (can be None), figure out what to do with the validated inputs. :param str action: The action. Must be one of self.valid_actions. :type email: str or None :param email: Either an email address, or None if the action doesn't need an email address.
def _on_connection_open(self, connection): """ Callback invoked when the connection is successfully established. Args: connection (pika.connection.SelectConnection): The newly-estabilished connection. """ _log.info("Successfully opened connection to %...
Callback invoked when the connection is successfully established. Args: connection (pika.connection.SelectConnection): The newly-estabilished connection.
def _get_data(self, file_id): ''' a helper method for retrieving the byte data of a file ''' title = '%s._get_data' % self.__class__.__name__ # request file data try: record_data = self.drive.get_media(fileId=file_id).execute() except: r...
a helper method for retrieving the byte data of a file
def reset_failed(self, pk): """ reset failed counter :param pk: :return: """ TriggerService.objects.filter(consumer__name__id=pk).update(consumer_failed=0, provider_failed=0) TriggerService.objects.filter(provider__name__id=pk).update(consumer_failed=0, provid...
reset failed counter :param pk: :return:
def propose_unif(self): """Propose a new live point by sampling *uniformly* within the union of N-spheres defined by our live points.""" # Initialize a K-D Tree to assist nearest neighbor searches. if self.use_kdtree: kdtree = spatial.KDTree(self.live_u) else: ...
Propose a new live point by sampling *uniformly* within the union of N-spheres defined by our live points.
def subtype_ids(elements, subtype): """ returns the ids of all elements of a list that have a certain type, e.g. show all the nodes that are ``TokenNode``\s. """ return [i for (i, element) in enumerate(elements) if isinstance(element, subtype)]
returns the ids of all elements of a list that have a certain type, e.g. show all the nodes that are ``TokenNode``\s.
def on_exception(self, exception): """An exception occurred in the streaming thread""" logger.error('Exception from stream!', exc_info=True) self.streaming_exception = exception
An exception occurred in the streaming thread
def __constructMetricsModules(self, metricSpecs): """ Creates the required metrics modules Parameters: ----------------------------------------------------------------------- metricSpecs: A sequence of MetricSpec objects that specify which metric modules to instantiate """ if no...
Creates the required metrics modules Parameters: ----------------------------------------------------------------------- metricSpecs: A sequence of MetricSpec objects that specify which metric modules to instantiate
def feature_path_unset(self): """Copy features to memory and remove the association of the feature file.""" if not self.feature_file: raise IOError('No feature file to unset') with open(self.feature_path) as handle: feats = list(GFF.parse(handle)) if len(feat...
Copy features to memory and remove the association of the feature file.
def get_pid(name): """Check if process is running by name.""" if not shutil.which("pidof"): return False try: subprocess.check_output(["pidof", "-s", name]) except subprocess.CalledProcessError: return False return True
Check if process is running by name.
def run(self): """ this is the actual execution of the instrument thread: continuously read values from the probes """ eta = self.settings['noise_strength'] gamma = 2 * np.pi * self.settings['noise_bandwidth'] dt = 1. / self.settings['update frequency'] control =...
this is the actual execution of the instrument thread: continuously read values from the probes
def _write_plist(self, root): """Write plist file based on our generated tree.""" # prettify the XML indent_xml(root) tree = ElementTree.ElementTree(root) with open(self.preferences_file, "w") as prefs_file: prefs_file.write( "<?xml version=\"1.0\" en...
Write plist file based on our generated tree.
def post_unvote(self, post_id): """Action lets you unvote for a post (Requires login). Parameters: post_id (int): """ return self._get('posts/{0}/unvote.json'.format(post_id), method='PUT', auth=True)
Action lets you unvote for a post (Requires login). Parameters: post_id (int):
def restore_state(self): """Restore GUI state from configuration file.""" # restore last source path last_source_path = setting( 'lastSourceDir', self.default_directory, expected_type=str) self.source_directory.setText(last_source_path) # restore path pdf output ...
Restore GUI state from configuration file.
def _ReformatMessageString(self, message_string): """Reformats the message string. Args: message_string (str): message string. Returns: str: message string in Python format() (PEP 3101) style. """ def _PlaceHolderSpecifierReplacer(match_object): """Replaces message string place h...
Reformats the message string. Args: message_string (str): message string. Returns: str: message string in Python format() (PEP 3101) style.
def iter_delimiter(self, byte_size=8192): """ Generalization of the default iter file delimited by '\n'. Note: The newline string can be arbitrarily long; it need not be restricted to a single character. You can also set the read size and control whether or not the newline string is left on th...
Generalization of the default iter file delimited by '\n'. Note: The newline string can be arbitrarily long; it need not be restricted to a single character. You can also set the read size and control whether or not the newline string is left on the end of the iterated lines. Setting newlin...
async def requirements(client: Client, search: str) -> dict: """ GET list of requirements for a given UID/Public key :param client: Client to connect to the api :param search: UID or public key :return: """ return await client.get(MODULE + '/requirements/%s' % search, schema=REQUIREMENTS_SC...
GET list of requirements for a given UID/Public key :param client: Client to connect to the api :param search: UID or public key :return:
def get_stack_frames(error_stack: bool = True) -> list: """ Returns a list of the current stack frames, which are pruned focus on the Cauldron code where the relevant information resides. """ cauldron_path = environ.paths.package() resources_path = environ.paths.resources() frames = ( ...
Returns a list of the current stack frames, which are pruned focus on the Cauldron code where the relevant information resides.
def weave_instance(instance, aspect, methods=NORMAL_METHODS, lazy=False, bag=BrokenBag, **options): """ Low-level weaver for instances. .. warning:: You should not use this directly. :returns: An :obj:`aspectlib.Rollback` object. """ if bag.has(instance): return Nothing entangleme...
Low-level weaver for instances. .. warning:: You should not use this directly. :returns: An :obj:`aspectlib.Rollback` object.
def parse_config_file(config_file, skip_unknown=False): """Parse a Gin config file. Args: config_file: The path to a Gin config file. skip_unknown: A boolean indicating whether unknown configurables and imports should be skipped instead of causing errors (alternatively a list of configurable na...
Parse a Gin config file. Args: config_file: The path to a Gin config file. skip_unknown: A boolean indicating whether unknown configurables and imports should be skipped instead of causing errors (alternatively a list of configurable names to skip if unknown). See `parse_config` for additional ...
def _should_defer(input_layer, args, kwargs): """Checks to see if any of the args are templates.""" for arg in itertools.chain([input_layer], args, six.itervalues(kwargs)): if isinstance(arg, (_DeferredLayer, UnboundVariable)): return True elif (isinstance(arg, collections.Sequence) and not ...
Checks to see if any of the args are templates.
def correlation_plot(self, data): """ Create heatmap of Pearson's correlation coefficient. Parameters ---------- data : pd.DataFrame() Data to display. Returns ------- matplotlib.figure Heatmap. """ # CHECK: Add saved...
Create heatmap of Pearson's correlation coefficient. Parameters ---------- data : pd.DataFrame() Data to display. Returns ------- matplotlib.figure Heatmap.
def _pack_with_custom_ops(dataset, keys, length): """Helper-function for packing a dataset which has already been batched. See pack_dataset() Relies on custom ops which require a custom compiled binary. Faster than _pack_with_tf_ops(), and denser packing. Args: dataset: a dataset containing padded batc...
Helper-function for packing a dataset which has already been batched. See pack_dataset() Relies on custom ops which require a custom compiled binary. Faster than _pack_with_tf_ops(), and denser packing. Args: dataset: a dataset containing padded batches of examples. keys: a list of strings (must have...
def update_from_model_change(self, oldmodel, newmodel, tile): """ Update various internal variables from a model update from oldmodel to newmodel for the tile `tile` """ self._loglikelihood -= self._calc_loglikelihood(oldmodel, tile=tile) self._loglikelihood += self._calc...
Update various internal variables from a model update from oldmodel to newmodel for the tile `tile`
def generic_visit(self, node: AST, dfltChaining: bool = True) -> str: """Default handler, called if no explicit visitor function exists for a node. """ for field, value in ast.iter_fields(node): if isinstance(value, list): for item in value: ...
Default handler, called if no explicit visitor function exists for a node.
def is_link(url, processed, files): """ Determine whether or not a link should be crawled A url should not be crawled if it - Is a file - Has already been crawled Args: url: str Url to be processed processed: list[str] List of urls that have already been crawled Ret...
Determine whether or not a link should be crawled A url should not be crawled if it - Is a file - Has already been crawled Args: url: str Url to be processed processed: list[str] List of urls that have already been crawled Returns: bool If `url` should be crawled
def extract_index(index_data, global_index=False): ''' Instantiates and returns an AllIndex object given a valid index configuration CLI Example: salt myminion boto_dynamodb.extract_index index ''' parsed_data = {} keys = [] for key, value in six.iteritems(index_data): ...
Instantiates and returns an AllIndex object given a valid index configuration CLI Example: salt myminion boto_dynamodb.extract_index index
def get_record_types(self): """Gets the record types available in this object. A record ``Type`` explicitly indicates the specification of an interface to the record. A record may or may not inherit other record interfaces through interface inheritance in which case support of a...
Gets the record types available in this object. A record ``Type`` explicitly indicates the specification of an interface to the record. A record may or may not inherit other record interfaces through interface inheritance in which case support of a record type may not be explicit in the...
def translate_abstract_actions_to_keys(self, abstract): """ Translates a list of tuples ([pretty mapping], [value]) to a list of tuples ([some key], [translated value]) each single item in abstract will undergo the following translation: Example1: we want: "MoveRight": 5.0 ...
Translates a list of tuples ([pretty mapping], [value]) to a list of tuples ([some key], [translated value]) each single item in abstract will undergo the following translation: Example1: we want: "MoveRight": 5.0 possible keys for the action are: ("Right", 1.0), ("Left", -1.0) ...
def prior_to_xarray(self): """Convert prior samples to xarray.""" prior = self.prior # filter posterior_predictive and log_likelihood prior_predictive = self.prior_predictive if prior_predictive is None: prior_predictive = [] elif isinstance(prior_predi...
Convert prior samples to xarray.
def get_model_field_label_and_value(instance, field_name) -> (str, str): """ Returns model field label and value. :param instance: Model instance :param field_name: Model attribute name :return: (label, value) tuple """ label = field_name value = str(getattr(instance, field_name)) fo...
Returns model field label and value. :param instance: Model instance :param field_name: Model attribute name :return: (label, value) tuple
def export(self, name, columns, points): """Write the points to the Cassandra cluster.""" logger.debug("Export {} stats to Cassandra".format(name)) # Remove non number stats and convert all to float (for Boolean) data = {k: float(v) for (k, v) in dict(zip(columns, points)).iteritems() i...
Write the points to the Cassandra cluster.
def create_notebook(self, position=Gtk.PositionType.TOP): """ Function creates a notebook """ notebook = Gtk.Notebook() notebook.set_tab_pos(position) notebook.set_show_border(True) return notebook
Function creates a notebook
def loop(self, sequences=None, outputs=None, non_sequences=None, block=None, **kwargs): """ Start a loop. Usage: ``` with deepy.graph.loop(sequences={"x": x}, outputs={"o": None}) as vars: vars.o = vars.x + 1 loop_outputs = deepy.graph.loop_outputs() r...
Start a loop. Usage: ``` with deepy.graph.loop(sequences={"x": x}, outputs={"o": None}) as vars: vars.o = vars.x + 1 loop_outputs = deepy.graph.loop_outputs() result = loop_outputs.o ```
def groups(self): """Get the list of Groups (by dn) that the bound CSH LDAP member object is in. """ group_list = [] all_groups = self.get('memberof') for group_dn in all_groups: if self.__ldap_group_ou__ in group_dn: group_list.append(group_dn...
Get the list of Groups (by dn) that the bound CSH LDAP member object is in.
def match(self, table, nomatch=0): """ Make a vector of the positions of (first) matches of its first argument in its second. Only applicable to single-column categorical/string frames. :param List table: the list of items to match against :param int nomatch: value that should ...
Make a vector of the positions of (first) matches of its first argument in its second. Only applicable to single-column categorical/string frames. :param List table: the list of items to match against :param int nomatch: value that should be returned when there is no match. :returns: a...
def min(self, array, role = None): """ Return the minimum value of ``array`` for the entity members. ``array`` must have the dimension of the number of persons in the simulation If ``role`` is provided, only the entity member with the given role are taken into account. ...
Return the minimum value of ``array`` for the entity members. ``array`` must have the dimension of the number of persons in the simulation If ``role`` is provided, only the entity member with the given role are taken into account. Example: >>> salaries = household.mem...
def run_filter(vrn_file, align_bam, ref_file, data, items): """Filter and annotate somatic VCFs with damage/bias artifacts on low frequency variants. Moves damage estimation to INFO field, instead of leaving in FILTER. """ if not should_filter(items) or not vcfutils.vcf_has_variants(vrn_file): ...
Filter and annotate somatic VCFs with damage/bias artifacts on low frequency variants. Moves damage estimation to INFO field, instead of leaving in FILTER.
def load(path, group=None, sel=None, unpack=False): """ Loads an HDF5 saved with `save`. This function requires the `PyTables <http://www.pytables.org/>`_ module to be installed. Parameters ---------- path : string Filename from which to load the data. group : string or list ...
Loads an HDF5 saved with `save`. This function requires the `PyTables <http://www.pytables.org/>`_ module to be installed. Parameters ---------- path : string Filename from which to load the data. group : string or list Load a specific group in the HDF5 hierarchy. If `group` is...
def run(self): """ Ping entries to a directory in a thread. """ logger = getLogger('zinnia.ping.directory') socket.setdefaulttimeout(self.timeout) for entry in self.entries: reply = self.ping_entry(entry) self.results.append(reply) logg...
Ping entries to a directory in a thread.
def get_summary(profile_block_list, maxlines=20): """ References: https://github.com/rkern/line_profiler """ time_list = [get_block_totaltime(block) for block in profile_block_list] time_list = [time if time is not None else -1 for time in time_list] blockid_list = [get_block_id(block) f...
References: https://github.com/rkern/line_profiler
def get_header(self, idx, formatted=False): """ Return a list of the variable names at the given indices """ header = self._uname if not formatted else self._fname return [header[x] for x in idx]
Return a list of the variable names at the given indices
def SendKey(key: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate typing a key. key: int, a value in class `Keys`. """ keybd_event(key, 0, KeyboardEventFlag.KeyDown | KeyboardEventFlag.ExtendedKey, 0) keybd_event(key, 0, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey, 0...
Simulate typing a key. key: int, a value in class `Keys`.
def _set_port(self, v, load=False): """ Setter method for port, mapped from YANG variable /qos/cpu/slot/port_group/port (container) If this variable is read-only (config: false) in the source YANG file, then _set_port is considered as a private method. Backends looking to populate this variable shou...
Setter method for port, mapped from YANG variable /qos/cpu/slot/port_group/port (container) If this variable is read-only (config: false) in the source YANG file, then _set_port is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_port() dir...
def open(self, session, resource_name, access_mode=constants.AccessModes.no_lock, open_timeout=constants.VI_TMO_IMMEDIATE): """Opens a session to the specified resource. Corresponds to viOpen function of the VISA library. :param session: Resource Manager session ...
Opens a session to the specified resource. Corresponds to viOpen function of the VISA library. :param session: Resource Manager session (should always be a session returned from open_default_resource_manager()). :param resource_name: Unique symbo...
def QA_indicator_ASI(DataFrame, M1=26, M2=10): """ LC=REF(CLOSE,1); AA=ABS(HIGH-LC); BB=ABS(LOW-LC); CC=ABS(HIGH-REF(LOW,1)); DD=ABS(LC-REF(OPEN,1)); R=IF(AA>BB AND AA>CC,AA+BB/2+DD/4,IF(BB>CC AND BB>AA,BB+AA/2+DD/4,CC+DD/4)); X=(CLOSE-LC+(CLOSE-OPEN)/2+LC-REF(OPEN,1)); SI=16*X/R*MAX...
LC=REF(CLOSE,1); AA=ABS(HIGH-LC); BB=ABS(LOW-LC); CC=ABS(HIGH-REF(LOW,1)); DD=ABS(LC-REF(OPEN,1)); R=IF(AA>BB AND AA>CC,AA+BB/2+DD/4,IF(BB>CC AND BB>AA,BB+AA/2+DD/4,CC+DD/4)); X=(CLOSE-LC+(CLOSE-OPEN)/2+LC-REF(OPEN,1)); SI=16*X/R*MAX(AA,BB); ASI:SUM(SI,M1); ASIT:MA(ASI,M2);
def create_transform_job(self, config, wait_for_completion=True, check_interval=30, max_ingestion_time=None): """ Create a transform job :param config: the config for transform job :type config: dict :param wait_for_completion: if the program should ...
Create a transform job :param config: the config for transform job :type config: dict :param wait_for_completion: if the program should keep running until job finishes :type wait_for_completion: bool :param check_interval: the time interval in seconds which the operator ...
def condition_on_par_knowledge(cov,par_knowledge_dict): """ experimental function to include conditional prior information for one or more parameters in a full covariance matrix """ missing = [] for parnme in par_knowledge_dict.keys(): if parnme not in cov.row_names: missing.ap...
experimental function to include conditional prior information for one or more parameters in a full covariance matrix
def infer_isinstance(callnode, context=None): """Infer isinstance calls :param nodes.Call callnode: an isinstance call :param InferenceContext: context for call (currently unused but is a common interface for inference) :rtype nodes.Const: Boolean Const value of isinstance call :raises Use...
Infer isinstance calls :param nodes.Call callnode: an isinstance call :param InferenceContext: context for call (currently unused but is a common interface for inference) :rtype nodes.Const: Boolean Const value of isinstance call :raises UseInferenceDefault: If the node cannot be inferred
def format_prefix(filename, sres): """ Prefix to a filename in the directory listing. This is to make the listing similar to an output of "ls -alh". """ try: pwent = pwd.getpwuid(sres.st_uid) user = pwent.pw_name except KeyError: user = sres.st_uid try: grent = grp.getgrgid(sres.st_gid) ...
Prefix to a filename in the directory listing. This is to make the listing similar to an output of "ls -alh".
def _prev_month(self): """Updated calendar to show the previous month.""" self._canvas.place_forget() self._date = self._date - self.timedelta(days=1) self._date = self.datetime(self._date.year, self._date.month, 1) self._build_calendar()
Updated calendar to show the previous month.
def get_oc_api_token(): """ Get token of user logged in OpenShift cluster :return: str, API token """ oc_command_exists() try: return run_cmd(["oc", "whoami", "-t"], return_output=True).rstrip() # remove '\n' except subprocess.CalledProcessError as ex: raise ConuException("...
Get token of user logged in OpenShift cluster :return: str, API token
def _updateB(oldB, B, W, degrees, damping, inds, backinds): # pragma: no cover '''belief update function.''' for j,d in enumerate(degrees): kk = inds[j] bk = backinds[j] if d == 0: B[kk,bk] = -np.inf continue belief = W[kk,bk] + W[j] oldBj = oldB[j] if d == oldBj.s...
belief update function.
def Record(self, obj): """Records the object as visited. Args: obj: visited object. Returns: True if the object hasn't been previously visited or False if it has already been recorded or the quota has been exhausted. """ if len(self._visit_recorder_objects) >= _MAX_VISIT_OBJECTS:...
Records the object as visited. Args: obj: visited object. Returns: True if the object hasn't been previously visited or False if it has already been recorded or the quota has been exhausted.
def copy_bulma_files(self): """ Copies Bulma static files from package's static/bulma into project's STATIC_ROOT/bulma """ original_bulma_dir = os.path.join( os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'static', 'bulma' ...
Copies Bulma static files from package's static/bulma into project's STATIC_ROOT/bulma
def ui_extensions(self): """ Provides access to UI extensions management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/ui-extensions :return: :class:`EnvironmentUIExtensionsProxy <contentful_management.ui_extensions_pro...
Provides access to UI extensions management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/ui-extensions :return: :class:`EnvironmentUIExtensionsProxy <contentful_management.ui_extensions_proxy.EnvironmentUIExtensionsProxy>` object. ...
def _get_pathcost_func( name: str ) -> Callable[[int, int, int, int, Any], float]: """Return a properly cast PathCostArray callback.""" return ffi.cast( # type: ignore "TCOD_path_func_t", ffi.addressof(lib, name) )
Return a properly cast PathCostArray callback.