Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
346,900
def add_rule(self, start_col, start_row, end_col, end_row, width=0.5, color=(0,0,0)): self.rules.append( (start_col, start_row, end_col, end_row, width, color) )
Adds a rule to the grid. The row and column numbers are those on the top left of the corresponding cell in the grid. So if the grid is 10x10, then the right hand edge of the grid will be column 10, and the bottom will be column 10. In other words there is one more rule-row and column tha...
346,901
def run(self, parameter_space, kernel_options, tuning_options): logging.debug( + kernel_options.kernel_name) results = [] for element in parameter_space: params = OrderedDict(zip(tuning_options.tune_params.keys(), element)) time = self.dev.compile_and...
Iterate through the entire parameter space using a single Python process :param parameter_space: The parameter space as an iterable. :type parameter_space: iterable :param kernel_options: A dictionary with all options for the kernel. :type kernel_options: kernel_tuner.interface.Options...
346,902
def list_suites(suitedir="./testcases/suites", cloud=False): suites = [] suites.extend(TestSuite.get_suite_files(suitedir)) if cloud: names = cloud.get_campaign_names() if names: suites.append("------------------------------------") ...
Static method for listing suites from both local source and cloud. Uses PrettyTable to generate the table. :param suitedir: Local directory for suites. :param cloud: cloud module :return: PrettyTable object or None if no test cases were found
346,903
def _run_check_cmd(self, low_data): ret = {: False} cmd_opts = {} if in self.opts[]: cmd_opts[] = self.opts[].get() for entry in low_data[]: cmd = self.functions[]( entry, ignore_retcode=True, python_shell=True, **cmd_opts) lo...
Alter the way a successful state run is determined
346,904
def _get_prop_from_modelclass(modelclass, name): if name == : return modelclass._key parts = name.split() part, more = parts[0], parts[1:] prop = modelclass._properties.get(part) if prop is None: if issubclass(modelclass, model.Expando): prop = model.GenericProperty(part) else: rai...
Helper for FQL parsing to turn a property name into a property object. Args: modelclass: The model class specified in the query. name: The property name. This may contain dots which indicate sub-properties of structured properties. Returns: A Property object. Raises: KeyError if the prop...
346,905
def parse_torrent_properties(table_datas): output = {: table_datas[0].text, : None, : None, : None} for i in range(1, len(table_datas)): td = table_datas[i] url = td.get() params = Parser.get_params(url) if Parser.is_subcategory(params) and not ou...
Static method that parses a given list of table data elements and using helper methods `Parser.is_subcategory`, `Parser.is_quality`, `Parser.is_language`, collects torrent properties. :param list lxml.HtmlElement table_datas: table_datas to parse :return: identified category, subcategory, quali...
346,906
def toggle_rich_text(self, checked): if checked: self.docstring = not checked self.switch_to_rich_text() self.set_option(, checked)
Toggle between sphinxified docstrings or plain ones
346,907
def print_table(title, headers, rows, sort_columns=None): if sort_columns is not None: if isinstance(sort_columns, int): rows = sorted(rows, key=itemgetter(sort_columns)) elif isinstance(sort_columns, (list, tuple)): rows = sorted(rows, key=itemgetter(*sort_columns)) ...
Print a table of rows with headers using tabulate. Parameters: title (:term: string): String that will be output before the Table. headers (list or tuple): List of strings that defines the header for each row. Each string in this list may be multiline by inserting...
346,908
def post(self, client_method, data, post_params=None, is_json=True): url = self._wa.apollo_url + self.CLIENT_BASE + client_method if post_params is None: post_params = {} headers = { : } data.update({ : self._wa.username, ...
Make a POST request
346,909
def add_manual_segmentation_to_data_frame(self, data_frame, segmentation_dictionary): data_frame[] = for i, (k, v) in enumerate(segmentation_dictionary.items()): for start, end in v: if type(start) != np.datetime64...
Utility method to store manual segmentation of gait time series. :param data_frame: The data frame. It should have x, y, and z columns. :type data_frame: pandas.DataFrame :param segmentation_dictionary: A dictionary of the form {'signal_type': [(from, to), (from, to)], ..., 'signal_...
346,910
def ifi_type(self, value): self.bytearray[self._get_slicers(2)] = bytearray(c_ushort(value or 0))
Type setter.
346,911
def availability(self, participants=(), required_duration=(), available_periods=(), start_interval=None, buffer=()): options = {} options[] = self.map_availability_participants( participants) options[] = self.map_availability_required_duration( required_duration)...
Performs an availability query. :param list participants: An Array of participant groups or a dict for a single participant group. :param dict or int required_duration - An Integer representing the minimum number of minutes of availability required. :param list available_periods - An Array of av...
346,912
def save(self, **kwargs): if self.output_path: write_ipynb(self.nb, self.output_path)
Saves the wrapped notebook state. If an output path is known, this triggers a save of the wrapped notebook state to the provided path. Can be used outside of cell state changes if execution is taking a long time to conclude but the notebook object should be synced. For example...
346,913
def _search_names(self, query): regexp = re.compile(query, re.IGNORECASE | re.DOTALL) for contact in self.contacts.values(): if regexp.search(contact.get_full_name()) is not None: yield contact
Search in the name filed for contacts matching query. :param query: the query to search for :type query: str :yields: all found contacts :rtype: generator(carddav_object.CarddavObject)
346,914
def add_sections(app, doctree, fromdocname): needs = getattr(app.builder.env, , {}) for key, need_info in needs.items(): sections = get_sections(need_info) need_info[] = sections need_info[] = sections[0] if sections else ""
Add section titles to the needs as additional attributes that can be used in tables and filters
346,915
def path(self): if self.origin: return six.text_type(self.origin / self.relpath) else: return six.text_type(self.relpath)
Concatenation of ``origin`` and ``relpath``, as a string. Used in stack traces and other debugging places.
346,916
def finalize(self): self._comboboxListView.removeEventFilter(self) self.comboBox.model().rowsInserted.disconnect(self.comboBoxRowsInserted) self.comboBox.activated.disconnect(self.comboBoxActivated) super(ChoiceCtiEditor, self).finalize()
Is called when the editor is closed. Disconnect signals.
346,917
def from_xml(content_types_xml): types_elm = parse_xml(content_types_xml) ct_map = _ContentTypeMap() for o in types_elm.override_lst: ct_map._add_override(o.partName, o.contentType) for d in types_elm.default_lst: ct_map._add_default(d.extension, d.conten...
Return a new |_ContentTypeMap| instance populated with the contents of *content_types_xml*.
346,918
def print_stack_info(self): try: rest_api_id = None deployment_found = False response = self._cf_client.describe_stack_resources( StackName=self._stack_name ) print() rows = [] for resource in response...
List resources from the given stack Args: None Returns: A dictionary filled resources or None if things went sideways
346,919
def find_coord_vars(ncds): coord_vars = [] for d in ncds.dimensions: if d in ncds.variables and ncds.variables[d].dimensions == (d,): coord_vars.append(ncds.variables[d]) return coord_vars
Finds all coordinate variables in a dataset. A variable with the same name as a dimension is called a coordinate variable.
346,920
def upgrade(refresh=False, **kwargs): <package>old<old-version>new<new-version>* if salt.utils.data.is_true(refresh): refresh_db() old = list_pkgs() cmd = [, , , ] result = __salt__[](cmd, output_loglevel=, ...
Upgrade all packages to the latest possible version. When run in global zone, it updates also all non-global zones. In non-global zones upgrade is limited by dependency constrains linked to the version of pkg://solaris/entire. Returns a dictionary containing the changes: .. code-block:: python ...
346,921
def genkeyhex(): while True: key = hash256( hexlify(os.urandom(40) + str(datetime.datetime.now()) .encode("utf-8"))) if int(key,16) > 1 and int(key,16) < N: break return ke...
Generate new random Bitcoin private key, using os.urandom and double-sha256. Hex format.
346,922
def get_consumption(self, deviceid, timerange="10"): tranges = ("10", "24h", "month", "year") if timerange not in tranges: raise ValueError( "Unknown timerange. Possible values are: {0}".format(tranges) ) url = self.base_url + "/net/home_auto_que...
Return all available energy consumption data for the device. You need to divice watt_values by 100 and volt_values by 1000 to get the "real" values. :return: dict
346,923
def push(self, remote=None, revision=None): self.ensure_exists() if not (remote or self.remote or self.default_push_remote): logger.info("Skipping push (no default remote is configured).") timer = Timer() logger.info("Pushing changes from %...
Push changes from the local repository to a remote repository. :param remote: The location of a remote repository (a string or :data:`None`). :param revision: A specific revision to push (a string or :data:`None`). .. warning:: Depending on the version control backend the push command ...
346,924
def _print_sql_with_error(self, sql, error_line): if os.linesep in sql: lines = sql.split(os.linesep) digits = math.ceil(math.log(len(lines) + 1, 10)) i = 1 for line in lines: if i == error_line: self._io.text(.format(i...
Writes a SQL statement with an syntax error to the output. The line where the error occurs is highlighted. :param str sql: The SQL statement. :param int error_line: The line where the error occurs.
346,925
def connect_post_node_proxy(self, name, **kwargs): kwargs[] = True if kwargs.get(): return self.connect_post_node_proxy_with_http_info(name, **kwargs) else: (data) = self.connect_post_node_proxy_with_http_info(name, **kwargs) return data
connect_post_node_proxy # noqa: E501 connect POST requests to proxy of Node # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.connect_post_node_proxy(name, async_req=True) >>>...
346,926
async def get_resources(self): facade = client.ResourcesFacade.from_connection(self.connection) response = await facade.ListResources([client.Entity(self.tag)]) resources = dict() for result in response.results: for resource in result.charm_store_resources or []: ...
Return resources for this application. Returns a dict mapping resource name to :class:`~juju._definitions.CharmResource` instances.
346,927
def Nu_Gupta(Re, Pr, rho_w=None, rho_b=None, mu_w=None, mu_b=None): r Nu = 0.004*Re**0.923*Pr**0.773 if rho_w and rho_b: Nu *= (rho_w/rho_b)**0.186 if mu_w and mu_b: Nu *= (mu_w/mu_b)**0.366 return Nu
r'''Calculates internal convection Nusselt number for turbulent vertical upward flow in a pipe under supercritical conditions according to [1]_. .. math:: Nu_w = 0.004 Re_w^{0.923} \bar{Pr}_w^{0.773} \left(\frac{\rho_w}{\rho_b}\right)^{0.186} \left(\frac{\mu_w}{\mu_b}\right)^{0....
346,928
def read_td_query(query, engine, index_col=None, parse_dates=None, distributed_join=False, params=None): if params is None: params = {} header = engine.create_header("read_td_query") if engine.type == and distributed_join is not None: header += "-- set session distributed_join = \...
Read Treasure Data query into a DataFrame. Returns a DataFrame corresponding to the result set of the query string. Optionally provide an index_col parameter to use one of the columns as the index, otherwise default integer index will be used. Parameters ---------- query : string Query...
346,929
def extract_changesets(objects): def add_changeset_info(collation, axis, item): if axis not in collation: collation[axis] = {} first = collation[axis] first["id"] = axis first["username"] = item["username"] first["uid"] = item["uid"] first[...
Provides information about each changeset present in an OpenStreetMap diff file. Parameters ---------- objects : osc_decoder class A class containing OpenStreetMap object dictionaries. Returns ------- changeset_collation : dict A dictionary of dictionaries with each changes...
346,930
def load_config(self): actor = get_actor() if actor and actor.is_running(): if self.argv is None: self.console_parsed = False self.cfg.copy_globals(actor.cfg) for name in list(self....
Load the application configuration from a file and/or from the command line. Called during application initialisation. The parameters overriding order is the following: * default parameters. * the key-valued params passed in the initialisation. * the parameters in the o...
346,931
def _jit_predict_fun(model_predict, num_devices): def predict(x, params=(), rng=None): if num_devices == 1: return backend.jit(model_predict)(x, params, rng=rng) @functools.partial(backend.pmap, axis_name="batch") def mapped_predict(x, params, rng): return model_predict(x, p...
Use jit on model_predict if required.
346,932
def CallState(self, messages=None, next_state="", client_id=None, request_data=None, start_time=None): if messages is None: messages = [] if not next_state: raise ValueError("next_state can't be empty.") ...
This method is used to asynchronously schedule a new hunt state. The state will be invoked in a later time and receive all the messages we send. Args: messages: A list of rdfvalues to send. If the last one is not a GrrStatus, we append an OK Status. next_state: The state in this hunt t...
346,933
def h5ToDict(h5, readH5pyDataset=True): h = h5py.File(h5, "r") ret = unwrapArray(h, recursive=True, readH5pyDataset=readH5pyDataset) if readH5pyDataset: h.close() return ret
Read a hdf5 file into a dictionary
346,934
def get_paths_to_root(self, action: str, max_path_length: int = 20, beam_size: int = 30, max_num_paths: int = 10) -> List[List[str]]: action_left_side, _ = action.split() right_side_indexed_a...
For a given action, returns at most ``max_num_paths`` paths to the root (production with ``START_SYMBOL``) that are not longer than ``max_path_length``.
346,935
def index_queryset(self, using=None): kwargs = {"active": True} if hasattr(Page(), ): kwargs[] = True if hasattr(Page(), ): kwargs[] = False return self.get_model().objects.filter(**kwargs)
Used when the entire index for model is updated.
346,936
def confd_state_snmp_version_v1(self, **kwargs): config = ET.Element("config") confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring") snmp = ET.SubElement(confd_state, "snmp") version = ET.SubElement(snmp, "version") v1 = ET.S...
Auto Generated Code
346,937
def iter_orgs(self, number=-1, etag=None): from .orgs import Organization url = self._build_url(, base_url=self._api) return self._iter(int(number), url, Organization, etag=etag)
Iterate over organizations the user is member of :param int number: (optional), number of organizations to return. Default: -1 returns all available organization :param str etag: (optional), ETag from a previous request to the same endpoint :returns: list of :class:`Even...
346,938
def _pack(self, fname, encoding): (fd, tmpfile) = tempfile.mkstemp() os.close(fd) try: self.save(tmpfile, mode=, validate=False) document_loader, processobj, metadata, uri = load_cwl(tmpfile) finally: os.remove(tmpfile) w...
Save workflow with ``--pack`` option This means that al tools and subworkflows are included in the workflow file that is created. A packed workflow cannot be loaded and used in scriptcwl.
346,939
def iiOfAny(instance, classes): if type(classes) not in [list, tuple]: classes = [classes] return any( type(instance).__name__ == cls.__name__ for cls in classes )
Returns true, if `instance` is instance of any (iiOfAny) of the `classes`. This function doesn't use :py:func:`isinstance` check, it just compares the `class` names. This can be generaly dangerous, but it is really useful when you are comparing class serialized in one module and deserialized in anothe...
346,940
def get_native_type(self, java_type): if java_type in ArchSoot.sizeof.keys(): jni_type_size = ArchSoot.sizeof[java_type] else: jni_type_size = self.native_simos.arch.bits return SimTypeReg(size=jni_type_size)
Maps the Java type to a SimTypeReg representation of its native counterpart. This type can be used to indicate the (well-defined) size of native JNI types. :return: A SymTypeReg with the JNI size of the given type.
346,941
def conclude_course(self, id, event): path = {} data = {} params = {} path["id"] = id self._validate_enum(event, ["delete", "conclude"]) params["event"] = event self.logger.debug("DELETE /api/v1/courses/...
Conclude a course. Delete or conclude an existing course
346,942
def allowCommission(self): print % self.port try: cmd = WPANCTL_CMD + print cmd if self.isActiveCommissioner: return True if self.__sendCommand(cmd)[0] != : self.isActiveCommissioner = True time.sl...
start commissioner candidate petition process Returns: True: successful to start commissioner candidate petition process False: fail to start commissioner candidate petition process
346,943
def utcnow(): d = dt.datetime.utcnow() d = d.replace(tzinfo=utc) return d
Get the current date and time in UTC :return:
346,944
def piv(ctx): try: ctx.obj[] = PivController(ctx.obj[].driver) except APDUError as e: if e.sw == SW.NOT_FOUND: ctx.fail("The PIV application can't be found on this YubiKey.") raise
Manage PIV Application. Examples: \b Generate an ECC P-256 private key and a self-signed certificate in slot 9a: $ ykman piv generate-key --algorithm ECCP256 9a pubkey.pem $ ykman piv generate-certificate --subject "yubico" 9a pubkey.pem \b Change the PIN from 123456 to 6543...
346,945
def tmDiff(tm1, tm2, verbosity = 0, relaxSegmentTests =True): return False result = True if (tm1.activeState[] != tm2.activeState[]).any(): print , numpy.where(tm1.activeState[] != tm2.activeState[]) result = False if (tm1.predictedState[] - tm2.predictedState[]).any(): print , nu...
Given two TM instances, list the difference between them and returns False if there is a difference. This function checks the major parameters. If this passes (and checkLearn is true) it checks the number of segments on each cell. If this passes, checks each synapse on each segment. When comparing C++ and Py, t...
346,946
async def async_init(self): self.pool = await aioredis.create_pool( (self.host, self.port), db=self.db_id, minsize=self.min_pool_size, maxsize=self.max_pool_size, loop=asyncio.get_event_loop(), )
Handle here the asynchronous part of the init.
346,947
async def dump_field(obj, elem, elem_type, params=None): if isinstance(elem, (int, bool)) or issubclass(elem_type, x.UVarintType) or issubclass(elem_type, x.IntType): return set_elem(obj, elem) elif issubclass(elem_type, x.BlobType) or isinstance(obj, bytes) or isinstance(obj, bytearray): ...
Dumps generic field to the popo object representation, according to the element specification. General multiplexer. :param obj: :param elem: :param elem_type: :param params: :return:
346,948
def minutes_played(self): if self._minutes_played[self._index]: minutes, seconds = self._minutes_played[self._index].split() minutes = float(minutes) + float(seconds) / 60 return float(minutes) return None
Returns a ``float`` of the number of game minutes the player was on the court for.
346,949
def get_response_dict(self, attrs, context, is_formset): form_type = "form" if is_formset: form_type = "formset" response_dict = { % form_type: attrs.get("form_action", ), % form_type: attrs.get("form_method", ), % form_type: ...
Returns a dictionary with all the parameters necessary to render the form/formset in a template. :param attrs: Dictionary with the helper's attributes used for rendering the form/formset :param context: `django.template.Context` for the node :param is_formset: Boolean value. If set to T...
346,950
def open( self ): if self._connection is None: self._connection = sqlite3.connect(self._dbfile)
Open the database connection.
346,951
def issueCommand(self, command, *args): result = Deferred() self._dq.append(result) self.sendLine(b" ".join([command] + list(args))) return result
Issue the given Assuan command and return a Deferred that will fire with the response.
346,952
def init_with_context(self, context): super(PersonalModule, self).init_with_context(context) current_user = context[].user if django.VERSION < (1, 5): current_username = current_user.first_name or current_user.username else: current_username = current_use...
Initializes the link list.
346,953
def GetDefaultServicePeriod(self): if not self._default_service_period: if len(self.service_periods) == 0: self.NewDefaultServicePeriod() elif len(self.service_periods) == 1: self._default_service_period = self.service_periods.values()[0] return self._default_service_period
Return the default ServicePeriod. If no default ServicePeriod has been set select the default depending on how many ServicePeriod objects are in the Schedule. If there are 0 make a new ServicePeriod the default, if there is 1 it becomes the default, if there is more than 1 then return None.
346,954
def units(self): existing = [i.units for i in self.geometry.values()] if any(existing[0] != e for e in existing): return existing[0]
Get the units for every model in the scene, and raise a ValueError if there are mixed units. Returns ----------- units : str Units for every model in the scene
346,955
def connect(self, inputs): outputs, updates = self.transform(inputs) if isinstance(outputs, dict): outputs = sorted(outputs.items()) if isinstance(outputs, (TT.TensorVariable, SS.SparseVariable)): outputs = [(, outputs)] outs = {self.full_name(na...
Create Theano variables representing the outputs of this layer. Parameters ---------- inputs : dict of Theano expressions Symbolic inputs to this layer, given as a dictionary mapping string names to Theano expressions. Each string key should be of the form "{...
346,956
def _load_tasks(self, project): task_queue = project.task_queue for task in self.taskdb.load_tasks( self.taskdb.ACTIVE, project.name, self.scheduler_task_fields ): taskid = task[] _schedule = task.get(, self.default_schedule) priority...
load tasks from database
346,957
def enable_encryption(self, output_key, input_key): self._chacha = chacha20.Chacha20Cipher(output_key, input_key)
Enable encryption with the specified keys.
346,958
def create_bulk(self, params, meta, **kwargs): validated = kwargs.pop() return [ self.create(params, meta, validated=item) for item in validated ]
Create items in bulk by reusing existing ``.create()`` handler. .. note:: This is default create_bulk implementation that may not be safe to use in production environment depending on your implementation of ``.create()`` method handler.
346,959
def img_binary_list(): qemu_imgs = [] for path in Qemu.paths_list(): try: for f in os.listdir(path): if (f == "qemu-img" or f == "qemu-img.exe") and \ os.access(os.path.join(path, f), os.X_OK) and \ ...
Gets QEMU-img binaries list available on the host. :returns: Array of dictionary {"path": Qemu-img binary path, "version": version of Qemu-img}
346,960
def remove_api_gateway(): logger.debug("[ client = boto3.client(, region_name=PRIMARY_REGION) matches = [x for x in client.get_rest_apis().get(, list()) if x[] == API_GATEWAY] if len(matches) == 0: logger.info("[!] API Gateway already removed") return True match =...
Remove the Blockade REST API service.
346,961
def clear_measurements(self): mid_list = self.assignments.get(, None) if mid_list is not None: for mid in mid_list: self.configs.delete_measurements(mid=mid) self.assignments[] = None
Forget any previous measurements
346,962
def flatten_blocks(lines, num_indents=-1): INDENTATION = " " * 4 if not lines: return "" if isinstance(lines, six.string_types): return INDENTATION * num_indents + lines return "\n".join([flatten_blocks(line, num_indents + 1) for line in lines])
Take a list (block) or string (statement) and flattens it into a string with indentation.
346,963
def get_renderer_from_definition(config): options = config.get(, {}) try: renderer_type = config[] renderer_colors = [(float(x[0]), hex_to_color(x[1])) for x in config[]] fill_value = options.get() if fill_value is not None: fill_value = float(fill_value) e...
Returns a renderer object based on the configuration (as a dictionary)
346,964
def update_file(finfo, sample_info, config, pass_uptodate=False): storage_dir = utils.safe_makedir(_get_storage_dir(finfo, config)) if finfo.get("type") == "directory": return _copy_finfo_directory(finfo, storage_dir) else: return _copy_finfo(finfo, storage_dir, pass_uptodate=pass_uptod...
Update the file in local filesystem storage.
346,965
def transform_data(self, data): def type_check(value): if pd.isnull(value): return None elif (isinstance(value, pd.tslib.Timestamp) or isinstance(value, pd.Period)): return time.mktime(value.timetuple()) ...
Transform Pandas Timeseries into JSON format Parameters ---------- data: DataFrame or Series Pandas DataFrame or Series must have datetime index Returns ------- JSON to object.json_data Example ------- >>>vis.transform_data(df) ...
346,966
def download_cli(directory, master_token=None, member=None, access_token=None, source=None, project_data=False, max_size=, verbose=False, debug=False, memberlist=None, excludelist=None, id_filename=False): return download(directory, master_token, member, acces...
Command line function for downloading data from project members to the target directory. For more information visit :func:`download<ohapi.command_line.download>`.
346,967
def load_config_file(config_file: str) -> HmipConfig: _config = configparser.ConfigParser() with open(config_file, "r") as fl: _config.read_file(fl) logging_filename = _config.get("LOGGING", "FileName", fallback="hmip.log") if logging_filename == "None": logging_filename...
Loads the config ini file. :raises a FileNotFoundError when the config file does not exist.
346,968
def propagate_min_max_up(self, cols=[], target_df_name=, source_df_name=, min_suffix=, max_suffix=): target_ind = self.ancestry.index(target_df_name) source_ind = self.an...
Take minimum/maximum values for a set of columns in source_df, and apply them to the target table. This method won't overwrite values in the target table, it will only supply values where they are missing. Parameters ---------- cols : list-like list of column...
346,969
def removeBitPadding(str, blocksize=AES_blocksize): pad_len = 0 for char in str[::-1]: if char == : pad_len += 1 else: break pad_len += 1 str = str[:-pad_len] return str
Remove bit padding with 0x80 followed by zero (null) bytes
346,970
def ensure_queue_count( self, queued, url, timeout, auth, acs_url, ssl_verify, tags=None, label_tags=None, group=None ): metric_name = .format(self.QUEUE_PREFIX) apps_response = self.get_apps_json(url, timeout, auth, acs_url, ssl_verify, tags, group) for app in apps_respon...
Ensure `marathon.queue.count` is reported as zero for apps without queued instances.
346,971
def get_type_data(name): name = name.upper() try: return { : , : , : name, : , : GNU_BASIC_NUMERIC_FORMAT_TYPES[name] + , : GNU_BASIC_NUMERIC_FORMAT_TYPES[name], : ( + GNU_BASIC_NUMERIC_F...
Return dictionary representation of type. Can be used to initialize primordium.type.primitives.Type
346,972
def setup_hooks(self): hooks = list() if self.saver_spec is not None and (self.execution_type == or self.distributed_spec[] == 0): self.saver_directory = self.saver_spec[] hooks.append(tf.train.CheckpointSaverHook( checkpoint_dir=self.saver_dir...
Creates and returns a list of hooks to use in a session. Populates self.saver_directory. Returns: List of hooks to use in a session.
346,973
def value(self): r from numpy_sugar.linalg import ddot, sum2diag if self._cache["value"] is not None: return self._cache["value"] scale = exp(self.logscale) delta = 1 / (1 + exp(-self.logitdelta)) v0 = scale * (1 - delta) v1 = scale * delta ...
r"""Log of the marginal likelihood. Formally, .. math:: - \frac{n}{2}\log{2\pi} - \frac{1}{2} \log{\left| v_0 \mathrm K + v_1 \mathrm I + \tilde{\Sigma} \right|} - \frac{1}{2} \left(\tilde{\boldsymbol\mu} - \mathr...
346,974
def _make_urp_hash(username, realm, passwd): if realm is None: realm = b"" return _h_value(b":".join((username, realm, passwd)))
Compute MD5 sum of username:realm:password. :Parameters: - `username`: a username. - `realm`: a realm. - `passwd`: a password. :Types: - `username`: `bytes` - `realm`: `bytes` - `passwd`: `bytes` :return: the MD5 sum of the parameters joined with ':'. :r...
346,975
def brozzler_new_site(argv=None): argv = argv or sys.argv arg_parser = argparse.ArgumentParser( prog=os.path.basename(argv[0]), description=, formatter_class=BetterArgumentDefaultsHelpFormatter) arg_parser.add_argument(, metavar=, help=) add_rethinkdb_options(arg...
Command line utility entry point for queuing a new brozzler site. Takes a seed url and creates a site and page object in rethinkdb, which brozzler-workers will look at and start crawling.
346,976
def get_state(self, state): for data in list(self._send_queue.queue): desired_states = data[] for desired_state in desired_states: if desired_state[] == state: return desired_state[] if state == States.FILTER_LOW_SPEE...
Returns True if the specified state is enabled.
346,977
def _top(self, k): if k > self.m: raise ValueError("k larger than the number of alternatives") G = np.ones((self.m, self.m)) for i in range(self.m): for j in range(self.m): if i == j: continue ...
Description: Top k breaking Parameters: k: the number of alternatives to break from highest rank
346,978
def explain_prediction_linear_classifier(clf, doc, vec=None, top=None, top_targets=None, target_names=None, targets...
Explain prediction of a linear classifier. See :func:`eli5.explain_prediction` for description of ``top``, ``top_targets``, ``target_names``, ``targets``, ``feature_names``, ``feature_re`` and ``feature_filter`` parameters. ``vec`` is a vectorizer instance used to transform raw features to the inp...
346,979
def find_reachable(rdf, res): starttime = time.time() seen = set() to_search = set([res]) while len(to_search) > 0: res = to_search.pop() if res in seen: continue seen.add(res) for p, o in rdf.predicate_objects(res): ...
Return the set of reachable resources starting from the given resource, excluding the seen set of resources. Note that the seen set is modified in-place to reflect the ongoing traversal.
346,980
def encode(cls, value): try: if float(value) + 0 == value: return repr(value) except (TypeError, ValueError): pass raise InvalidValue()
encode a floating point number to bytes in redis :param value: float :return: bytes
346,981
def _dcm_to_euler(self, dcm): assert(dcm.shape == (3, 3)) theta = np.arcsin(min(1, max(-1, -dcm[2][0]))) if abs(theta - np.pi/2) < 1.0e-3: phi = 0.0 psi = (np.arctan2(dcm[1][2] - dcm[0][1], dcm[0][2] + dcm[1][1]) + phi) elif...
Create DCM from euler angles :param dcm: 3x3 dcm array :returns: array [roll, pitch, yaw] in rad
346,982
def arcte_with_lazy_pagerank(adjacency_matrix, rho, epsilon, number_of_threads=None): adjacency_matrix = sparse.csr_matrix(adjacency_matrix) number_of_nodes = adjacency_matrix.shape[0] if number_of_threads is None: number_of_threads = get_threads_number() if number_of_threads == 1: ...
Extracts local community features for all graph nodes based on the partitioning of node-centric similarity vectors. Inputs: - A in R^(nxn): Adjacency matrix of an undirected network represented as a SciPy Sparse COOrdinate matrix. - rho: Restart probability - epsilon: Approximation thres...
346,983
def obj_deref(ref): from indico_livesync.models.queue import EntryType if ref[] == EntryType.category: return Category.get_one(ref[]) elif ref[] == EntryType.event: return Event.get_one(ref[]) elif ref[] == EntryType.session: return Session.get_one(ref[]) elif ref[] == E...
Returns the object identified by `ref`
346,984
def private_path(self): path = os.path.join(self.path, , ) try: os.mkdir(path) except OSError as e: if e.errno != errno.EEXIST: raise return path
Get the path to a directory which can be used to store arbitrary data This directory should not conflict with any of the repository internals. The directory should be created if it does not already exist.
346,985
async def pong(self, data: bytes = b"") -> None: await self.ensure_open() data = encode_data(data) await self.write_frame(True, OP_PONG, data)
This coroutine sends a pong. An unsolicited pong may serve as a unidirectional heartbeat. The content may be overridden with the optional ``data`` argument which must be a string (which will be encoded to UTF-8) or a bytes-like object.
346,986
def decode(stream, strict=False, logger=None, timezone_offset=None): if not isinstance(stream, util.BufferedByteStream): stream = util.BufferedByteStream(stream) if logger: logger.debug() msg = Envelope() msg.amfVersion = stream.read_ushort() if msg.amfVersion > 0x0...
Decodes the incoming stream as a remoting message. @type stream: L{BufferedByteStream<pyamf.util.BufferedByteStream>} @param strict: Enforce strict decoding. Default is `False`. @param logger: Used to log interesting events whilst decoding a remoting message. @type logger: U{logging.Logger<http...
346,987
def QA_util_random_with_topic(topic=, lens=8): _list = [chr(i) for i in range(65, 91)] + [chr(i) for i in range(97, 123) ] + [str(i) for i in range(10)] num = rando...
生成account随机值 Acc+4数字id+4位大小写随机
346,988
def with_data(path, data): if isinstance(data, str): data = json.loads(data) if os.path.exists(path): raise ValueError("File exists, not overwriting data. Set the " " attribute on a normally-initialized " ...
Initialize a new file that starts out with some data. Pass data as a list, dict, or JSON string.
346,989
def scc(graph): order = [] vis = {vertex: False for vertex in graph} graph_transposed = {vertex: [] for vertex in graph} for (v, neighbours) in graph.iteritems(): for u in neighbours: add_edge(graph_transposed, u, v) for v in graph: if not vis[v]: dfs_...
Computes the strongly connected components of a graph
346,990
def forward_kinematics(self, q): q = numpy.array(q).flatten() if len(q) != len(self.links): raise ValueError() tr = self.base.copy() l = [] for link, theta in zip(self.links, q): tr = tr * link.get_transformation_matrix(theta) l.a...
Computes the homogeneous transformation matrix of the end effector of the chain. :param vector q: vector of the joint angles (theta 1, theta 2, ..., theta n)
346,991
def updateGroupResponse(self, group, vendorSpecific=None): mmp_dict = {: (, group.toxml())} return self.PUT(, fields=mmp_dict, headers=vendorSpecific)
CNIdentity.addGroupMembers(session, groupName, members) → boolean https://releases.dataone.org/online/api- documentation-v2.0.1/apis/CN_APIs.html#CNIdentity.addGroupMembers. Args: group: vendorSpecific: Returns:
346,992
def binary_guesser(handle, num_bytes=512): text_chars = .join(map(chr, range(32, 127))) + byte_chars = text_chars.encode() handle_location = handle.tell() first_block = handle.read(num_bytes) if type(first_block) is str: first_block = first_block.encode() filtered_block = first_bl...
Raise error if file not likely binary Guesses if a file is binary, raises error if file is not likely binary, then returns to location in file when handle passed to binary_guesser. Args: handle (file): File handle of file thought to be binary num_bytes (int): Bytes of file to read to gues...
346,993
def convert_new_publication_info_to_old(publication_infos): def _needs_a_hidden_pubnote(journal_title, journal_volume): return ( journal_title in _JOURNALS_THAT_NEED_A_HIDDEN_PUBNOTE and journal_volume in _JOURNALS_THAT_NEED_A_HIDDEN_PUBNOTE[journal_title] ) result ...
Convert back a ``publication_info`` value from the new format to the old. Does the inverse transformation of :func:`convert_old_publication_info_to_new`, to be used whenever we are sending back records from Labs to Legacy. Args: publication_infos: a ``publication_info`` in the new format. Ret...
346,994
def tlist2dict(tuple_list,**kwargs): if( in kwargs): deepcopy = kwargs[] else: deepcopy = 1 if( in kwargs): check = kwargs[] else: check = 1 if(check): if(tltl.is_tlist(tuple_list)): pass else: return(None) else: ...
#duplicate keys will lost tl = [(1,2),(3,4),(1,5)] tlist2dict(tl)
346,995
def generate_pingback_content(soup, target, max_length, trunc_char=): link = soup.find(, href=target) content = strip_tags(six.text_type(link.findParent())) index = content.index(link.string) if len(content) > max_length: middle = max_length // 2 start = index - middle end...
Generate a description text for the pingback.
346,996
def tenant_create(name, description=None, enabled=True, profile=None, **connection_args): *nova tenant* kstone = auth(profile, **connection_args) new = getattr(kstone, _TENANTS, None).create(name, description, enabled) return tenant_get(new.id, profile=profile, **connection_args)
Create a keystone tenant CLI Examples: .. code-block:: bash salt '*' keystone.tenant_create nova description='nova tenant' salt '*' keystone.tenant_create test enabled=False
346,997
def validate(cls, data): try: jsonschema.validate( data, cls.SCHEMA, types={: (list, tuple)}) except jsonschema.ValidationError as e: raise InvalidFormat("Failure data not of the" " expected...
Validate input data matches expected failure ``dict`` format.
346,998
def load_context(ctx_path, ctx_type, scm=None): if ctx_path == : return loads(sys.stdin.read(), ac_parser=ctx_type, ac_schema=scm) return load(ctx_path, ac_parser=ctx_type, ac_schema=scm)
:param ctx_path: context file path or '-' (read from stdin) :param ctx_type: context file type :param scm: JSON schema file in any formats anyconfig supports, to validate given context files
346,999
def query(self, string, repeat_n_times=None): if not repeat_n_times: repeat_n_times = self.__determine_how_many_times_to_repeat_query(string) lines = self.__get_command_lines(string) return_list = [] for line in lines: lst = self.__query_n_times(line, rep...
This method performs the operations onto self.g :param string: The list of operations to perform. The sequences of commands should be separated by a semicolon An example might be CREATE {'tag': 'PERSON', 'text': 'joseph'}(v1), {'relation': 'LIVES_AT'}(v1,v2), ...