Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
340,600
def info(self, action=None): if action in self.cache: return self.cache[action][] return self.cache.keys() or None
returns cached request info for given action, or list of cached actions
340,601
def create_binding(self, vhost, exchange, queue, rt_key=None, args=None): vhost = quote(vhost, ) exchange = quote(exchange, ) queue = quote(queue, ) body = json.dumps({: rt_key, : args or []}) path = Client.urls[] % (vhost, ...
Creates a binding between an exchange and a queue on a given vhost. :param string vhost: vhost housing the exchange/queue to bind :param string exchange: the target exchange of the binding :param string queue: the queue to bind to the exchange :param string rt_key: the routing key to us...
340,602
def withdraw_coin(self, coin_name, amount, address): return self._trade_api_call(, coinName=coin_name, amount=amount, address=address)
The method is designed for cryptocurrency withdrawals. Please note: You need to have the privilege of the Withdraw key to be able to use this method. You can make a request for enabling this privilege by submitting a ticket to Support. You need to create the API key that you are going to use for...
340,603
def close_driver(self): channel = self.__get_channel() driver = self.__get_driver_for_channel(channel) if self.__config.get(self.REUSE_BROWSER, True): try: driver.delete_all_cookies() driver.get("abou...
Close current running instance of Webdriver. Usage:: driver = WTF_WEBDRIVER_MANAGER.new_driver() driver.get("http://the-internet.herokuapp.com") WTF_WEBDRIVER_MANAGER.close_driver()
340,604
def _update(self, **kwargs): for key, value in _iteritems(kwargs): if key == : if isinstance(value, dict): if self.settings is None: self.settings = Settings(**value) else: self.settings....
Update some attributes. If a 'settings' attribute is passed as a dict, then it updates the content of the settings, if any, instead of completely overwriting it.
340,605
def render(data, algorithms=(DEFAULT_ALOGRITHM,), seperator=): return seperator.join(str(ihash) for ihash in generate(data, algorithms))
Returns a subresource integrity string for the given data & algorithms >>> data = b"alert('Hello, world.');" >>> render(data) 'sha384-H8BRh8j48O9oYatfu5AZzq6A9RINhZO5H16dQZngK7T62em8MUt1FLm52t+eX6xO' >>> print(render(data, ['sha256', 'sha384'], seperator='\\n')) sha256-qznLcsROx4GACP2dm0UCKCzC...
340,606
def avail_locations(call=None): if call == : raise SaltCloudSystemExit( ) ret = {} conn = get_conn() response = conn.getCreateObjectOptions() for datacenter in response[]: ret[datacenter[][][]] = { : datacenter[][][], ...
List all available locations
340,607
def _get_csv_from_model(models, crumbs, csvs): logger_csvs.info("enter get_csv_from_model: {}".format(crumbs)) _idx = 0 try: for _name, _model in models.items(): if "distributionTable" in _model: models[_name]["distributionTable"], csvs = _get_csv_from_table(_model["...
Get csv from model data :param dict models: Metadata :param str crumbs: Crumbs :param dict csvs: Csv :return dict models: Metadata :return dict csvs: Csv
340,608
def validate_seeded_answers(answers, options, algo): if algo[] == : return validate_seeded_answers_simple(answers, options, algo) elif algo[] == : return validate_seeded_answers_random(answers) else: raise UnknownChooseAnswerAlgorithm()
Validate answers based on selection algorithm This is called when instructor setup the tool and providing seeded answers to the question. This function is trying to validate if instructor provided enough seeds for a give algorithm. e.g. we require 1 seed for each option in simple algorithm and at least 1 s...
340,609
def _check_for_conda_problems(): conda_bin = _get_conda_bin() channels = _get_conda_channels(conda_bin) lib_dir = os.path.join(os.path.dirname(conda_bin), os.pardir, "lib") for l in ["libgomp.so.1", "libquadmath.so"]: if not os.path.exists(os.path.join(lib_dir, l)): subprocess.c...
Identify post-install conda problems and fix. - libgcc upgrades can remove libquadmath, which moved to libgcc-ng
340,610
def account_move(self, source, wallet, accounts): wallet = self._process_value(wallet, ) source = self._process_value(source, ) accounts = self._process_value(accounts, ) payload = {"wallet": wallet, "source": source, "accounts": accounts} resp = self.call(, payload) ...
Moves **accounts** from **source** to **wallet** .. enable_control required :param source: wallet to move accounts from :type source: str :param wallet: wallet to move accounts to :type wallet: str :param accounts: accounts to move :type accounts: list of str ...
340,611
def accept_prompt(self, text=None, response=None, wait=None): with self.driver.accept_modal("prompt", text=text, response=response, wait=wait): yield
Execute the wrapped code, accepting a prompt, optionally responding to the prompt. Args: text (str | RegexObject, optional): Text to match against the text in the modal. response (str, optional): Response to provide to the prompt. wait (int | float, optional): Maximum time t...
340,612
def finalize(self): ddb_files = list(filter(None, [work.outdir.has_abiext("DDB") for work in self])) out_ddb = self.outdir.path_in("out_DDB") desc = "DDB file merged by %s on %s" % (self.__class__.__name__, time.asctime()) mrgddb = wrappers.Mrgddb(manager=sel...
This method is called when the flow is completed.
340,613
def line_point_(self, label=None, style=None, opts=None, options={}, colors={"line": "orange", "point": " try: if style is None: style = self.chart_style if "size" not in style: style["size"] = 10 style["color"] = colors["line"] c = self._get_chart("line", style=style, opts=opts, ...
Get a line and point chart
340,614
def model_enums(vk, model): model[] = {} enums_type = [x[] for x in vk[][][] if x.get() == ] for name in enums_type: model[][name] = {} enums = [x for x in vk[][] if x.get() in (, )] for enum in enums: name = enum[] t = enum.g...
Fill the model with enums model['enums'] = {'name': {'item_name': 'item_value'...}, ...}
340,615
def parse(cls, value, default=_no_default): if isinstance(value, cls): return value elif isinstance(value, six.integer_types) and not isinstance(value, EnumBase): e = cls._value_to_member.get(value, _no_default) else: e = cls._name_to_member.get(value...
Parses an enum member name or value into an enum member. Accepts the following types: - Members of this enum class. These are returned directly. - Integers. If there is an enum member with the integer as a value, that member is returned. - Strings. If there is an enum member with the st...
340,616
def connect(self, fedora_url, data=None, method=): if data is None: data = {} if not fedora_url.startswith("http"): fedora_url = urllib.parse.urljoin(self.base_url, fedora_url) request = urllib.request.Request(fedor...
Method attempts to connect to REST servers of the Fedora Commons repository using optional data parameter. Args: fedora_url(string): Fedora URL data(dict): Data to through to REST endpoint method(str): REST Method, defaults to GET Returns: result...
340,617
async def list_state(self, request): paging_controls = self._get_paging_controls(request) head, root = await self._head_to_root(request.url.query.get( , None)) validator_query = client_state_pb2.ClientStateListRequest( state_root=root, address=reques...
Fetches list of data entries, optionally filtered by address prefix. Request: query: - head: The id of the block to use as the head of the chain - address: Return entries whose addresses begin with this prefix Response: data: An a...
340,618
def _pull_all(command): page = requests.get(BASE_URL,verify=False) soup = BeautifulSoup(page.text,"lxml") table = soup.find(,{:}) rows = table.findAll("tr") rows = rows[1:-1] l = [] name_max = 0 for row in rows: elements = row.findAll() date = elements[0].string name = elements[1].string n = _ascii_c...
Website scraper for the info from table content
340,619
def fake2db_logger(): username = getpass.getuser() FORMAT = logging.basicConfig(format=FORMAT) extra_information = {: username} logger = logging.getLogger() return logger, extra_information
creates a logger obj
340,620
def load_metadata(refresh_cache=False): cache = get_metadata_cache() if refresh_cache: cache.refresh() if not cache.is_open: cache.open() return cache.graph
Returns a graph representing meta-data for all Project Gutenberg texts. Pertinent information about texts or about how texts relate to each other (e.g. shared authors, shared subjects) can be extracted using standard RDF processing techniques (e.g. SPARQL queries). After making an initial remote call to...
340,621
def simulate( cls, epm_or_path, weather_data_or_path, base_dir_path, simulation_name=None, stdout=None, stderr=None, beat_freq=None ): if not os.path.isdir(base_dir_path): raise NotA...
Parameters ---------- epm_or_path weather_data_or_path base_dir_path: simulation dir path simulation_name: str, default None if provided, simulation will be done in {base_dir_path}/{simulation_name} else, simulation will be done in {base_dir_path} ...
340,622
def _get_redis_cache_opts(): return { : __opts__.get(, ), : __opts__.get(, 6379), : __opts__.get(, None), : __opts__.get(, ), : __opts__.get(, ), : __opts__.get(, False), : __opts__.get(, {}), : __opts__.get(, False), }
Return the Redis server connection details from the __opts__.
340,623
def update_contribution_entry(database, entry): entry = clean_entry(entry) database.contributions.update( {: entry[]}, {: entry}, upsert=True )
Update a record of a contribution report in the provided database. @param database: The MongoDB database to operate on. The contributions collection will be used from this database. @type db: pymongo.database.Database @param entry: The entry to insert into the database, updating the entry with ...
340,624
def parse_name(name): bucket = None item = None m = re.match(_STORAGE_NAME, name) if m: bucket = m.group(1) item = m.group(2) if item is not None: item = item[1:] else: m = re.match( + _OBJECT_NAME + , name) if m: item = m.group(1) return bucket, item
Parse a gs:// URL into the bucket and item names. Args: name: a GCS URL of the form gs://bucket or gs://bucket/item Returns: The bucket name (with no gs:// prefix), and the item name if present. If the name could not be parsed returns None for both.
340,625
def serializeAuthors(self): author_details = [] auid = tethnedao.getMaxAuthorID() for val in self.corpus.features[].index.values(): auid = auid + 1 self.authorIdMap[val[1]+val[0]] = auid instanceData = { "model": "django-tethne.aut...
This method creates a fixture for the "django-tethne_author" model. Returns ------- Author details in JSON format, which can be written to a file.
340,626
def bundle(self, ref, capture_exceptions=False): from ..orm.exc import NotFoundError if isinstance(ref, Dataset): ds = ref else: try: ds = self._db.dataset(ref) except NotFoundError: ds = None if not ds: ...
Return a bundle build on a dataset, with the given vid or id reference
340,627
def get_unit_waveforms(recording, sorting, unit_ids=None, grouping_property=None, start_frame=None, end_frame=None, ms_before=3., ms_after=3., dtype=None, max_num_waveforms=np.inf, filter=False, bandpass=[300, 6000], save_as_features=True, verbose=False, compute_property_from_r...
This function returns the spike waveforms from the specified unit_ids from t_start and t_stop in the form of a numpy array of spike waveforms. Parameters ---------- recording sorting unit_ids grouping_property start_frame end_frame ms_before ms_after dtype max_num_wa...
340,628
def has_path(self, path, method=None): method = self._normalize_method_name(method) path_dict = self.get_path(path) path_dict_exists = path_dict is not None if method: return path_dict_exists and method in path_dict return path_dict_exists
Returns True if this Swagger has the given path and optional method :param string path: Path name :param string method: HTTP method :return: True, if this path/method is present in the document
340,629
def make_tar(tfn, source_dirs, ignore_path=[], optimize_python=True): def select(fn): rfn = realpath(fn) for p in ignore_path: if p.endswith(): p = p[:-1] if rfn.startswith(p): return False if rfn in python_files: ...
Make a zip file `fn` from the contents of source_dis.
340,630
def set_session_password(self, password): assert len(password) <= 8, return self.library.Cli_SetSessionPassword(self.pointer, c_char_p(six.b(password)))
Send the password to the PLC to meet its security level.
340,631
def _replace_property(property_key, property_value, resource, logical_id): if property_key and property_value: resource.get(PROPERTIES_KEY, {})[property_key] = property_value elif property_key or property_value: LOG.info("WARNING: Ignoring Metadata for Resource %s. Metad...
Replace a property with an asset on a given resource This method will mutate the template Parameters ---------- property str The property to replace on the resource property_value str The new value of the property resource dict Dictio...
340,632
def _parse_ident(self): remainder = self.string[self.pos:] ident = re.match(r, remainder).group(0) self.pos += len(ident) return ident
Parse an identifier and return it (possibly an empty string). Updates ``pos``.
340,633
def doi(self): if not ISBN.hyphenRange: ISBN.hyphenRange = hyphen.ISBNRange() seg = ISBN.hyphenRange.hyphensegments(self._id) return + self._id[0:3] + + \ self._id[3:-(1 + seg[3])] + + self._id[-(1 + seg[3]):]
Returns ISBN number with segment hypenation Data obtained from https://www.isbn-international.org/ https://www.isbn-international.org/export_rangemessage.xml @return: ISBN formated as ISBN13 with hyphens
340,634
def replace_variable(self, variable): if variable == : return self.value if variable == : return self.timedelta raise ValueError("Invalid variable %s", variable)
Substitute variables with numeric values
340,635
def availableVersions(self): r = [] for t in self.vcs.tags(): logger.debug("available version tag: %s", t) if not len(t.strip()): continue try: r.append(GitCloneVersion(t, t, self)) except ValueError: ...
return a list of GitCloneVersion objects for tags which are valid semantic version idenfitifiers.
340,636
def target_data(self): if self._td is not None: return self._td ptr = ffi.lib.LLVMPY_GetExecutionEngineTargetData(self) self._td = targets.TargetData(ptr) self._td._owned = True return self._td
The TargetData for this execution engine.
340,637
def GetParentFileEntry(self): volume_index = lvm.LVMPathSpecGetVolumeIndex(self.path_spec) if volume_index is None: return None return self._file_system.GetRootFileEntry()
Retrieves the parent file entry. Returns: LVMFileEntry: parent file entry or None if not available.
340,638
def _diff_internal(d1,d2): axbyczaxbudv same =[] kdiff =[] vdiff = [] for key in d1: value = d1[key] if(key in d2): if(value == d2[key]): same.append(key) else: vdiff.append(key) else: kdiff.append(key) r...
d1 = {'a':'x','b':'y','c':'z'} d2 = {'a':'x','b':'u','d':'v'} _diff_internal(d1,d2) _diff_internald2,d1)
340,639
def logout(anchore_config): ecode = 0 try: aa = contexts[] if aa: anchore_auth.anchore_auth_invalidate(aa) if in aa: os.remove(aa[]) print "Logout successful." except Exception as err: anchore_print_err() ecode = 1 sy...
Log out of Anchore service
340,640
def write_PROM_HOTB_progenitor(self,name,description): try: from ProgenitorHotb_new import ProgenitorHotb_new except ImportError: print() return nz=len(self.get()) prog=ProgenitorHotb_new(nz) prog.header = +description+ ...
Write a progenitor file for the PROMETHEUS/HBOT supernova code. Parameters ---------- name : string File name for the progenitor file description : string Information to be written into the file header.
340,641
def _clean_global_uninteresting_paths(self): uninteresting_dest_count = 0 interested_rts = self._rt_mgr.global_interested_rts LOG.debug(, interested_rts) for route_family in [RF_IPv4_VPN, RF_IPv6_VPN, RF_RTC_UC]: if route_f...
Marks paths that do not have any route targets of interest for withdrawal. Since global tables can have paths with route targets that are not interesting any more, we have to clean these paths so that appropriate withdraw are sent out to NC and other peers. Interesting route targets ...
340,642
def portals(self): url = "%s/portals" % self.root return _portals.Portals(url=url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)
returns the Portals class that provides administration access into a given organization
340,643
def exitcode(self): if self._process is None: raise ProcessError( "Process has not been started yet" % self.name) return self._process.exitcode
Process exit code. :const:`0` when process exited successfully, positive number when exception was occurred, negative number when process was signaled and :data:`None` when process has not exited yet.
340,644
def setLoc(self, loc): self.loc = loc self.rect[0] = self.loc[0] self.rect[1] = self.loc[1]
Sets a new location (and changes the rect loc) for this widget.
340,645
def _asynciostacks(*args, **kwargs): print(80 * ) print() tasks = asyncio.all_tasks(_glob_loop) for task in tasks: task.print_stack() print(80 * ) print() faulthandler.dump_traceback() print(80 * )
A signal handler used to print asyncio task stacks and thread stacks.
340,646
def encodeRNA(seq_vec, maxlen=None, seq_align="start"): return encodeSequence(seq_vec, vocab=RNA, neutral_vocab="N", maxlen=maxlen, seq_align=seq_align, pad_value="N", ...
Convert the RNA sequence into 1-hot-encoding numpy array as for encodeDNA
340,647
def create_custom_views(auth, url, name=None, upperview=None): create_custom_views_url = \ f_url = url + create_custom_views_url if upperview is None: payload = + name + else: parentviewid = get_custom_views(auth, url, upperview)[0][] paylo...
function takes no input and issues a RESTFUL call to get a list of custom views from HPE IMC. Optional Name input will return only the specified view. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeim...
340,648
def get(self, request): try: client = request.session[self.get_client().get_session_key()] logger.debug("API returned: %s", request.GET) client.complete(dict(request.GET.items())) request.session[self.get_client().get_session_key()] = client ...
Called after the user is redirected back to our application. Tries to: - Complete the OAuth / OAuth2 flow - Redirect the user to another view that deals with login, connecting or user creation.
340,649
def find_bucket(self, bucketing_id, parent_id, traffic_allocations): bucketing_key = BUCKETING_ID_TEMPLATE.format(bucketing_id=bucketing_id, parent_id=parent_id) bucketing_number = self._generate_bucket_value(bucketing_key) self.config.logger.debug( % ( bucketing_number, bucketing_id )...
Determine entity based on bucket value and traffic allocations. Args: bucketing_id: ID to be used for bucketing the user. parent_id: ID representing group or experiment. traffic_allocations: Traffic allocations representing traffic allotted to experiments or variations. Returns: Entity...
340,650
def match_rstring(self, tokens, item): name, suffix = tokens return self.match_mstring((None, name, suffix), item, use_bytes=suffix.startswith("b"))
Match suffix string.
340,651
def render_relation(self, r, **args): if r is None: return "." m = self.config.relsymbolmap if r in m: return m[r] return r
Render an object property
340,652
def execute(self, action): action_mappings, axis_mappings = [], [] if self.discretize_actions: combination = self.discretized_actions[action] for key, value in combination: if isinstance(value...
Executes a single step in the UE4 game. This step may be comprised of one or more actual game ticks for all of which the same given action- and axis-inputs (or action number in case of discretized actions) are repeated. UE4 distinguishes between action-mappings, which are boolean actions (e.g. j...
340,653
def attribute_format(frmt: str) -> BufferFormat: try: return ATTRIBUTE_FORMATS[frmt] except KeyError: raise ValueError("Buffer format unknown. Valid formats: {}".format( frmt, ATTRIBUTE_FORMATS.keys() ))
Look up info about an attribute format :param frmt: Format of an :return: BufferFormat instance
340,654
def to_json(obj, indent=4, sort_keys=True, **kwargs): obj_dict = to_dict(obj, **kwargs) return json.dumps(obj_dict, indent=indent, sort_keys=sort_keys)
:param obj: object to convert to dictionary and then output to json :param indent: indent json by number of spaces :param sort_keys: sort json output by key if true :param kwargs: arguments to pass to to_dict :return: json string
340,655
def from_yaml(*streams): return from_dict(merge_dicts(*map( lambda f: yaml.load(f, Loader=Loader), list(streams) )))
Build voluptuous.Schema function parameters from a streams of YAMLs
340,656
def download(url, file_name): r = requests.get(url, stream=True) file_size = int(r.headers[]) file_exists = False if os.path.isfile(file_name): local_file_size = os.path.getsize(file_name) if local_file_size == file_size: sha1_file = file_name + if ...
if py3: file_size = int(u.getheader("Content-Length")[0]) else: file_size = int(u.info().getheaders("Content-Length")[0])
340,657
def __analyse_objects(self, image_source, color_analyser, collect_dynamic): pointer_image = Image.open(image_source); image_size = pointer_image.size; object_analysers = []; color_segments = color_analyser.allocate_clusters(); ...
! @brief Performs object segmentation by the second layer. @param[in] image_source (string): Path to image file that should be processed. @param[in] color_analyser (syncnet_analyser): Analyser of color segmentation results. @param[in] collect_dynamic (bool): If 'True' then ...
340,658
def _scan_nodes(nodelist, context, instance_types, current_block=None, ignore_blocks=None): results = [] for node in nodelist: if isinstance(node, instance_types): results.append(node) if node.template: ...
Loop through all nodes of a single scope level. :type nodelist: django.template.base.NodeList :type current_block: BlockNode :param instance_types: The instance to look for
340,659
def intersection(self, coordinates, objects=False): if objects: return self._intersection_obj(coordinates, objects) p_mins, p_maxs = self.get_coordinate_pointers(coordinates) p_num_results = ctypes.c_uint64(0) it = ctypes.pointer(ctypes.c_int64()) core.r...
Return ids or objects in the index that intersect the given coordinates. :param coordinates: sequence or array This may be an object that satisfies the numpy array protocol, providing the index's dimension * 2 coordinate pairs representing the `mink` and `maxk` coord...
340,660
def get_session(credentials, config): session = requests.Session() session.verify = False auth_url = config.get("auth_url") if auth_url: cookie = session.post( auth_url, data={ "j_username": credentials[0], "j_password": credentials[1...
Gets requests session.
340,661
def encoding(self): encoding = None ct = self.get_header() if ct: ah = AcceptHeader(ct) if ah.media_types: encoding = ah.media_types[0][2].get("charset", None) return encoding
the character encoding of the request, usually only set in POST type requests
340,662
def _build_inventory(self, cluster): inventory_data = defaultdict(list) for node in cluster.get_all_nodes(): if node.preferred_ip is None: log.warning( "Ignoring node `{0}`: No IP address." .format(node.name)) ...
Builds the inventory for the given cluster and returns its path :param cluster: cluster to build inventory for :type cluster: :py:class:`elasticluster.cluster.Cluster`
340,663
def get_mix_gen(self, sample): def mix(length): result = "".join(random.choice(sample) for _ in xrange(length)).strip() if len(result) == length: return result return mix(length) return mix
Returns function that returns sequence of characters of a given length from a given sample
340,664
def payload(self): _msg = as_unicode(self.part[1]) if "cty" in self.headers and self.headers["cty"].lower() != "jwt": pass else: try: _msg = json.loads(_msg) except ValueError: pass return _msg
Picks out the payload from the different parts of the signed/encrypted JSON Web Token. If the content type is said to be 'jwt' deserialize the payload into a Python object otherwise return as-is. :return: The payload
340,665
def delete(self, key): self.logger.info( % (self, key)) super(LoggingDatastore, self).delete(key)
Removes the object named by `key`. LoggingDatastore logs the access.
340,666
def map(cls, visitor, value, value_type): unpacked = visitor.unpack(value, value_type, visitor) if unpacked == cls.StopVisiting or isinstance( unpacked, cls.StopVisiting ): return unpacked.return_value if isinstance(unpacked, tuple): props, ...
The common visitor API used by all three visitor implementations. args: ``visitor=``\ *Visitor* Visitor options instance: contains the callbacks to use to implement the visiting, as well as traversal & filtering options. ``value=``\ *Obj...
340,667
def cmap2pixmap(cmap, steps=50): import numpy as np inds = np.linspace(0, 1, steps) n = len(cmap.clst) - 1 tups = [cmap.clst[int(x * n)] for x in inds] rgbas = [QColor(int(r * 255), int(g * 255), int(b * 255), 255).rgba() for r, g, b in tups] im = QImage(steps, 1, QImag...
Convert a Ginga colormap into a QPixmap
340,668
def set_item(self, index, new_item): row = index.row() if hasattr(index, "row") else index self.collection[row] = new_item self.dataChanged.emit(self.index( row, 0), self.index(row, self.rowCount() - 1))
Changes item at index in collection. Emit dataChanged signal. :param index: Number of row or index of cell :param new_item: Dict-like object
340,669
def get_version(): version_py = os.path.join(os.path.dirname(__file__), , ) with open(version_py, ) as fh: for line in fh: if line.startswith(): return line.split()[-1].strip().replace(, ) raise ValueError(.format(version_py))
Gets the current version of the package.
340,670
def append(self, s, charset=None, errors=): if charset is None: charset = self._charset elif not isinstance(charset, Charset): charset = Charset(charset) if not isinstance(s, str): input_charset = charset.input_codec or if input_charset =...
Append a string to the MIME header. Optional charset, if given, should be a Charset instance or the name of a character set (which will be converted to a Charset instance). A value of None (the default) means that the charset given in the constructor is used. s may be a byte s...
340,671
def _iterate_records(self): raise_invalid_gzip = False empty_record = False while True: try: self.record = self._next_record(self.next_line) if raise_invalid_gzip: self._raise_invalid_gzip_err() yield self...
iterate over each record
340,672
def GetFormattedField(self, event, field_name): callback_name = self._FIELD_FORMAT_CALLBACKS.get(field_name, None) callback_function = None if callback_name: callback_function = getattr(self, callback_name, None) if callback_function: output_value = callback_function(event) else: ...
Formats the specified field. Args: event (EventObject): event. field_name (str): name of the field. Returns: str: value of the field.
340,673
def requester( url, main_url=None, delay=0, cook=None, headers=None, timeout=10, host=None, proxies=[None], user_agents=[None], failed=None, processed=None ): cook = cook or set() headers = headers or set() user...
Handle the requests and return the response body.
340,674
def get_views(self, mo_refs, properties=None): property_specs = [] for mo_ref in mo_refs: property_spec = self.create() property_spec.type = str(mo_ref._type) if properties is None: properties = [] else: ...
Get a list of local view's for multiple managed objects. :param mo_refs: The list of ManagedObjectReference's that views are \ to be created for. :type mo_refs: ManagedObjectReference :param properties: The properties to retrieve in the views. :type properties: list :ret...
340,675
def dechex(num,zfill=0): 0004 if not isitint(num): raise TypeError("Input must be integer/long.") o = hex(num).lstrip("0x").rstrip("L") if o == "" or o == "0": o = try: o = unhexlify(o) except: o = unhexlify("0"+o) if o == b or o == 0: o = else:...
Simple integer to hex converter. The zfill is the number of bytes, even though the input is a hex string, which means that the actual zfill is 2x what you might initially think it would be. For example: >>> dechex(4,2) '0004'
340,676
def make_report(isodate=): if isodate == : isodate = date.today() else: isodate = date(*time.strptime(isodate, )[:3]) isodate1 = isodate + timedelta(1) tag_ids = [] tag_status = [] tag_contents = [] jobs = dbcmd( , ALL_JOBS, isodate.isoformat(), isodate1...
Build a HTML report with the computations performed at the given isodate. Return the name of the report, which is saved in the current directory.
340,677
def p_term_mult_factor(self, args): op = if args[1].attr == else return AST(op, [args[0], args[2]])
term ::= term MULT_OP factor
340,678
def get_best_candidate(self): self.incumbent = self.surrogate.Y.max() def z(x): x = x.copy().reshape(-1, self.n_dims) y_mean, y_var = self.surrogate.predict(x) af = self._acquisition_function(y_mean=y_mean, y_var=y_var) ...
Returns ---------- best_candidate : the best candidate hyper-parameters as defined by
340,679
def parse_age(value=None): if not value: return None try: seconds = int(value) except ValueError: return None if seconds < 0: return None try: return timedelta(seconds=seconds) except OverflowError: return None
Parses a base-10 integer count of seconds into a timedelta. If parsing fails, the return value is `None`. :param value: a string consisting of an integer represented in base-10 :return: a :class:`datetime.timedelta` object or `None`.
340,680
def url_stats(self, short): data = dict(action=, shorturl=short) jsondata = self._api_request(params=data) return _json_to_shortened_url(jsondata[])
Get stats for short URL or keyword. Parameters: short: Short URL (http://example.com/abc) or keyword (abc). Returns: ShortenedURL: Shortened URL and associated data. Raises: ~yourls.exceptions.YOURLSHTTPError: HTTP error with response from Y...
340,681
def mount_configure_send(self, target_system, target_component, mount_mode, stab_roll, stab_pitch, stab_yaw, force_mavlink1=False): return self.send(self.mount_configure_encode(target_system, target_component, mount_mode, stab_roll, stab_pitch, stab_yaw), force_mavlink1=force_mavlink1)
Message to configure a camera mount, directional antenna, etc. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) mount_mode : mount operating mode (see MAV_MOUNT_MODE enum) (uint8_t) stab_rol...
340,682
def get_colour_handler(extranames: List[str] = None, with_process_id: bool = False, with_thread_id: bool = False, stream: TextIO = None) -> logging.StreamHandler: fmt = "%(white)s%(asctime)s.%(msecs)03d" if with_process_id or with_threa...
Gets a colour log handler using a standard format. Args: extranames: additional names to append to the logger's name with_process_id: include the process ID in the logger's name? with_thread_id: include the thread ID in the logger's name? stream: ``TextIO`` stream to send log output...
340,683
def enclosing_box(boxes): x = max(0, min([box.x for box in boxes])) y = max(0, min([box.y for box in boxes])) x2 = max([box.bottom_right()[0] for box in boxes]) y2 = max([box.bottom_right()[1] for box in boxes]) return Box.from_xy(x, y, x2, y2)
Finds a new box that exactly encloses all the given boxes. :param boxes: Array of Box objects :return: Box object that encloses all boxes
340,684
def start_session(self): self.__current_row = self.__history_mode = False self.__editable_history = deepcopy(self.__history) self.__prompt_show = True self.refresh_window()
Start new session and prepare environment for new row editing process :return: None
340,685
def task2ics(): from argparse import ArgumentParser, FileType from sys import stdout parser = ArgumentParser(description=) parser.add_argument(, nargs=, help=, default=expanduser()) parser.add_argument(, nargs=, type=FileType(), default=stdout, help=) args = parser....
Command line tool to convert from Taskwarrior to iCalendar
340,686
def notification_is_blocked_by_contact(self, notifways, timeperiods, notif, contact): return not contact.want_host_notification(notifways, timeperiods, self.last_chk, self.state, notif.type, self.busines...
Check if the notification is blocked by this contact. :param notif: notification created earlier :type notif: alignak.notification.Notification :param contact: contact we want to notify :type notif: alignak.objects.contact.Contact :return: True if the notification is blocked, Fa...
340,687
def convert_ilsvrc2012(directory, output_directory, output_filename=, shuffle_seed=config.default_seed): devkit_path = os.path.join(directory, DEVKIT_ARCHIVE) train, valid, test = [os.path.join(directory, fn) for fn in IMAGE_TARS] n_train, valid_groundtruth...
Converter for data from the ILSVRC 2012 competition. Source files for this dataset can be obtained by registering at [ILSVRC2012WEB]. Parameters ---------- input_directory : str Path from which to read raw data files. output_directory : str Path to which to save the HDF5 file. ...
340,688
def cursor(self, *cursors): self._ensure_alive() self._last_usage = self._loop.time() try: if cursors and \ any(not issubclass(cursor, Cursor) for cursor in cursors): raise TypeError() except TypeError: raise TypeError(...
Instantiates and returns a cursor By default, :class:`Cursor` is returned. It is possible to also give a custom cursor through the cursor_class parameter, but it needs to be a subclass of :class:`Cursor` :param cursor: custom cursor class. :returns: instance of cursor, by defa...
340,689
def enable_svc_freshness_check(self, service): if not service.check_freshness: service.modified_attributes |= DICT_MODATTR["MODATTR_FRESHNESS_CHECKS_ENABLED"].value service.check_freshness = True self.send_an_element(service.get_update_status_brok())
Enable freshness check for a service Format of the line that triggers function call:: ENABLE_SERVICE_FRESHNESS_CHECK;<host_name>;<service_description> :param service: service to edit :type service: alignak.objects.service.Service :return: None
340,690
def _calc_result(self, results, calc): lg = logging.getLogger("%s.%s" % (self.ln, inspect.stack()[0][3])) lg.setLevel(self.log_level) if calc is None: return results lg.debug("calc %s", calc) hits = results.get(,{}).get(,[]) ...
parses the calc string and then reads the results and returns the new value Elasticsearch no longer allow dynamic in scripting args: results: the list of results from Elasticsearch calc: the calculation sting returns: refomated results list with calc...
340,691
def delete_user_id(self, user_id, mount_point=): return self._adapter.delete(.format(mount_point, user_id))
DELETE /auth/<mount_point>/map/user-id/<user_id> :param user_id: :type user_id: :param mount_point: :type mount_point: :return: :rtype:
340,692
def loadFeatureWriterFromString(spec): spec = spec.strip() m = _featureWriterSpecRE.match(spec) if not m or (m.end() - m.start()) != len(spec): raise ValueError(spec) moduleName = m.group(1) or "ufo2ft.featureWriters" className = m.group(2) kwargs = m.group(3) module = importli...
Take a string specifying a feature writer class to load (either a built-in writer or one defined in an external, user-defined module), initialize it with given options and return the writer object. The string must conform to the following notation: - an optional python module, followed by '::' - a ...
340,693
def _switch_charset_dict(characters, target=): offset_characters = {} offset = block_offset * offsets[target][] for char in characters: offset_key = chr(ord(char) + offset) offset_value = chr(ord(characters[char]) + offset) offset_characters[offset_key] = offset_value retur...
Switches the character set of the key/value pairs in a dictionary.
340,694
def cmy(self): r, g, b = self.color c = 1 - r m = 1 - g y = 1 - b return (c, m, y)
CMY: returned in range 0.0 - 1.0 CMY is subtractive, e.g. black: (1, 1, 1), white (0, 0, 0)
340,695
def process_synonyms(self, entity: List[dict]) -> List[dict]: label = entity[] for synonym in entity[]: if not in synonym: raise ValueError(f) elif len(synonym) > 1: raise ValueError(f) return entity
Making sure key/value is in proper format for synonyms in entity
340,696
def get_association(id, **kwargs): results = search_associations(id=id, **kwargs) assoc = results[][0] if len(results[]) > 0 else {} return assoc
Fetch an association object by ID
340,697
def convertImages(self): exts=[,] for fname in [x for x in self.files1 if cm.ext(x) in exts]: ID="UNKNOWN" if len(fname)>8 and fname[:8] in self.IDs: ID=fname[:8] fname2=ID+"_jpg_"+fname if not fname2 in self.files2: ...
run this to turn all folder1 TIFs and JPGs into folder2 data. TIFs will be treated as micrographs and converted to JPG with enhanced contrast. JPGs will simply be copied over.
340,698
def AnalyzeAPK(_file, session=None, raw=False): log.debug("AnalyzeAPK") if session: log.debug("Using existing session {}".format(session)) if raw: data = _file filename = hashlib.md5(_file).hexdigest() else: with open(_file, "rb") as fd: ...
Analyze an android application and setup all stuff for a more quickly analysis! If session is None, no session is used at all. This is the default behaviour. If you like to continue your work later, it might be a good idea to use a session. A default session can be created by using :meth:`~get_d...
340,699
def _check_choices_attribute(self): if self.choices: warning_params = { : ( " contains an invalid time zone value " "which was not found as a supported time zone by pytz " "{version}." ), ...
Checks to make sure that choices contains valid timezone choices.