Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
354,300
def suggest(query): search_params = { : , : , : , } search_params[] = query raw_result = _wiki_request(search_params) if raw_result[].get(): return raw_result[][][] return None
Get a Wikipedia search suggestion for `query`. Returns a string or None if no suggestion was found.
354,301
def diag(ax=None, linecolor=, linestyle=, **kwargs): ax = get_ax(ax) xy_min = np.min((ax.get_xlim(), ax.get_ylim())) xy_max = np.max((ax.get_ylim(), ax.get_xlim())) return ax.plot([xy_min, xy_max], [xy_min, xy_max], ls=linestyle, c=linecolor, ...
Plot the diagonal.
354,302
def extract_stack(start=0): try: raise ZeroDivisionError except ZeroDivisionError: trace = sys.exc_info()[2] f = trace.tb_frame.f_back for i in range(start): f = f.f_back stack = [] while f is not None: stack.append({ "line": f.f_lineno, ...
SNAGGED FROM traceback.py Altered to return Data Extract the raw traceback from the current stack frame. Each item in the returned list is a quadruple (filename, line number, function name, text), and the entries are in order from newest to oldest
354,303
def rotate(self, word): before = string.printable[:62] after = .join([i[5:] + i[:5] for i in [string.digits, string.ascii_lowercase, string.ascii_uppercase]]) table = dict(zip(before, after...
Replaced by a letter 5 right shift. e.g. a->f, b->g, . -> .
354,304
def to_latex(self): latex = r"[{} " for attribute, value in self: if attribute in [, ]: continue value_l = value.to_latex() if value_l == "": continue latex += "{attribute:<15} & {value:<20} \\\\ \n".format(attribute=attribute, value=value_l) ...
Returns a LaTeX representation of an attribute-value matrix
354,305
def modify_process_summary(self, pid=None, text=, append=False): pid = self._get_pid(pid) if append: current_summary = self.get_process_info(pid).get() or modified_text = current_summary + + text text = modified_text request_data = {"id": pid, "d...
modify_process_summary(self, pid=None, text='') Modifies the summary text of the process execution :Parameters: * *key* (`pid`) -- Identifier of an existing process * *key* (`text`) -- summary text * *append* (`boolean`) -- True to append to summary. False to override it.
354,306
def sort(self, **parameters): parameters = self._coerce_by_parameter(parameters) self._sort = parameters return self
Parameters: `by`: pass either a field name or a wildcard string to sort on prefix with `-` to make a desc sort. `alpha`: set it to True to sort lexicographically instead of numerically.
354,307
def is_transaction_signer_authorized(self, transactions, state_root, from_state): role = None if role is None: role = self._cache.get_role("transactor.transaction_signer", state_root, from_state) ...
Check the transaction signing key against the allowed transactor permissions. The roles being checked are the following, from first to last: "transactor.transaction_signer.<TP_Name>" "transactor.transaction_signer" "transactor" "def...
354,308
async def connect_message(self, message, context): conn_string = message.get() client_id = context.user_data await self.connect(client_id, conn_string)
Handle a connect message. See :meth:`AbstractDeviceAdapter.connect`.
354,309
def centroid(X): C = np.sum(X, axis=0) / len(X) return C
Calculate the centroid from a matrix X
354,310
def _call_command(self, name, *args, **kwargs): obj = getattr(self, , self) if name in self.available_modifiers and obj._pk and not obj.connected: obj.connect() meth = getattr(self, % name, self._traverse_command) return meth(...
Check if the command to be executed is a modifier, to connect the object. Then call _traverse_command.
354,311
def play_video(self, video_id, playlist_id=None): self.start_session_if_none() self._session.play_video(video_id, playlist_id)
Play video(video_id) now. This ignores the current play queue order. :param video_id: YouTube video id(http://youtube.com/watch?v=video_id) :param playlist_id: youtube.com/watch?v=video_id&list=playlist_id
354,312
def is_valid_ext_comm_attr(attr): if not isinstance(attr, str): return False tokens = attr.rsplit(, 1) if len(tokens) != 2: return False try: if in tokens[0]: if not is_valid_ipv4(tokens[0]): return False else: int(tokens[0]...
Validates *attr* as string representation of RT or SOO. Returns True if *attr* is as per our convention of RT or SOO, else False. Our convention is to represent RT/SOO is a string with format: *global_admin_part:local_admin_path*
354,313
def _set_media_type(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u: {: 17}, u: {: 2}, u: {:...
Setter method for media_type, mapped from YANG variable /brocade_interface_ext_rpc/get_interface_detail/output/interface/media_type (enumeration) If this variable is read-only (config: false) in the source YANG file, then _set_media_type is considered as a private method. Backends looking to populate this v...
354,314
def initial_finall_mass_relation(self,marker=,linestyle=): final_m=[] ini_m=[] for i in range(len(self.runs_H5_surf)): sefiles=se(self.runs_H5_out[i]) ini_m.append(sefiles.get("mini")) h1=sefiles.get(int(sefiles.se.cycles[-2]),) mass=sefiles.get(in...
INtiial to final mass relation
354,315
def block_sep1(self, Y): Y1 = Y[..., self.cri.M:] if self.cri.Cd > 1: shp = list(Y1.shape) shp[self.cri.axisM] = self.cri.dimN shp[self.cri.axisC] = self.cri.Cd Y1 = Y1.reshape(shp) Y1 = np.swapaxes(Y...
Separate variable into component corresponding to Y1 in Y.
354,316
def join_url_parts(*args): if len(args) == 1: return args[0] return_val = clean_url_segment(args[0]) for i in range(1, len(args)): arg = args[i] if i == len(args) - 1: return_val += + arg else: return return_val
Joins a list of segments into a URL-like string :type args: List<string>
354,317
def regress_components( data, components, remove_mean=True ): timepoints = data.shape[0] betas = np.linalg.pinv(components).dot(data) if remove_mean: datahat = components.dot(betas) else: datahat = components[:, 1:].dot(betas[1:, ...]) regressed_data = data - datahat retur...
Returns data with components regressed out. :param bool remove_mean: whether or not demean data (i.e. degree 0), :param int axis: numpy array axes along which regression is performed
354,318
def change_password(): basic_auth = % (DEFAULT_USERNAME, DEFAULT_PASSWORD) try: auth = base64.encodestring(basic_auth) except TypeError: auth = base64.encodestring(bytes(basic_auth, )).decode() headers = { "Content-Type": "application/json", "Accept": "applicat...
Changes the standard password from neo4j to testing to be able to run the test suite.
354,319
def main(args=None): parser = get_parser() args = parser.parse_args(args=args) if not (args.matrix or args.dependencies or args.treemap or args.graph): args.matrix = True packages = [] for arg in args.packages: if in arg: for package in arg.split(): ...
Main function. This function is the command line entry point. Args: args (list of str): the arguments passed to the program. Returns: int: return code being 0 (OK), 1 (dsm empty) or 2 (error).
354,320
def map_single_axis(low, high, dead_zone, hot_zone, value): input_range = high - low corrected_low = low + input_range * dead_zone corrected_high = high - input_range * hot_zone return map_into_range(corrected_low, corrected_high, value)
Apply dead and hot zones before mapping a value to a range. The dead and hot zones are both expressed as the proportion of the axis range which should be regarded as 0.0 or 1.0 (or -1.0 depending on cardinality) respectively, so for example setting dead zone to 0.2 means the first 20% of the range of the axis w...
354,321
def fetch(code) : ret = {} code = KeywordFetcher._remove_strings(code) result = KeywordFetcher.prog.findall(code) for keyword in result : if len(keyword) <= 1: continue if keyword.isdigit(): continue if keyword[0] == or keyword[0] == : keyword = keyword[1:] if keyword[-1] == or keyword[-...
Fetch keywords by Code
354,322
def song_detail(ids): if not isinstance(ids, list): raise ParamsError() c = [] for id in ids: c.append({: id}) r = NCloudBot() r.method = r.data = {: json.dumps(c), : c, "csrf_token": ""} r.send() return r.response
通过歌曲 ID 获取歌曲的详细信息 :param ids: 歌曲 ID 的 list
354,323
def selection(self): if self._font.get() is "" or self._font.get() not in self._fonts: return None else: return self._font.get()
Selection property. :return: None if no font is selected and font family name if one is selected. :rtype: None or str
354,324
def genus_specific(self): closestrefseqgenus = False for sample in self.runmetadata.samples: if sample.general.bestassemblyfile != : try: closestrefseqgenus = sample.general.closestrefseqgenus except AttributeError: ...
For genus-specific targets, MLST and serotyping, determine if the closest refseq genus is known - i.e. if 16S analyses have been performed. Perform the analyses if required
354,325
def parse_args(): parser = argparse.ArgumentParser( description="Import existing secrets to YubiHSM eco system", add_help=True, formatter_class=argparse.ArgumentDefaultsHelpFormatter,) parser.add_argument(, , dest=, default=default_device, ...
Parse the command line arguments
354,326
def _ProcessZipFileWithPlugins(self, parser_mediator, zip_file): archive_members = zip_file.namelist() for plugin in self._plugins: try: plugin.UpdateChainAndProcess( parser_mediator, zip_file=zip_file, archive_members=archive_members) except errors.WrongCompoundZIPPlugin as...
Processes a zip file using all compound zip files. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. zip_file (zipfile.ZipFile): the zip file. It should not be closed in this method, but will be closed in P...
354,327
def _entity_list_as_bel(entities: Iterable[BaseEntity]) -> str: return .join( e.as_bel() for e in entities )
Stringify a list of BEL entities.
354,328
def guest_inspect_vnics(self, userid_list): if not isinstance(userid_list, list): userid_list = [userid_list] action = "get the vnics statistics of guest " % str(userid_list) with zvmutils.log_and_reraise_sdkbase_error(action): return self._monitor.inspect_vnics(...
Get the vnics statistics of the guest virtual machines :param userid_list: a single userid string or a list of guest userids :returns: dictionary describing the vnics statistics of the vm in the form {'UID1': [{ 'vswitch_name': xx,...
354,329
def cli(env, identifier, wait): vsi = SoftLayer.VSManager(env.client) vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, ) ready = vsi.wait_for_ready(vs_id, wait) if ready: env.fout("READY") else: raise exceptions.CLIAbort("Instance %s not ready" % vs_id)
Check if a virtual server is ready.
354,330
def get_include_methods(request): methods = request.get("include_methods", "") include_methods = [ x.strip() for x in methods.split(",") if x.strip()] return include_methods
Retrieve include_methods values from the request
354,331
def from_values(cls, vals): "Deprecated method to construct tree from list of objects" if util.config.future_deprecations: param.main.param.warning("%s.from_values is deprecated, the %s " "constructor may now be used directly.") return cls(items=c...
Deprecated method to construct tree from list of objects
354,332
def parseFilename(filename): _indx = filename.find() if _indx > 0: _fname = filename[:_indx] _extn = filename[_indx + 1:-1] else: _fname = filename _extn = None return _fname, _extn
Parse out filename from any specified extensions. Returns rootname and string version of extension name.
354,333
def list_certificates(self): if self._rest_version >= LooseVersion("1.12"): return self._request("GET", "cert") else: cert = self._request("GET", "cert") out = ResponseList([cert]) out.headers = cert.headers ...
Get the attributes of the current array certificate. :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **GET cert** :type \*\*kwargs: optional :returns: A list of dictionaries describing all confi...
354,334
def add_route(route, endpoint=None, **kw): def apiurl(route): return .join(s.strip() for s in ["", BASE_URL, route]) return add_senaite_route(apiurl(route), endpoint, **kw)
Add a new JSON API route
354,335
def put(self, instance, errors): if errors: return self.errors(errors) return self.updated(instance)
Update a model instance. :param instance: The model instance. :param errors: Any errors. :return: The updated model instance, or a dictionary of errors.
354,336
def dump_memory_map(memoryMap, mappedFilenames = None, bits = None): if not memoryMap: return table = Table() if mappedFilenames: table.addRow("Address", "Size", "State", "Access", "Type", "File") else: table.addRow("Address", "Size", "State...
Dump the memory map of a process. Optionally show the filenames for memory mapped files as well. @type memoryMap: list( L{win32.MemoryBasicInformation} ) @param memoryMap: Memory map returned by L{Process.get_memory_map}. @type mappedFilenames: dict( int S{->} str ) @param ma...
354,337
async def do_del_aldb(self, args): params = args.split() addr = None mem_bytes = None memory = None try: addr = Address(params[0]) mem_bytes = binascii.unhexlify(params[1]) memory = int.from_bytes(mem_bytes, byteorder=) _...
Delete device All-Link record. WARNING THIS METHOD CAN DAMAGE YOUR DEVICE IF USED INCORRECTLY. Please ensure the memory id is appropriate for the device. You must load the ALDB of the device before using this method. The memory id must be an existing memory id in the ALDB or this ...
354,338
def after_match(self, func, full_fallback=False): iterator = iter(self) for item in iterator: if func(item): return iterator if full_fallback: iterator = iter(self) return iterator
Returns an iterator for all the elements after the first match. If `full_fallback` is `True`, it will return all the messages if the function never matched.
354,339
def get_parameter(self, name): for parameter in self._parameters: if parameter.name == name: return parameter
Get the parameter on this schema with the given C{name}.
354,340
def set_unix_socket_params(self, abstract=None, permissions=None, owner=None, umask=None): self._set(, abstract, cast=bool) self._set(, permissions) self._set(, owner) self._set(, umask) return self._section
Sets Unix-socket related params. :param bool abstract: Force UNIX socket into abstract mode (Linux only). :param str permissions: UNIX sockets are filesystem objects that obey UNIX permissions like any other filesystem object. You can set the UNIX sockets' permissions with thi...
354,341
def validate(self, schema=None): if schema is None: schema = self._schema type_checker = Draft3Validator.TYPE_CHECKER.redefine( "datetime", lambda c, d: isinstance(d, (datetime.date, datetime.datetime)) ) ValidatorCls = jsonschema.validators.extend(Draft...
Validate that we have a valid object. On error, this will raise a `ScrapeValueError` This also expects that the schemas assume that omitting required in the schema asserts the field is optional, not required. This is due to upstream schemas being in JSON Schema v3, and not validictory'...
354,342
def get_browser_datetime(webdriver): js_stmt = browser_date = webdriver.execute_script(js_stmt) return datetime(int(browser_date[]), int(browser_date[]) + 1, int(browser_date[]), int(browser_date[]), ...
Get the current date/time on the web browser as a Python datetime object. This date matches 'new Date();' when ran in JavaScript console. Args: webdriver: Selenium WebDriver instance Returns: datetime - Python datetime object. Usage:: ...
354,343
def update_config(self): result = False while self._configmixin_queue: config = self._configmixin_queue.popleft() self.config.update(config) result = True return result
Pull any changes made with :py:meth:`set_config`. Call this from within your component before using any config values to ensure you have the latest values set by the user. :return: Whether the config was updated. :rtype: bool
354,344
def LVMPathSpecGetVolumeIndex(path_spec): volume_index = getattr(path_spec, , None) if volume_index is None: location = getattr(path_spec, , None) if location is None or not location.startswith(): return None volume_index = None try: volume_index = int(location[4:], 10) - 1 exc...
Retrieves the volume index from the path specification. Args: path_spec (PathSpec): path specification. Returns: int: volume index or None if not available.
354,345
def reset(self): self._frame_counter = 0 ob_real = self.real_env.reset() self.sim_env.add_to_initial_stack(ob_real) for _ in range(3): ob_real, _, _, _ = self.real_env.step(self.name_to_action_num["NOOP"]) self.sim_env.add_to_initial_stack(ob_real) ob_sim = self.sim_env.reset()...
Reset simulated and real environments.
354,346
def _call_extractor(extractor, text): if isinstance(extractor, str): return _get_terminal(extractor, text) else: return extractor(text)
This method calls an extractor on some text. If extractor is just a string, it is passed as the first value to _get_terminal. Otherwise it is treated as a callable and text is passed directly to it. This makes it so you can have a shorthand of terminal(val) <-> val.
354,347
def process_email(ctx, param, value): user = User.query.filter(User.email == value).first() if not user: raise click.BadParameter(%s\, value) return user
Return an user if it exists.
354,348
def average_fft(self, fftlength=None, overlap=0, window=None): from gwpy.spectrogram import Spectrogram if fftlength is None: fftlength = self.duration if isinstance(fftlength, units.Quantity): fftlength = fftlength.value nfft = int((fftlength * ...
Compute the averaged one-dimensional DFT of this `TimeSeries`. This method computes a number of FFTs of duration ``fftlength`` and ``overlap`` (both given in seconds), and returns the mean average. This method is analogous to the Welch average method for power spectra. Paramete...
354,349
def python_value(self, value): value = super(OrderedUUIDField, self).python_value(value) u = binascii.b2a_hex(value) value = u[8:16] + u[4:8] + u[0:4] + u[16:22] + u[22:32] return UUID(value.decode())
Convert binary blob to UUID instance
354,350
def runOnExecutor(self, *commands, oper=ACCEPT, defer_shell_expansion=False): return self.makeOutput(EXE, commands, oper=oper, defer_shell_expansion=defer_shell_expansion)
This runs in the executor of the current scope. You cannot magically back out since there are no gurantees that ssh keys will be in place (they shouldn't be).
354,351
def vcs_virtual_ip_address_inband_interface_ve(self, **kwargs): config = ET.Element("config") vcs = ET.SubElement(config, "vcs", xmlns="urn:brocade.com:mgmt:brocade-vcs") virtual = ET.SubElement(vcs, "virtual") ip = ET.SubElement(virtual, "ip") address = ET.SubElement(ip...
Auto Generated Code
354,352
def get_params(self, deep=True): params = { "loss": self.loss, "learning_schedule": self.learning_schedule, "no_components": self.no_components, "learning_rate": self.learning_rate, "k": self.k, "n": self.n, "rho": sel...
Get parameters for this estimator. Arguments --------- deep: boolean, optional If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns ------- params : mapping of string to any Pa...
354,353
def get(self, page_size, current_page, session): request = TOPRequest() request[] = page_size request[] = current_page self.create(self.execute(request, session)) return self.groups
taobao.crm.groups.get 查询卖家的分组 查询卖家的分组,返回查询到的分组列表,分页返回分组
354,354
def partition(src, key=None): bucketized = bucketize(src, key) return bucketized.get(True, []), bucketized.get(False, [])
No relation to :meth:`str.partition`, ``partition`` is like :func:`bucketize`, but for added convenience returns a tuple of ``(truthy_values, falsy_values)``. >>> nonempty, empty = partition(['', '', 'hi', '', 'bye']) >>> nonempty ['hi', 'bye'] *key* defaults to :class:`bool`, but can be caref...
354,355
def get_sf_values(self, filename=): file = os.path.join(self.datapath, filename) hour_factors = pd.read_csv(file, index_col=0) hour_factors = hour_factors.query( .format( self.building_class, self.shlp_type)) residential = ...
Determine the h-values Parameters ---------- filename : string name of file where sigmoid factors are stored
354,356
def pb(name, labels, predictions, num_thresholds=None, weights=None, display_name=None, description=None): import tensorflow.compat.v1 as tf if num_thresholds is None: num_thresholds = _DEFAULT_NUM_THRESHOLDS if weights is None: weights = 1.0 bucket_...
Create a PR curves summary protobuf. Arguments: name: A name for the generated node. Will also serve as a series name in TensorBoard. labels: The ground truth values. A bool numpy array. predictions: A float32 numpy array whose values are in the range `[0, 1]`. Dimensions must match those...
354,357
def _get_statements(self, lines, start): result = [] statement = [] nocomment = [l.split("!")[0] for l in lines] length = 0 for i in range(len(nocomment)): line = nocomment[i].strip() linenum = start + i length += len(lines[i]) + 1 ...
Returns a list of complete Fortran statements for the specified lines by dealing with comments and line continuations. Returns a list of tuples of the form (linenum, statement, orginal character length). :arg start: the start index in the overall document for these lines.
354,358
def ack(self, items): for item in items: time_to_ack = item.time_to_ack if time_to_ack is not None: self._manager.ack_histogram.add(time_to_ack) ack_ids = [item.ack_id for item in items] request = types.StreamingPullRequest(ack_ids=ack_i...
Acknowledge the given messages. Args: items(Sequence[AckRequest]): The items to acknowledge.
354,359
def badRequestMethod(self, environ, start_response): response = "400 Bad Request\n\nTo access this PyAMF gateway you " \ "must use POST requests (%s received)" % environ[] start_response(, [ (, ), (, str(len(response))), (, gateway.SERVER_NAME), ...
Return HTTP 400 Bad Request.
354,360
def get_customjs(self, references, plot_id=None): if plot_id is None: plot_id = self.plot.id or self_callback = self.js_callback.format(comm_id=self.comm.id, timeout=self.timeout, ...
Creates a CustomJS callback that will send the requested attributes back to python.
354,361
def _rc_sdiffstore(self, dst, src, *args): args = list_or_args(src, args) result = self.sdiff(*args) if result is not set([]): return self.sadd(dst, *list(result)) return 0
Store the difference of sets ``src``, ``args`` into a new set named ``dest``. Returns the number of keys in the new set.
354,362
def get_config(self, config_filename): x = pyini.Ini(lazy=True, basepath=os.path.join(self.project_dir, )) for p in reversed(self.apps): app_path = get_app_dir(p) filename = os.path.join(app_path, config_filename) if os.path.exists(filename): ...
Collection all config file in all available apps, and merge them into ini object :return: ini object
354,363
def smart_account(app): if os.environ[] == : return from flask_security import SQLAlchemyUserDatastore, Security account_module_name, account_class_name = os.environ[ ].rsplit(, 1) account_module = importlib.import_module(account_module_name) account_class = getattr(account_m...
尝试使用内置方式构建账户
354,364
def controversial(self, limit=None): return self._reddit.controversial(self.display_name, limit=limit)
GETs controversial links from this subreddit. Calls :meth:`narwal.Reddit.controversial`. :param limit: max number of links to return
354,365
def clean_source_index(self): cleanup_timer = Timer() cleanup_counter = 0 for entry in os.listdir(self.config.source_index): pathname = os.path.join(self.config.source_index, entry) if os.path.islink(pathname) and not os.path.exists(pathname): log...
Cleanup broken symbolic links in the local source distribution index. The purpose of this method requires some context to understand. Let me preface this by stating that I realize I'm probably overcomplicating things, but I like to preserve forward / backward compatibility when possible...
354,366
def query(query, use_sudo=True, **kwargs): func = use_sudo and run_as_root or run user = kwargs.get() or env.get() password = kwargs.get() or env.get() options = [ , , , ] if user: options.append( % quote(user)) if password: options.append( % qu...
Run a MySQL query.
354,367
def get_dataset(): seg_data = "segmentation-X.npy" seg_labels = "segmentation-y.npy" if os.path.isfile(seg_data) and os.path.isfile(seg_labels): X = numpy.load(seg_data) y = numpy.load(seg_labels) with open(, ) as f: datasets = pickle.load(f) return (X,...
Create a dataset for machine learning of segmentations. Returns ------- tuple : (X, y) where X is a list of tuples. Each tuple is a feature. y is a list of labels (0 for 'not in one symbol' and 1 for 'in symbol')
354,368
def parallel_apply_transformations(x, transforms, black_border_size=0): transforms = tf.convert_to_tensor(transforms, dtype=tf.float32) x = _apply_black_border(x, black_border_size) num_transforms = transforms.get_shape().as_list()[0] im_shape = x.get_shape().as_list()[1:] tiled_x = tf.reshape( ...
Apply image transformations in parallel. :param transforms: TODO :param black_border_size: int, size of black border to apply Returns: Transformed images
354,369
def _read_para_via_rvs(self, code, cbit, clen, *, desc, length, version): if clen % 16 != 0: raise ProtocolError(f) _addr = list() for _ in range(clen // 16): _addr.append(ipaddress.ip_address(self._read_fileng(16))) via_rvs = dict( type=des...
Read HIP VIA_RVS parameter. Structure of HIP VIA_RVS parameter [RFC 6028]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ...
354,370
def log_flush_for_obj_for_interval(self, log_type, obj_id, interval): if not log_type: log_type = "policies" interval = interval.replace(" ", "+") flush_url = "{}/{}/id/{}/interval/{}".format( self.url, log_type, obj_id, interval) sel...
Flush logs for an interval of time for a specific object. Please note, log_type is a variable according to the API docs, but acceptable values are not listed. Only "policies" is demonstrated as an acceptable value. Args: log_type (str): Only documented type is "policies". T...
354,371
def GetSitelinksFromFeed(client, feed): return feed_items
Gets the sitelinks from a feed. Args: client: an AdWordsClient instance. feed: the feed used to retrieve sitelinks. Returns: A dictionary mapping the feed item ID to SiteLinkFromFeed.
354,372
def build(opts=None): board = catan.board.Board() modify(board, opts) return board
Build a new board using the given options. :param opts: dictionary mapping str->Opt :return: the new board, Board
354,373
def getResultsTotalCount(self): count = 0 for val in self.getRawResults().values(): count += len(val) return count
The total number of analysis results parsed
354,374
def groups(username, **kwargs): group_list = [] return group_list
Authenticate against an LDAP group Behavior is highly dependent on if Active Directory is in use. AD handles group membership very differently than OpenLDAP. See the :ref:`External Authentication <acl-eauth>` documentation for a thorough discussion of available parameters for customizing the search. ...
354,375
def p_recipe(self, t): if len(t) == 3: t[0] = t[1] + t[2] else: t[0] = t[1]
recipe : RECIPE_LINE | RECIPE_LINE recipe
354,376
def set_state(self): glEnable(self.region.material.target) glBindTexture(self.region.material.target, self.region.material.id) self.region.bone.setRotate(self.data)
Sets the state required for this vertex region. Currently binds and enables the texture of the material of the region.
354,377
def get_registers(self, cpu_id): if not isinstance(cpu_id, baseinteger): raise TypeError("cpu_id can only be an instance of type baseinteger") (names, values) = self._call("getRegisters", in_p=[cpu_id]) return (names, values)
Gets all the registers for the given CPU. in cpu_id of type int The identifier of the Virtual CPU. out names of type str Array containing the lowercase register names. out values of type str Array parallel to the names holding the register values as if the ...
354,378
def get_for_resource(resource): resource_content_type = ContentType.objects.get_for_model(resource) default_items = set(DefaultPriceListItem.objects.filter(resource_content_type=resource_content_type)) service = resource.service_project_link.service items = set(PriceListItem.obj...
Get list of all price list items that should be used for resource. If price list item is defined for service - return it, otherwise - return default price list item.
354,379
def parse_dunder_all(self): assert self.current.value == self.consume(tk.NAME) if self.dunder_all is not None or self.dunder_all_error is not None: self.dunder_all = None self.dunder_all_error = return if self.current.value != : ...
Parse the __all__ definition in a module.
354,380
def get_hash(path, form=, chunk_size=4096): try: hash_type = getattr(hashlib, form) except AttributeError: raise ValueError(.format(form)) with open(path, ) as ifile: hash_obj = hash_type() for chunk in iter(lambda: ifile.read(chunk_size), b): hash_o...
Generate a hash digest string for a file.
354,381
def zopen(filename, *args, **kwargs): if Path is not None and isinstance(filename, Path): filename = str(filename) name, ext = os.path.splitext(filename) ext = ext.upper() if ext == ".BZ2": if PY_VERSION[0] >= 3: return bz2.open(filename, *args, **kwargs) else: ...
This function wraps around the bz2, gzip and standard python's open function to deal intelligently with bzipped, gzipped or standard text files. Args: filename (str/Path): filename or pathlib.Path. \*args: Standard args for python open(..). E.g., 'r' for read, 'w' for write. ...
354,382
def hacking_docstring_multiline_end(physical_line, previous_logical, tokens): r docstring = is_docstring(tokens, previous_logical) if docstring: if not in docstring: return else: last_line = docstring.split()[-1] pos = max(last_line.rfind(i) for ...
r"""Check multi line docstring end. OpenStack HACKING guide recommendation for docstring: Docstring should end on a new line Okay: '''foobar\nfoo\nbar\n''' Okay: def foo():\n '''foobar\n\nfoo\nbar\n''' Okay: class Foo(object):\n '''foobar\n\nfoo\nbar\n''' Okay: def foo():\n a = '''not...
354,383
def sparse_dot_product_attention_truncated( q, k, v, bi, experts_params, use_map_fn=False, mask_right=False, ): batch_size, nb_heads, _, depth = common_layers.shape_list(q) total_loss = 0.0 list_lsh = [LshGating(depth=depth, **experts_params) for _ in range(nb_heads)] ...
Sparse multihead self attention. Perform an approximation of the full multihead attention by dispatching the tokens using their keys/values. Thus the attention matrix are only computed each times on a subset of the tokens. Notes: * The function don't perform scaling here (multihead_attention does the /sq...
354,384
def dataset_filepath(filename, dataset_name=None, task=None, **kwargs): dataset_dir_path = dataset_dirpath( dataset_name=dataset_name, task=task, **kwargs) return os.path.join(dataset_dir_path, filename)
Get the path of the corresponding dataset file. Parameters ---------- filename : str The name of the file. dataset_name : str, optional The name of the dataset. Used to define a sub-directory to contain all instances of the dataset. If not given, a dataset-specific directory is ...
354,385
def pop(self): move = self.move_stack.pop() self.transpositions.subtract((self.zobrist_hash(), )) self.move_number -= 1 captured_piece_type = self.captured_piece_stack.pop() captured_piece_color = self.turn if not move: ...
Restores the previous position and returns the last move from the stack.
354,386
def plot_summary(self, parameters=None, truth=None, extents=None, display=False, filename=None, chains=None, figsize=1.0, errorbar=False, include_truth_chain=True, blind=None, watermark=None, extra_parameter_spacing=0.5, vertical_spacing_ratio=1.0, show_nam...
Plots parameter summaries This plot is more for a sanity or consistency check than for use with final results. Plotting this before plotting with :func:`plot` allows you to quickly see if the chains give well behaved distributions, or if certain parameters are suspect or require a great...
354,387
def seek(self, offset, whence=SEEK_SET): if not self._seekable: raise UnsupportedOperation() self.flush() return self._update_seek(offset, whence)
Change the stream position to the given byte offset. Args: offset (int): Offset is interpreted relative to the position indicated by whence. whence (int): The default value for whence is SEEK_SET. Values for whence are: SEEK_SET or 0 – sta...
354,388
def cli_values(self, argv): options = [] for option in self._options: kwargs = option.kwargs.copy() kwargs[] = None kwargs[] = False options.append(Option(*option.args, **kwargs)) parser = self.build_...
Parse command-line arguments into values. Parses arguments provided on the command-line (or sys.argv). Only returns arguments that are explicitly supplied, so we strip out defaults and validation rules like `required` in this call.
354,389
def _get_operation_rpc(self): request_pb = operations_pb2.GetOperationRequest(name=self.name) return self.client._operations_stub.GetOperation(request_pb)
Polls the status of the current operation. Uses gRPC request to check. :rtype: :class:`~google.longrunning.operations_pb2.Operation` :returns: The latest status of the current operation.
354,390
def dsn(): configs = {: host, : port, : database, : user, : password} return .join([.format(_[0], _[1]) for _ in configs.items() if _[1] is not None and _[1] != ])
Return a libpq connection string using the variables defined in this file.
354,391
def __load(self): parts = self.__class_name.split() module_name = ".".join(parts[:-1]) module = __import__(module_name) modules = [] for comp in parts[1:]: module = getattr(module, comp) modules.append(module) self.__module = modules[-2]
Loads dynamically the class that acts like a namespace for constants.
354,392
def save_model(self, request, entry, form, change): context = RequestContext(request) try: content = render_placeholder(entry.content_placeholder, context) entry.content = content or except KeyError: entry.content = super(EntryP...
Fill the content field with the interpretation of the placeholder
354,393
def print_user(self, user): status = "active" token = user.token if token in [, ]: status = token if token is None: token = subid = "%s\t%s[%s]" %(user.id, token, status) print(subid) return subid
print a relational database user
354,394
def _set_name(self, version=AUTO): name = if version: if version is AUTO: version = sys.version_info[0] if version == 2: version = name = % (name, version) self.name = name
Returns plugin name.
354,395
def peek_with_kwargs(init, args=[]): def peek(store, container, _stack=None): return init(\ *[ store.peek(attr, container, _stack=_stack) for attr in args ], \ **dict([ (attr, store.peek(attr, container, _stack=_stack)) \ for attr in container if attr not in args...
Make datatypes passing keyworded arguments to the constructor. This is a factory function; returns the actual `peek` routine. Arguments: init (callable): type constructor. args (iterable): arguments NOT to be keyworded; order does matter. Returns: callable: deserializer (`peek`...
354,396
def production_variant(model_name, instance_type, initial_instance_count=1, variant_name=, initial_weight=1, accelerator_type=None): production_variant_configuration = { : model_name, : instance_type, : initial_instance_count, : variant_name, : ini...
Create a production variant description suitable for use in a ``ProductionVariant`` list as part of a ``CreateEndpointConfig`` request. Args: model_name (str): The name of the SageMaker model this production variant references. instance_type (str): The EC2 instance type for this production vari...
354,397
def getname(obj): for name_attribute in (, ): try: return getattr(obj, name_attribute, getattr(obj.__class__, name_attribute)) except AttributeError: pass raise TypeError( % type(obj))
Return the most qualified name of an object :param obj: object to fetch name :return: name of ``obj``
354,398
def get_auth_token(self, user_payload): username = user_payload.get() or None password = user_payload.get() or None if not username or not password: raise ValueError() token = .format( username=username, password=password).encode() token_b64 = ...
Extracts username, password from the `user_payload` and encode the credentials `username:password` in `base64` form
354,399
def show_fuzzy_date(self): date = self.time.replace(tzinfo=None) if date <= datetime.now(): diff = datetime.now() - date if diff.days >= 14: return False else: diff = date - datetime.now() if diff.days >= 14: ...
Return whether the event is in the next or previous 2 weeks. Determines whether to display the fuzzy date.