Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
389,100
def _build_action_bound_constraints_table(self): self.action_lower_bound_constraints = {} self.action_upper_bound_constraints = {} for name, preconds in self.local_action_preconditions.items(): for precond in preconds: expr_type = precond.etype ...
Builds the lower and upper action bound constraint expressions.
389,101
def insert(self, key, value, ttl=0, format=None, persist_to=0, replicate_to=0): return _Base.insert(self, key, value, ttl=ttl, format=format, persist_to=persist_to, replicate_to=replicate_to)
Store an object in Couchbase unless it already exists. Follows the same conventions as :meth:`upsert` but the value is stored only if it does not exist already. Conversely, the value is not stored if the key already exists. Notably missing from this method is the `cas` parameter, this ...
389,102
def cluster(self, method, **kwargs): from eqcorrscan.utils import clustering tribes = [] func = getattr(clustering, method) if method in [, ]: cat = Catalog([t.event for t in self.templates]) groups = func(cat, **kwargs) for group in groups: ...
Cluster the tribe. Cluster templates within a tribe: returns multiple tribes each of which could be stacked. :type method: str :param method: Method of stacking, see :mod:`eqcorrscan.utils.clustering` :return: List of tribes. .. rubric:: Example
389,103
def get_box_files(self, box_key): uri = .join([self.api_uri, self.boxes_suffix, box_key, self.files_suffix ]) return self._req(, uri)
Gets to file infos in a single box. Args: box_key key for the file return (status code, list of file info dicts)
389,104
def get_reply_visibility(self, status_dict): visibility = ("public", "unlisted", "private", "direct") default_visibility = visibility.index(self.default_visibility) status_visibility = visibility.index(status_dict["visibility"]) return visibility[max(default_visibilit...
Given a status dict, return the visibility that should be used. This behaves like Mastodon does by default.
389,105
def has_args(): no_args_syntax = args_syntax = no_args_syntax + args, no_args = [(-1,-1)], [(-1,-1)] for i, line in enumerate(Overload.traceback_lines()): if args_syntax in line: args.append((i, line.find(args_syntax))) if no_args_syntax...
returns true if the decorator invocation had arguments passed to it before being sent a function to decorate
389,106
def getoptS(X, Y, M_E, E): n, r = X.shape C = np.dot(np.dot(X.T, M_E), Y) C = C.flatten() A = np.zeros((r * r, r * r)) for i in range(r): for j in range(r): ind = j * r + i temp = np.dot( np.dot(X.T, np.dot(X[:, i, None], Y[:, j, None]...
Find Sopt given X, Y
389,107
def clear_plot(self): self.tab_plot.clear() self.tab_plot.draw() self.save_plot.set_enabled(False)
Clear plot display.
389,108
def get_score(self, fmap=, importance_type=): if getattr(self, , None) is not None and self.booster not in {, }: raise ValueError( .format(self.booster)) allowed_importance_types = [, , , , ] if importance_type not in allowed_importance_types: ...
Get feature importance of each feature. Importance type can be defined as: * 'weight': the number of times a feature is used to split the data across all trees. * 'gain': the average gain across all splits the feature is used in. * 'cover': the average coverage across all splits the fea...
389,109
def power_down(self): GPIO.output(self._pd_sck, False) GPIO.output(self._pd_sck, True) time.sleep(0.01) return True
turn off the HX711 :return: always True :rtype bool
389,110
def qop(self): def on_update(header_set): if not header_set and in self: del self[] elif header_set: self[] = header_set.to_header() return parse_set_header(self.get(), on_update)
Indicates what "quality of protection" the client has applied to the message for HTTP digest auth.
389,111
def kmer_counter(seq, k=4): if isinstance(seq, basestring): return Counter(generate_kmers(seq, k))
Return a sequence of all the unique substrings (k-mer or q-gram) within a short (<128 symbol) string Used for algorithms like UniqTag for genome unique identifier locality sensitive hashing. jellyfish is a C implementation of k-mer counting If seq is a string generate a sequence of k-mer string If se...
389,112
def _allocate_address(self, instance, network_ids): with OpenStackCloudProvider.__node_start_lock: try: free_ips = [ip for ip in self.nova_client.floating_ips.list() if not ip.fixed_ip] if not free_ips: free_ips.append(sel...
Allocates a floating/public ip address to the given instance. :param instance: instance to assign address to :param list network_id: List of IDs (as strings) of networks where to request allocation the floating IP. :return: public ip address
389,113
def DeleteDatabase(self, database_link, options=None): if options is None: options = {} path = base.GetPathFromLink(database_link) database_id = base.GetResourceIdOrFullNameFromLink(database_link) return self.DeleteResource(path, ,...
Deletes a database. :param str database_link: The link to the database. :param dict options: The request options for the request. :return: The deleted Database. :rtype: dict
389,114
def get_masters(ppgraph): masters = {} for protein, peps in ppgraph.items(): ismaster = True peps = set(peps) multimaster = set() for subprotein, subpeps in ppgraph.items(): if protein == subprotein: continue if peps.issubset(subpeps):...
From a protein-peptide graph dictionary (keys proteins, values peptides), return master proteins aka those which have no proteins whose peptides are supersets of them. If shared master proteins are found, report only the first, we will sort the whole proteingroup later anyway. In that case, the mast...
389,115
def construct_codons_dict(alphabet_file = None): c_symbol = line.split(, 1)[0].strip(.join(protected_symbols)) if symbol in codons_dict.keys(): print symbol + " is already used as an symbol for codons: " print codons_dict...
Generate the sub_codons_right dictionary of codon suffixes. syntax of custom alphabet_files: char: list,of,amino,acids,or,codons,separated,by,commas Parameters ---------- alphabet_file : str File name for a custom alphabet definition. If no file is provided, the ...
389,116
def singleton(*args, **kwargs): def decorator(cls: type) -> Callable[[], object]: if issubclass(type(cls), _SingletonMetaClassBase): raise TypeError() box = _Box() factory = None lock = Lock() def metaclass_call(_): if box.value is None: ...
a lazy init singleton pattern. usage: ``` py @singleton() class X: ... ``` `args` and `kwargs` will pass to ctor of `X` as args.
389,117
def get_icloud_folder_location(): yosemite_icloud_path = icloud_home = os.path.expanduser(yosemite_icloud_path) if not os.path.isdir(icloud_home): error() return str(icloud_home)
Try to locate the iCloud Drive folder. Returns: (str) Full path to the iCloud Drive folder.
389,118
def unassigned(data, as_json=False): no_subusers = set() if not isinstance(data, list): return format_ret(no_subusers, as_json=as_json) for current in data: num_subusers = len(current["subusers"]) if num_subusers == 0: current_ip = current["ip"] no_sub...
https://sendgrid.com/docs/API_Reference/api_v3.html#ip-addresses The /ips rest endpoint returns information about the IP addresses and the usernames assigned to an IP unassigned returns a listing of the IP addresses that are allocated but have 0 users assigned data (response.b...
389,119
def count_objects_by_tags(self, metric, scraper_config): config = self.object_count_params[metric.name] metric_name = "{}.{}".format(scraper_config[], config[]) object_counter = Counter() for sample in metric.samples: tags = [ self._label_to_tag(l, s...
Count objects by whitelisted tags and submit counts as gauges.
389,120
def _set_copy(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=copy.copy, is_container=, presence=False, yang_name="copy", rest_name="copy", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u: {u...
Setter method for copy, mapped from YANG variable /copy (container) If this variable is read-only (config: false) in the source YANG file, then _set_copy is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_copy() directly.
389,121
def has_subdirectories(path, include, exclude, show_all): try: return len( listdir(path, include, exclude, show_all, folders_only=True) ) > 1 except (IOError, OSError): return False
Return True if path has subdirectories
389,122
def rvs(self, size=1, param=None): if param is not None: dtype = [(param, float)] else: dtype = [(p, float) for p in self.params] arr = numpy.zeros(size, dtype=dtype) for (p,_) in dtype: log_high = numpy.log10(self._bounds[p][0]) ...
Gives a set of random values drawn from this distribution. Parameters ---------- size : {1, int} The number of values to generate; default is 1. param : {None, string} If provided, will just return values for the given parameter. Otherwise, returns ra...
389,123
def gifs_categories_category_get(self, api_key, category, **kwargs): kwargs[] = True if kwargs.get(): return self.gifs_categories_category_get_with_http_info(api_key, category, **kwargs) else: (data) = self.gifs_categories_category_get_with_http_info(api_key, cat...
Category Tags Endpoint. Returns a list of tags for a given category. NOTE `limit` and `offset` must both be set; otherwise they're ignored. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked whe...
389,124
def get_hash(self): if self.__index_hash: return self.__index_hash key = self.request.method key += URLHelper.get_protocol(self.request.url) key += URLHelper.get_subdomain(self.request.url) key += URLHelper.get_hostname(self.request.url) key += URL...
Generate and return the dict index hash of the given queue item. Note: Cookies should not be included in the hash calculation because otherwise requests are crawled multiple times with e.g. different session keys, causing infinite crawling recursion. Note: ...
389,125
def page_strip(page, versioned): page.pop(, None) contents_key = versioned and or contents = page.get(contents_key, ()) if versioned: keys = [] for k in contents: if k[]: keys.append((k[], k[], True)) else: keys.ap...
Remove bits in content results to minimize memory utilization. TODO: evolve this to a key filter on metadata, like date
389,126
def _wrapinstance(ptr, base=None): assert isinstance(ptr, long), "Argument must be of type <long>" assert (base is None) or issubclass(base, Qt.QtCore.QObject), ( "Argument must be of type <QObject>") if Qt.IsPyQt4 or Qt.IsPyQt5: func = getattr(Qt, "_sip").wrapinstance elif Qt.I...
Enable implicit cast of pointer to most suitable class This behaviour is available in sip per default. Based on http://nathanhorne.com/pyqtpyside-wrap-instance Usage: This mechanism kicks in under these circumstances. 1. Qt.py is using PySide 1 or 2. 2. A `base` argument is not pr...
389,127
def _init_client(): global client, path_prefix if client is not None: return etcd_kwargs = { : __opts__.get(, ), : __opts__.get(, 2379), : __opts__.get(, ), : __opts__.get(, True), : __opts__.get(, False), : __opts__.get(,...
Setup client and init datastore.
389,128
def logtrick_minimizer(minimizer): r @wraps(minimizer) def new_minimizer(fun, x0, jac=True, bounds=None, **minimizer_kwargs): if bounds is None: return minimizer(fun, x0, jac=jac, bounds=bounds, **minimizer_kwargs) logx, expx, gradx, bounds = _logtr...
r""" Log-Trick decorator for optimizers. This decorator implements the "log trick" for optimizing positive bounded variables. It will apply this trick for any variables that correspond to a Positive() bound. Examples -------- >>> from scipy.optimize import minimize as sp_min >>> from ....
389,129
def get_path(self): md5_hash = hashlib.md5(self.task_id.encode()).hexdigest() logger.debug(, md5_hash, self.task_id) return os.path.join(self.temp_dir, str(self.unique.value), md5_hash)
Returns a temporary file path based on a MD5 hash generated with the task's name and its arguments
389,130
def diri(table): t = [] for i in table: a = [j + 1 for j in i] t.append(np.ndarray.tolist(np.random.mtrand.dirichlet(a))) return t
from SparCC - "randomly draw from the corresponding posterior Dirichlet distribution with a uniform prior"
389,131
def _Build(self, storage_file): self._index = {} for event_tag in storage_file.GetEventTags(): self.SetEventTag(event_tag)
Builds the event tag index. Args: storage_file (BaseStorageFile): storage file.
389,132
def process_tls(self, data, name): ret = [] try: lines = [x.strip() for x in data.split()] for idx, line in enumerate(lines): if line == : continue sub = self.process_host(line, name, idx) if sub is not...
Remote TLS processing - one address:port per line :param data: :param name: :return:
389,133
def get_sdk_dir(self): try: return self._sdk_dir except AttributeError: sdk_dir = self.find_sdk_dir() self._sdk_dir = sdk_dir return sdk_dir
Return the MSSSDK given the version string.
389,134
def fetch(bank, key): c_key = .format(bank, key) try: _, value = api.kv.get(c_key) if value is None: return {} return __context__[].loads(value[]) except Exception as exc: raise SaltCacheError( .format( c_key, exc ) ...
Fetch a key value.
389,135
def pluralize(data_type): known = { u"address": u"addresses", u"company": u"companies" } if data_type in known.keys(): return known[data_type] else: return u"%ss" % data_type
adds s to the data type or the correct english plural form
389,136
def __get_pid_by_scanning(self): dwProcessId = None dwThreadId = self.get_tid() with win32.CreateToolhelp32Snapshot(win32.TH32CS_SNAPTHREAD) as hSnapshot: te = win32.Thread32First(hSnapshot) while te is not None: if te.th32ThreadID == dwThreadId: ...
Internally used by get_pid().
389,137
def create_app(config_name): app = Flask(__name__) app.config.from_object(CONFIG[config_name]) BOOTSTRAP.init_app(app) from flask_seguro.controllers.main import main as main_blueprint app.register_blueprint(main_blueprint) return app
Factory Function
389,138
async def promote_chat_member(self, chat_id: typing.Union[base.Integer, base.String], user_id: base.Integer, can_change_info: typing.Union[base.Boolean, None] = None, can_post_messages: typing.Union[base.Boolean, None]...
Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Pass False for all boolean parameters to demote a user. Source: https://core.telegram.org/bots/api#promotechatmembe...
389,139
def copy( ctx, opts, owner_repo_package, destination, skip_errors, wait_interval, no_wait_for_sync, sync_attempts, ): owner, source, slug = owner_repo_package click.echo( "Copying %(slug)s package from %(source)s to %(dest)s ... " % { "slug": cli...
Copy a package to another repository. This requires appropriate permissions for both the source repository/package and the destination repository. - OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the REPO name where the package is stored, and the PACKAGE name (slug) of the pac...
389,140
def _has_fileno(stream): try: stream.fileno() except (AttributeError, OSError, IOError, io.UnsupportedOperation): return False return True
Returns whether the stream object seems to have a working fileno() Tells whether _redirect_stderr is likely to work. Parameters ---------- stream : IO stream object Returns ------- has_fileno : bool True if stream.fileno() exists and doesn't raise OSError or UnsupportedOpe...
389,141
def log_interp1d(self, xx, yy, kind=): logx = np.log10(xx) logy = np.log10(yy) lin_interp = interp1d(logx, logy, kind=kind) log_interp = lambda zz: np.power(10.0, lin_interp(np.log10(zz))) return log_interp
Performs a log space 1d interpolation. :param xx: the x values. :param yy: the y values. :param kind: the type of interpolation to apply (as per scipy interp1d) :return: the interpolation function.
389,142
def protocol_version_to_kmip_version(value): if not isinstance(value, ProtocolVersion): return None if value.major == 1: if value.minor == 0: return enums.KMIPVersion.KMIP_1_0 elif value.minor == 1: return enums.KMIPVersion.KMIP_1_1 elif value.minor ...
Convert a ProtocolVersion struct to its KMIPVersion enumeration equivalent. Args: value (ProtocolVersion): A ProtocolVersion struct to be converted into a KMIPVersion enumeration. Returns: KMIPVersion: The enumeration equivalent of the struct. If the struct cannot be co...
389,143
def plot_element_profile(self, element, comp, show_label_index=None, xlim=5): plt = pretty_plot(12, 8) pd = self._pd evolution = pd.get_element_profile(element, comp) num_atoms = evolution[0]["reaction"].reactants[0].num_atoms element_energy ...
Draw the element profile plot for a composition varying different chemical potential of an element. X value is the negative value of the chemical potential reference to elemental chemical potential. For example, if choose Element("Li"), X= -(µLi-µLi0), which corresponds to the voltage ve...
389,144
def create_presentation(self): if not self.overwrite and os.path.exists(self.output): raise ConversionError("File %s already exist and --overwrite not specified" % self.output) video = self.download_video() raw_slides = self.download_slides() png_...
Create the presentation. The audio track is mixed with the slides. The resulting file is saved as self.output DownloadError is raised if some resources cannot be fetched. ConversionError is raised if the final video cannot be created.
389,145
async def getStickerSet(self, name): p = _strip(locals()) return await self._api_request(, _rectify(p))
See: https://core.telegram.org/bots/api#getstickerset
389,146
def fromDatetime(klass, dtime): self = klass.__new__(klass) if dtime.tzinfo is not None: self._time = dtime.astimezone(FixedOffset(0, 0)).replace(tzinfo=None) else: self._time = dtime self.resolution = datetime.timedelta.resolution return self
Return a new Time instance from a datetime.datetime instance. If the datetime instance does not have an associated timezone, it is assumed to be UTC.
389,147
def fit(self, Z, **fit_params): Zt, fit_params = self._pre_transform(Z, **fit_params) self.steps[-1][-1].fit(Zt, **fit_params) Zt.unpersist() return self
Fit all the transforms one after the other and transform the data, then fit the transformed data using the final estimator. Parameters ---------- Z : ArrayRDD, TupleRDD or DictRDD Input data in blocked distributed format. Returns ------- self : Spark...
389,148
def request(self, method, url, params=None, **aio_kwargs): oparams = { : self.consumer_key, : sha1(str(RANDOM()).encode()).hexdigest(), : self.signature.name, : str(int(time.time())), : self.version, } oparams.update(params or ...
Make a request to provider.
389,149
def heading_title(self): art_title = self.article.root.xpath()[0] article_title = deepcopy(art_title) article_title.tag = article_title.attrib[] = article_title.attrib[] = return article_title
Makes the Article Title for the Heading. Metadata element, content derived from FrontMatter
389,150
def create_new_dispatch(self, dispatch): self._validate_uuid(dispatch.dispatch_id) url = "/notification/v1/dispatch" post_response = NWS_DAO().postURL( url, self._write_headers(), self._json_body(dispatch.json_data())) if post_response.status != 200: ...
Create a new dispatch :param dispatch: is the new dispatch that the client wants to create
389,151
def _get_function_name(self, fn, default="None"): if fn is None: fn_name = default else: fn_name = fn.__name__ return fn_name
Return name of function, using default value if function not defined
389,152
def _get_ssh_client(self): return ipa_utils.get_ssh_client( self.instance_ip, self.ssh_private_key_file, self.ssh_user, timeout=self.timeout )
Return a new or existing SSH client for given ip.
389,153
def default(self, request, exception): self.log(format_exc()) try: url = repr(request.url) except AttributeError: url = "unknown" response_message = "Exception occurred while handling uri: %s" logger.exception(response_message, url) if i...
Provide a default behavior for the objects of :class:`ErrorHandler`. If a developer chooses to extent the :class:`ErrorHandler` they can provide a custom implementation for this method to behave in a way they see fit. :param request: Incoming request :param exception: Exception ...
389,154
def _nth_of_quarter(self, nth, day_of_week): if nth == 1: return self.first_of("quarter", day_of_week) dt = self.replace(self.year, self.quarter * 3, 1) last_month = dt.month year = dt.year dt = dt.first_of("quarter") for i in range(nth - (1 if dt.da...
Modify to the given occurrence of a given day of the week in the current quarter. If the calculated occurrence is outside, the scope of the current quarter, then return False and no modifications are made. Use the supplied consts to indicate the desired day_of_week, ex. pendulum.MONDAY. ...
389,155
def add(self, element, multiplicity=1): if multiplicity < 1: raise ValueError("Multiplicity must be positive") self._elements[element] += multiplicity self._total += multiplicity
Adds an element to the multiset. >>> ms = Multiset() >>> ms.add('a') >>> sorted(ms) ['a'] An optional multiplicity can be specified to define how many of the element are added: >>> ms.add('b', 2) >>> sorted(ms) ['a', 'b', 'b'] This extends the ...
389,156
def _unpack_basis_label_or_index(self, label_or_index): self._check_basis_label_type(label_or_index) if isinstance(label_or_index, str): label = label_or_index try: ind = self.basis_labels.index(label) except ...
return tuple (label, ind) from `label_or_index` If `label_or_int` is a :class:`.SymbolicLabelBase` sub-instance, it will be stored in the `label` attribute, and the `ind` attribute will return the value of the label's :attr:`.FockIndex.fock_index` attribute. No checks are performed for...
389,157
def p_primary_expr_no_brace_4(self, p): if isinstance(p[2], self.asttypes.GroupingOp): p[0] = p[2] else: p[0] = self.asttypes.GroupingOp(expr=p[2]) p[0].setpos(p)
primary_expr_no_brace : LPAREN expr RPAREN
389,158
def get_accent_string(string): accents = list(filter(lambda accent: accent != Accent.NONE, map(get_accent_char, string))) return accents[-1] if accents else Accent.NONE
Get the first accent from the right of a string.
389,159
def is_modified(self): if len(self.__modified_data__) or len(self.__deleted_fields__): return True for value in self.__original_data__.values(): try: if value.is_modified(): return True except AttributeError: ...
Returns whether model is modified or not
389,160
def ajax_preview(request, **kwargs): data = { "html": render_to_string("pinax/blog/_preview.html", { "content": parse(request.POST.get("markup")) }) } return JsonResponse(data)
Currently only supports markdown
389,161
def from_array(self, coeffs, r0, errors=None, normalization=, csphase=1, lmax=None, copy=True): if _np.iscomplexobj(coeffs): raise TypeError() if type(normalization) != str: raise ValueError( ...
Initialize the class with spherical harmonic coefficients from an input array. Usage ----- x = SHMagCoeffs.from_array(array, r0, [errors, normalization, csphase, lmax, copy]) Returns ------- x : SHMagCoeffs class in...
389,162
def is_complete(self): return all(p.name in self.values for p in self.parameters if p.required)
Do all required parameters have values?
389,163
def get_assessment_part_item_session(self, *args, **kwargs): if not self.supports_assessment_part_lookup(): raise errors.Unimplemented() if self._proxy_in_args(*args, **kwargs): raise errors.InvalidArgument() return sessions.AssessmentPartItemSession(r...
Gets the ``OsidSession`` associated with the assessment part item service. return: (osid.assessment.authoring.AssessmentPartItemSession) - an ``AssessmentPartItemSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_assessment_part_ite...
389,164
def create_list_stories( list_id_stories, number_of_stories, shuffle, max_threads ): list_stories = [] with ThreadPoolExecutor(max_workers=max_threads) as executor: futures = { executor.submit(get_story, new) for new in list_id_stories[:number_of_stories] } ...
Show in a formatted way the stories for each item of the list.
389,165
def GetAll(alias=None,location=None,session=None): if not alias: alias = clc.v2.Account.GetAlias(session=session) policies = [] policy_resp = clc.v2.API.Call(, % alias,{},session=session) for k in policy_resp: r_val = policy_resp[k] for r in r_val: if r.get(): if location and r[].lower()!=lo...
Gets a list of anti-affinity policies within a given account. https://t3n.zendesk.com/entries/44657214-Get-Anti-Affinity-Policies >>> clc.v2.AntiAffinity.GetAll() [<clc.APIv2.anti_affinity.AntiAffinity object at 0x10c65e910>, <clc.APIv2.anti_affinity.AntiAffinity object at 0x10c65ec90>]
389,166
def conversations_replies(self, *, channel: str, ts: str, **kwargs) -> SlackResponse: kwargs.update({"channel": channel, "ts": ts}) return self.api_call("conversations.replies", http_verb="GET", params=kwargs)
Retrieve a thread of messages posted to a conversation Args: channel (str): Conversation ID to fetch thread from. e.g. 'C1234567890' ts (str): Unique identifier of a thread's parent message. e.g. '1234567890.123456'
389,167
def _find_value(key, *args): for arg in args: v = _get_value(arg, key) if v is not None: return v
Find a value for 'key' in any of the objects given as 'args
389,168
def initialize(self): mkdir_p(self.archive_path) mkdir_p(self.bin_path) mkdir_p(self.codebase_path) mkdir_p(self.input_basepath)
Create the laboratory directories.
389,169
def propose_value(self, value): if self.proposed_value is None: self.proposed_value = value if self.leader: self.current_accept_msg = Accept(self.network_uid, self.proposal_id, value) return self.current_accept_msg
Sets the proposal value for this node iff this node is not already aware of a previous proposal value. If the node additionally believes itself to be the current leader, an Accept message will be returned
389,170
def handle_exc(exc): err = ERRORS_TABLE.get(exc.pgcode) if err: abort(exceptions.InvalidQueryParams(**{ : err, : , })) abort(exceptions.DatabaseUnavailable)
Given a database exception determine how to fail Attempt to lookup a known error & abort on a meaningful error. Otherwise issue a generic DatabaseUnavailable exception. :param exc: psycopg2 exception
389,171
def is_unwrapped(f): try: g = look_up(object_name(f)) return g != f and unwrap(g) == f except (AttributeError, TypeError, ImportError): return False
If `f` was imported and then unwrapped, this function might return True. .. |is_unwrapped| replace:: :py:func:`is_unwrapped`
389,172
def put_metadata(self, key, value, namespace=): entity = self.get_trace_entity() if entity and entity.sampled: entity.put_metadata(key, value, namespace)
Add metadata to the current active trace entity. Metadata is not indexed but can be later retrieved by BatchGetTraces API. :param str namespace: optional. Default namespace is `default`. It must be a string and prefix `AWS.` is reserved. :param str key: metadata key under sp...
389,173
def to_json(self): res = dict() res[] = self.count res[] = self.messages res[] = self.forced res[] = self.keyboard res[] = list() for item in self.entities: res[].append(item.to_json()) res[] = self.forced_message return res
Serialize object to json dict :return: dict
389,174
def page_url(self) -> str: url = self.attributes[] assert isinstance(url, str) return url
(:class:`str`) The canonical url of the page.
389,175
def main(): opts = docopt(__doc__, version="cast 0.1") cast = pychromecast.PyChromecast(CHROMECAST_HOST) ramp = cast.get_protocol(pychromecast.PROTOCOL_RAMP) time.sleep(SLEEP_TIME) if ramp is None: print return 1 if opts[]: ramp.next() elif opts[]: ...
Read the options given on the command line and do the required actions. This method is used in the entry_point `cast`.
389,176
def batch(self, timelimit=None): from .launcher import BatchLauncher prev_dir = os.path.join(*self.workdir.split(os.path.sep)[:-1]) prev_dir = os.path.join(os.path.sep, prev_dir) workdir = os.path.join(prev_dir, os.path.basename(self.workdir) + "_batch") return...
Run the flow in batch mode, return exit status of the job script. Requires a manager.yml file and a batch_adapter adapter. Args: timelimit: Time limit (int with seconds or string with time given with the slurm convention: "days-hours:minutes:seconds"). If timelimit is None, the ...
389,177
def describe_change_set(awsclient, change_set_name, stack_name): client = awsclient.get_client() status = None while status not in [, ]: response = client.describe_change_set( ChangeSetName=change_set_name, StackName=stack_name) status = response[] ...
Print out the change_set to console. This needs to run create_change_set first. :param awsclient: :param change_set_name: :param stack_name:
389,178
def rpc_get_usages(self, filename, source, offset): line, column = pos_to_linecol(source, offset) uses = run_with_debug(jedi, , source=source, line=line, column=column, path=filename, encoding=) if uses is None: ret...
Return the uses of the symbol at offset. Returns a list of occurrences of the symbol, as dicts with the fields name, filename, and offset.
389,179
def birch(args): p = OptionParser(birch.__doc__) opts, args, iopts = p.set_image_options(args, figsize="8x6") if len(args) != 2: sys.exit(not p.print_help()) seqids, layout = args fig = plt.figure(1, (iopts.w, iopts.h)) root = fig.add_axes([0, 0, 1, 1]) K = Karyotype(fig, roo...
%prog birch seqids layout Plot birch macro-synteny, with an embedded phylogenetic tree to the right.
389,180
def p_DictionaryMember(p): p[0] = model.DictionaryMember(type=p[1], name=p[2], default=p[3])
DictionaryMember : Type IDENTIFIER Default ";"
389,181
def url(self): return urlresolvers.reverse( "admin:%s_%s_change" % (self.content_type.app_label, self.content_type.model), args = (self.get_object().uid,))
Return the admin url of the object.
389,182
def _reprJSON(self): return {: (self.spectrumRef, self.activation, self.isolationWindow, self.selectedIonList ) }
Returns a JSON serializable represenation of a ``MzmlPrecursor`` class instance. Use :func:`maspy.core.MzmlPrecursor._fromJSON()` to generate a new ``MzmlPrecursor`` instance from the return value. :returns: a JSON serializable python object
389,183
def _fast_read(self, infile): infile.seek(0) return(int(infile.read().decode().strip()))
Function for fast reading from sensor files.
389,184
def load_directory(self, top_path, followlinks): for dir_name, child_dirs, child_files in os.walk(top_path, followlinks=followlinks): for child_filename in child_files: if child_filename == DDS_IGNORE_FILENAME: pattern_lines = self._read_non_empty_lines(d...
Traverse top_path directory and save patterns in any .ddsignore files found. :param top_path: str: directory name we should traverse looking for ignore files :param followlinks: boolean: should we traverse symbolic links
389,185
def tokens2ids(tokens: Iterable[str], vocab: Dict[str, int]) -> List[int]: return [vocab.get(w, vocab[C.UNK_SYMBOL]) for w in tokens]
Returns sequence of integer ids given a sequence of tokens and vocab. :param tokens: List of string tokens. :param vocab: Vocabulary (containing UNK symbol). :return: List of word ids.
389,186
def run_npm(self): for name, version in npm_dependencies.items(): dep_name = % (name, version) self.run_cmd([, , , dep_name])
h/t https://github.com/elbaschid/virtual-node/blob/master/setup.py
389,187
def add_members(self, users=None, role=TeamRoles.MEMBER): if role and role not in TeamRoles.values(): raise IllegalArgumentError("role should be one of `TeamRoles` {}, got ".format(TeamRoles.values(), ...
Members to add to a team. :param members: list of members, either `User` objects or usernames :type members: List of `User` or List of pk :param role: (optional) role of the users to add (default `TeamRoles.MEMBER`) :type role: basestring :raises IllegalArgumentError: when provi...
389,188
def single_violation(self, column=None, value=None, **kwargs): return self._resolve_call(, column, value, **kwargs)
A single event violation is a one-time event that occurred on a fixed date, and is associated with one permitted facility. >>> PCS().single_violation('single_event_viol_date', '16-MAR-01')
389,189
def _add_genetic_models(self, variant_obj, info_dict): genetic_models_entry = info_dict.get() if genetic_models_entry: genetic_models = [] for family_annotation in genetic_models_entry.split(): for genetic_model in family_annotation.split()[-1].split(): ...
Add the genetic models found Args: variant_obj (puzzle.models.Variant) info_dict (dict): A info dictionary
389,190
def _prep_acl_for_compare(ACL): ret = copy.deepcopy(ACL) ret[] = _normalize_user(ret[]) for item in ret.get(, ()): item[] = _normalize_user(item.get()) return ret
Prepares the ACL returned from the AWS API for comparison with a given one.
389,191
def handle(client_message, handle_event_imap_invalidation=None, handle_event_imap_batch_invalidation=None, to_object=None): message_type = client_message.get_message_type() if message_type == EVENT_IMAPINVALIDATION and handle_event_imap_invalidation is not None: key = None if not client_mes...
Event handler
389,192
def apply_operation(self, symmop): def operate_site(site): new_cart = symmop.operate(site.coords) return Site(site.species, new_cart, properties=site.properties) self._sites = [operate_site(s) for s in self._sites]
Apply a symmetry operation to the molecule. Args: symmop (SymmOp): Symmetry operation to apply.
389,193
def handle_label_relation(self, line: str, position: int, tokens: ParseResults) -> ParseResults: subject_node_dsl = self.ensure_node(tokens[SUBJECT]) description = tokens[OBJECT] if self.graph.has_node_description(subject_node_dsl): raise RelabelWarning( lin...
Handle statements like ``p(X) label "Label for X"``. :raises: RelabelWarning
389,194
def _validate_bag(self, bag, **kwargs): failed = None try: bag.validate(**kwargs) except BagValidationError as e: failed = e if failed: raise BagValidationError("%s" % failed)
Validate BagIt (checksums, payload.oxum etc)
389,195
def _process_added_port_event(self, port_name): LOG.info("Hyper-V VM vNIC added: %s", port_name) self._added_ports.add(port_name)
Callback for added ports.
389,196
def parse_tweet(raw_tweet, source, now=None): if now is None: now = datetime.now(timezone.utc) raw_created_at, text = raw_tweet.split("\t", 1) created_at = parse_iso8601(raw_created_at) if created_at > now: raise ValueError("Tweet is from the future") return Tweet(click.unsty...
Parses a single raw tweet line from a twtxt file and returns a :class:`Tweet` object. :param str raw_tweet: a single raw tweet line :param Source source: the source of the given tweet :param Datetime now: the current datetime :returns: the parsed tweet :rtype: Tweet
389,197
def attention_lm_moe_large(): hparams = attention_lm_moe_base() hparams.num_hidden_layers = 5 hparams.moe_layers = "3" hparams.hidden_size = 1024 hparams.num_heads = 16 hparams.filter_size = 4096 hparams.moe_hidden_sizes = "4096" hparams.moe_num_experts = 128 hparams.layer_prepostprocess_dropout = ...
Large model for distributed training. Over 1B parameters, so requires multi-gpu training due to memory requirements. on lm1b_32k: After 45K steps on 8 GPUs (synchronous): eval_log_ppl_per_token = 3.18 eval_ppl_per_word = exp(1.107893 * eval_log_ppl_per_token) = 33.9 Returns: an hpar...
389,198
def _get_app_version(self, app_config): base_name = app_config.__module__.split()[0] module = __import__(base_name) return getattr(module, , )
Some plugins ship multiple applications and extensions. However all of them have the same version, because they are released together. That's why only-top level module is used to fetch version information.
389,199
def get_portchannel_info_by_intf_output_lacp_actor_brcd_state(self, **kwargs): config = ET.Element("config") get_portchannel_info_by_intf = ET.Element("get_portchannel_info_by_intf") config = get_portchannel_info_by_intf output = ET.SubElement(get_portchannel_info_by_intf, "outp...
Auto Generated Code