Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
346,500
def get_data(self): url = self.build_url() self.incidents_data = requests.get(url) if not self.incidents_data.status_code == 200: raise self.incidents_data.raise_for_status()
Gets data from the given url
346,501
def get_build_info_for_date(self, date, build_index=None): url = urljoin(self.base_url, self.monthly_build_list_regex) has_time = date and date.time() self.logger.info( % url) parser = self._create_directory_parser(url) regex = r % { : date.strftime(), ...
Return the build information for a given date.
346,502
def mass_tot(self, rho0, Ra, Rs): Ra, Rs = self._sort_ra_rs(Ra, Rs) sigma0 = self.rho2sigma(rho0, Ra, Rs) m_tot = 2 * np.pi * sigma0 * Ra * Rs return m_tot
total mass within the profile :param rho0: :param Ra: :param Rs: :return:
346,503
def _convert_before_2_0_0_b3(self, dynamips_id): dynamips_dir = self.project.module_working_directory(self.manager.module_name.lower()) for path in glob.glob(os.path.join(glob.escape(dynamips_dir), "configs", "i{}_*".format(dynamips_id))): dst = os.path.join(self._working_directory,...
Before 2.0.0 beta3 the node didn't have a folder by node when we start we move the file, we can't do it in the topology conversion due to case of remote servers
346,504
def find_ca_bundle(): if os.name==: return get_win_certfile() else: for cert_path in cert_paths: if os.path.isfile(cert_path): return cert_path try: return pkg_resources.resource_filename(, ) except (ImportError, ResolutionError, ExtractionError):...
Return an existing CA bundle path, or None
346,505
def parse(url, engine=None, conn_max_age=0, ssl_require=False): if url == : return { : SCHEMES[], : } config = {} url = urlparse.urlparse(url) path = url.path[1:] if in path and not url.query: pa...
Parses a database URL.
346,506
def assign_to_topic_partition(self, topic_partition=None): if isinstance(topic_partition, TopicPartition): topic_partition = [topic_partition] if not self._is_assigned(topic_partition): self.consumer.assign(topic_partition)
Assign a list of TopicPartitions to this consumer. - ``partitions`` (list of `TopicPartition`): Assignment for this instance.
346,507
def get_posts(self) -> Iterator[Post]: self._obtain_metadata() yield from (Post(self._context, node, self) for node in self._context.graphql_node_list("472f257a40c653c64c666ce877d59d2b", {: self.userid}, ...
Retrieve all posts from a profile.
346,508
def by_cat(self): for value in np.unique(self.category): cat_fm = self.filter(self.category == value) if self._categories: yield (cat_fm, self._categories[value]) else: yield (cat_fm, None)
Iterates over categories and returns a filtered datamat. If a categories object is attached, the images object for the given category is returned as well (else None is returned). Returns: (datamat, categories) : A tuple that contains first the filtered datamat (has ...
346,509
def modify_parameter_group(self, name, parameters=None): params = {: name} for i in range(0, len(parameters)): parameter = parameters[i] parameter.merge(params, i+1) return self.get_list(, params, ParameterGroup, verb=)
Modify a parameter group for your account. :type name: string :param name: The name of the new parameter group :type parameters: list of :class:`boto.rds.parametergroup.Parameter` :param parameters: The new parameters :rtype: :class:`boto.rds.parametergroup.ParameterGroup` ...
346,510
def setBEGINLIBPATH(): dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload") libpath = os.environ[].split() if libpath[-1]: libpath.append(dllpath) else: libpath[-1] = dllpath os.environ[] = .join(libpath)
The OS/2 EMX port has optional extension modules that do double duty as DLLs (and must use the .DLL file extension) for other extensions. The library search path needs to be amended so these will be found during module import. Use BEGINLIBPATH so that these are at the start of the library search path.
346,511
def parse_exchange_list(path, exchange, default_compartment): context = FilePathContext(path) for exchange_def in exchange: if in exchange_def: include_context = context.resolve(exchange_def[]) for exchange_compound in parse_exchange_file( include_cont...
Parse a structured exchange list as obtained from a YAML file. Yields tuples of compound, reaction ID, lower and upper flux bounds. Path can be given as a string or a context.
346,512
def start(self, exit_on_stop=True, secondary_wait=0, reconnect=False): if self.started: raise RuntimeError("DistributedEvaluator already started!") self.started = True if self.mode == MODE_PRIMARY: self._start_primary() elif self.mode == MODE_SECONDARY: ...
If the DistributedEvaluator is in primary mode, starts the manager process and returns. In this case, the ``exit_on_stop`` argument will be ignored. If the DistributedEvaluator is in secondary mode, it connects to the manager and waits for tasks. If in secondary mode and ``exit_o...
346,513
def similar_lorem(anon, obj, field, val): return anon.faker.lorem(field=field, val=val)
Generates lorem ipsum text with the same length and same pattern of linebreaks as the original. If the original often takes a standard form (e.g. a single word 'yes' or 'no'), this could easily fail to hide the original data.
346,514
def check_generic_request(self, item_session: ItemSession) -> Tuple[bool, str]: verdict, reason, test_info = self.consult_filters( item_session.request.url_info, item_session.url_record) verdict, reason = self.consult_hook(item_session, verdict, ...
Check URL filters and scripting hook. Returns: tuple: (bool, str)
346,515
async def rank(self, request, origin: Optional[Text]) \ -> Tuple[ float, Optional[BaseTrigger], Optional[type], Optional[bool], ]: if self.origin_name == origin: score = 1.0 elif self.origin_nam...
Computes the rank of this transition for a given request. It returns (in order): - The score (from 0 to 1) - The trigger instance (if it matched) - The class of the destination state (if matched)
346,516
def attention_lm_moe_base_memeff(): hparams = attention_lm_moe_base_long_seq() hparams.use_sepconv = False hparams.diet_experts = True hparams.layer_preprocess_sequence = "n" hparams.layer_postprocess_sequence = "da" hparams.layer_prepostprocess_dropout = 0.0 hparams.memory_efficient_ffn = True hpar...
Base model with attention expert.
346,517
def _decode_POST_value(request, field_name, default=None): if default is None: value = request.POST[field_name] else: value = request.POST.get(field_name, default) charsets = json.loads(request.POST.get(, "{}")) charset = charsets.get(field_name, ) if charset.lower()...
Helper to decode a request field into unicode based on charsets encoding. Args: request: the HttpRequest object. field_name: the field expected in the request.POST Kwargs: default: if passed in then field is optional and default is used if not found; if None, then assume fi...
346,518
def check_transport_host(self): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex((, 8080)) if result == 0: logging.info() return True return False
Check if zeromq socket is available on transport host
346,519
def _extract_emd(mat, filename): emd = mat[].squeeze() epoch = datetime.datetime(1904, 1, 1) def convert_epoch(x): timestamp = epoch + datetime.timedelta(seconds=x.astype(float)) return timestamp dfl = [] for f_id in range(0, emd.size): fdata = emd[f...
Extract the data from the EMD substruct, given a medusa-created MNU0-mat file Parameters ---------- mat: matlab-imported struct
346,520
def convert(self): from pyspectral.utils import (convert2wavenumber, get_central_wave) if self._wavespace == WAVE_LENGTH: rsr, info = convert2wavenumber(self.rsr) for band in rsr.keys(): for det in rsr[band].keys(): self.rsr[band][det...
Convert spectral response functions from wavelength to wavenumber
346,521
def flexifunction_buffer_function_ack_encode(self, target_system, target_component, func_index, result): return MAVLink_flexifunction_buffer_function_ack_message(target_system, target_component, func_index, result)
Flexifunction type and parameters for component at function index from buffer target_system : System ID (uint8_t) target_component : Component ID (uint8_t) func_index : Function index (uint16_t) result ...
346,522
def revoke(workers, qualification, by_name, reason, sandbox): if not (workers and qualification): raise click.BadParameter( "Must specify a qualification ID or name, and at least one worker ID" ) mturk = _mturk_service_from_config(sandbox) if by_name: result = mturk...
Revoke a qualification from 1 or more workers
346,523
def delete_differ_record(old_image, durable_model): data = {} for item in old_image: data[item] = DESER.deserialize(old_image[item]) data[] = {} del data[] durable_model(**data).save() LOG.debug()
Handles a DynamoDB DELETE event type -- For the Differ.
346,524
def get_text_line(self, line_nb): try: return to_text_string(self.toPlainText()).splitlines()[line_nb] except IndexError: return self.get_line_separator()
Return text line at line number *line_nb*
346,525
def cancel(self): if self.cancelled: raise error.AlreadyCancelled elif self.called: raise error.AlreadyCalled else: self.canceller(self) self.cancelled = 1 if self.debug: self._str = str(self) del se...
Unschedule this call @raise AlreadyCancelled: Raised if this call has already been unscheduled. @raise AlreadyCalled: Raised if this call has already been made.
346,526
def _patch_file(path, content): f = open(path) existing_content = f.read() f.close() if existing_content == content: log.warn() return False log.warn() _rename_path(path) f = open(path, ) try: f.write(content) finally: f.close() retur...
Will backup the file then patch it
346,527
def set_mode_label_to_keywords_creation(self): self.setWindowTitle(self.keyword_creation_wizard_name) if self.get_existing_keyword(): mode_name = tr( ).format( layer_name=self.layer.name()) else: mode_name = tr( ...
Set the mode label to the Keywords Creation/Update mode.
346,528
def _GetTimeElementsTuple(self, timestamp): year, month, day_of_month, hours, minutes, seconds = ( int(hexdigit[0] + hexdigit[1], 16) for hexdigit in zip( timestamp[::2], timestamp[1::2])) return (year + 1970, month + 1, day_of_month, hours, minutes, seconds)
Retrieves a time elements tuple from the timestamp. A Symantec log timestamp consist of six hexadecimal octets, that represent: First octet: Number of years since 1970 Second octet: Month, where January is represented by 0 Third octet: Day of the month Fourth octet: Number of hours Fi...
346,529
def _stripe_object_to_record(cls, data, current_ids=None, pending_relations=None): manipulated_data = cls._manipulate_stripe_object_hook(data) if "object" not in data: raise ValueError("Stripe data has no `object` value. Aborting. %r" % (data)) if not cls.is_valid_object(data): raise ValueError( "...
This takes an object, as it is formatted in Stripe's current API for our object type. In return, it provides a dict. The dict can be used to create a record or to update a record This function takes care of mapping from one field name to another, converting from cents to dollars, converting timestamps, and eli...
346,530
def get_or_create_user(self, username, password): info = self.get_ad_info(username, password) self.debug("INFO found: {}".format(info)) try: user = User.objects.get(username=username) except User.DoesNotExist: user = User(username=user...
Get or create the given user
346,531
def range(cls, field, from_value=None, to_value=None, include_lower=None, include_upper=None): instance = cls({: {field: {}}}) if from_value is not None: instance[][field][] = from_value if to_value is not None: instance[][field][] = to_value if include_...
http://www.elasticsearch.org/guide/reference/query-dsl/range-filter.html Filters documents with fields that have terms within a certain range. Similar to range query, except that it acts as a filter. Can be placed within queries that accept a filter.
346,532
def show(self, f, pattern=None): if pattern is None: f.write() for c in self.counters: f.write( % (c, self.counters[c])) f.write() f.write( % self.mav_error) f.write(str(self.gps)+) for m in sorted(self.msgs.keys()): ...
write status to status.txt
346,533
def _set_threshold_monitor(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=threshold_monitor.threshold_monitor, is_container=, presence=False, yang_name="threshold-monitor", rest_name="threshold-monitor", parent=self, path_helper=self._path_helper, ex...
Setter method for threshold_monitor, mapped from YANG variable /rbridge_id/threshold_monitor (container) If this variable is read-only (config: false) in the source YANG file, then _set_threshold_monitor is considered as a private method. Backends looking to populate this variable should do so via calli...
346,534
def augment_field_meta(field, queryset, field_properties, verbosity=0, count=0): if settings.DEBUG and verbosity > 3: print % field field_properties[] = db.clean_utf8(getattr(qs.all()[0], length_name, None)) field_properties[] = db.clean_utf8(getattr(qs.order_by(+len...
Return a dict of statistical properties (metadata) for a database column (model field) Strings are UTF-8 encoded (UTF-16 or invalid UTF-8 characters are ignored) Resulting dictionary is json-serializable using the pug.nlp.db.RobustEncoder class. { 'num_distinct': # count of distinct (different) ...
346,535
def get(cls, id, api=None): id = Transform.to_resource(id) api = api if api else cls._API if in cls._URL: extra = {: cls.__name__, : {: id}} logger.info(.format(cls), extra=extra) resource = api.get(url=cls._URL[].format(id=id)).json() re...
Fetches the resource from the server. :param id: Resource identifier :param api: sevenbridges Api instance. :return: Resource object.
346,536
def get(self, workflow_id, **queryparams): self.workflow_id = workflow_id return self._mc_client._get(url=self._build_path(workflow_id), **queryparams)
Get a summary of an individual Automation workflow’s settings and content. The trigger_settings object returns information for the first email in the workflow. :param workflow_id: The unique id for the Automation workflow :type workflow_id: :py:class:`str` :param queryparams: th...
346,537
def do_serialize(self, line): opts = self.SERIALIZE_OPTS if not self.current: self._help_noontology() return line = line.split() g = self.current[] if not line: line = [] if line[0] not in opts: self.help_serial...
Serialize an entity into an RDF flavour
346,538
def open_file(self, file): files = self.get_recent_files() try: files.remove(file) except ValueError: pass files.insert(0, file) del files[self.max_recent_files:] self.set_value(, files) self.updated.emit()
Adds a file to the list (and move it to the top of the list if the file already exists) :param file: file path to add the list of recent files.
346,539
def uninstall(self, bug: Bug) -> bool: r = self.__api.post(.format(bug.name)) raise NotImplementedError
Uninstalls the Docker image associated with a given bug.
346,540
async def on_raw_chghost(self, message): if not in self._capabilities or not self._capabilities[]: return nick, _ = self._parse_user(message.source) if nick not in self.users: return metadata = { : message.params[0], : ...
Change user and/or host of user.
346,541
def last_updated(self, subpath=None): try: return os.path.getmtime(self.readme_for(subpath)) except ReadmeNotFoundError: return None except (OSError, EnvironmentError) as ex: if ex.errno == errno.ENOENT: return None ...
Returns the time of the last modification of the Readme or specified subpath, or None if the file does not exist. The return value is a number giving the number of seconds since the epoch (see the time module). Raises werkzeug.exceptions.NotFound if the resulting path would fal...
346,542
def next_frame_savp_vae(): hparams = next_frame_savp() hparams.use_vae = True hparams.use_gan = False hparams.latent_loss_multiplier = 1e-3 hparams.latent_loss_multiplier_schedule = "linear_anneal" return hparams
SAVP - VAE only model.
346,543
def single_qubit_state_tomography(sampler: sim.Sampler, qubit: devices.GridQubit, circuit: circuits.Circuit, repetitions: int = 1000) -> TomographyResult: circuit_z = circuit + circuits.Circuit.from_ops(ops.me...
Single-qubit state tomography. The density matrix of the output state of a circuit is measured by first doing projective measurements in the z-basis, which determine the diagonal elements of the matrix. A X/2 or Y/2 rotation is then added before the z-basis measurement, which determines the imaginary a...
346,544
def _record_app_data(self, data): name, revision = data[0].split() root_version = data[1].split()[1] command = b.join(data[3:]).split(b + name + b)[0] self.meta.append({ : np.string_(name), : np.string_(revision), : np.string_(root_version), ...
Parse raw metadata output for a single application The usual output is: ApplicationName RevisionNumber ApplicationName ROOT_Version ApplicationName KM3NET ApplicationName ./command/line --arguments --which --can contain also multiple lines and --a...
346,545
def get_errors(error_string): lines = error_string.splitlines() error_lines = tuple(line for line in lines if line.find() >= 0) if len(error_lines) > 0: return .join(error_lines) else: return error_string.strip()
returns all lines in the error_string that start with the string "error"
346,546
def _trigger_refresh(self, key): "Triggers update to a plot on a refresh event" if not self.top_level or isinstance(self, GenericElementPlot): self.update(key)
Triggers update to a plot on a refresh event
346,547
def _filter_deprecation_warnings(): deprecation_filter = (, None, DeprecationWarning, re.compile(r, re.UNICODE), 0) try: warnings._add_filter(*deprecation_filter, append=False) except AttributeError: pass warnings.si...
Apply filters to deprecation warnings. Force the `DeprecationWarning` warnings to be displayed for the qiskit module, overriding the system configuration as they are ignored by default [1] for end-users. Additionally, silence the `ChangedInMarshmallow3Warning` messages. TODO: on Python 3.7, this m...
346,548
def remove(self, pools): data = dict() data["pools"] = pools uri = "api/pools/v2/" return self.delete(uri, data)
Remove Pools Running Script And Update to Not Created :param ids: List of ids :return: None on success :raise ScriptRemovePoolException :raise InvalidIdPoolException :raise NetworkAPIException
346,549
def salt_api_acl_tool(username, request): ** failure_str = ("[api_acl] Authentication failed for " "user %s from IP %s") success_str = ("[api_acl] Authentication sucessful for " "user %s from IP %s") pass_str = ("[api_acl] Authentication not checked for " ...
..versionadded:: 2016.3.0 Verifies user requests against the API whitelist. (User/IP pair) in order to provide whitelisting for the API similar to the master, but over the API. ..code-block:: yaml rest_cherrypy: api_acl: users: '*': ...
346,550
def set_neighbor_in_filter(neigh_ip_address, filters): core = CORE_MANAGER.get_core_service() peer = core.peer_manager.get_by_addr(neigh_ip_address) peer.in_filters = filters return True
Returns a neighbor in_filter for given ip address if exists.
346,551
def _check_response_for_request_errors(self): if self.response.HighestSeverity == "ERROR": for notification in self.response.Notifications: if notification.Severity == "ERROR": raise FedexError(notification.Code, noti...
Override this in each service module to check for errors that are specific to that module. For example, invalid tracking numbers in a Tracking request.
346,552
def resources(): ind_id = request.form[] upload_dir = os.path.abspath(app.config[]) req_file = request.files[] filename = secure_filename(req_file.filename) file_path = os.path.join(upload_dir, filename) name = request.form[] or filename req_file.save(file_path) ind_obj = app.db.i...
Upload a new resource for an individual.
346,553
def read(string): dotG = pydot.graph_from_dot_data(string) if (dotG.get_type() == "graph"): G = graph() elif (dotG.get_type() == "digraph"): G = digraph() elif (dotG.get_type() == "hypergraph"): return read_hypergraph(string) else: raise InvalidGraphTyp...
Read a graph from a string in Dot language and return it. Nodes and edges specified in the input will be added to the current graph. @type string: string @param string: Input string in Dot format specifying a graph. @rtype: graph @return: Graph
346,554
def mask_average(dset,mask): o = nl.run([,,,mask,dset]) if o: return float(o.output.split()[-1])
Returns average of voxels in ``dset`` within non-zero voxels of ``mask``
346,555
def interp2d2d(x,y,Z,xout,yout,split_factor=1,**kwargs): class ThreadClass(threading.Thread): def __init__(self, input_q,indices_q,result_q): threading.Thread.__init__(self) self.input = input_q self.indices = indices_q ...
INTERP2D2D : Interpolate a 2D matrix into another 2D matrix @param x: 1st dimension vector of size NX @param y: 2nd dimension vector of size NY @param Z: Array to interpolate (NXxNY) @param xout: 1st dimension vector of size NXout @param yout: 2nd dimension vector of size NYout ...
346,556
def calculate_key_stats(self, metric_store): stats_to_calculate = [, , , , ] percentiles_to_calculate = range(5, 101, 5) percentiles_to_calculate.append(99) for transaction in metric_store[].keys(): transaction_key = transaction + + self.calculated_stats[transaction_...
Calculate key statistics for given data and store in the class variables calculated_stats and calculated_percentiles calculated_stats: 'mean', 'std', 'median', 'min', 'max' calculated_percentiles: range(5,101,5), 99 :param dict metric_store: The metric store used to store all the parsed jmeter l...
346,557
def distance(vec1, vec2): if isinstance(vec1, Vector2) \ and isinstance(vec2, Vector2): dist_vec = vec2 - vec1 return dist_vec.length() else: raise TypeError("vec1 and vec2 must be Vector2's")
Calculate the distance between two Vectors
346,558
def to_text(path): try: from StringIO import StringIO import sys reload(sys) sys.setdefaultencoding() except ImportError: from io import StringIO from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.converter impor...
Wrapper around `pdfminer`. Parameters ---------- path : str path of electronic invoice in PDF Returns ------- str : str returns extracted text from pdf
346,559
def get_assessments_offered_by_ids(self, assessment_offered_ids): collection = JSONClientValidated(, collection=, runtime=self._runtime) object_id_list = [] for i in assessment_o...
Gets an ``AssessmentOfferedList`` corresponding to the given ``IdList``. In plenary mode, the returned list contains all of the assessments specified in the ``Id`` list, in the order of the list, including duplicates, or an error results if an ``Id`` in the supplied list is not found or...
346,560
def get_default_config_help(self): config = super(SignalfxHandler, self).get_default_config_help() config.update({ : , : , : , : , }) return config
Returns the help text for the configuration options for this handler
346,561
def commit(self, body): conn = self.get_conn() resp = (conn .projects() .commit(projectId=self.project_id, body=body) .execute(num_retries=self.num_retries)) return resp
Commit a transaction, optionally creating, deleting or modifying some entities. .. seealso:: https://cloud.google.com/datastore/docs/reference/rest/v1/projects/commit :param body: the body of the commit request. :type body: dict :return: the response body of the commit requ...
346,562
def to_decimal(text): if not isinstance(text, string_type): raise TypeError("expected str or unicode, %s given" % type(text)) if findall(r"[\x00-\x20\x7c-\xff]", text): raise ValueError("invalid character in sequence") text = text.lstrip() decimal = 0 length = len(text) - 1 ...
Takes a base91 char string and returns decimal
346,563
def new_tag(self, name: str, category: str=None) -> models.Tag: new_tag = self.Tag(name=name, category=category) return new_tag
Create a new tag.
346,564
def get_dashboard_history(self, id, **kwargs): kwargs[] = True if kwargs.get(): return self.get_dashboard_history_with_http_info(id, **kwargs) else: (data) = self.get_dashboard_history_with_http_info(id, **kwargs) return data
Get the version history of a specific dashboard # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_dashboard_history(id, async_req=True) >>> result = thread.g...
346,565
def makeSolution(self,cNrm,mNrm): s problem. Parameters ---------- cNrm : np.array Array of normalized consumption values for interpolation. Each row corresponds to a Markov state for this period. mNrm : np.array Array of normalized market re...
Construct an object representing the solution to this period's problem. Parameters ---------- cNrm : np.array Array of normalized consumption values for interpolation. Each row corresponds to a Markov state for this period. mNrm : np.array Array of n...
346,566
def body_blocks(soup): nodenames = body_block_nodenames() body_block_tags = [] if not soup: return body_block_tags first_sibling_node = firstnn(soup.find_all()) if first_sibling_node is None: return body_block_tags sibling_tags = first_sibling_node.find_next_siblings(no...
Note: for some reason this works and few other attempted methods work Search for certain node types, find the first nodes siblings of the same type Add the first sibling and the other siblings to a list and return them
346,567
def decode(kls, skelbuf, segid=None): if len(skelbuf) < 8: raise SkeletonDecodeError("{} bytes is fewer than needed to specify the number of verices and edges.".format(len(skelbuf))) num_vertices, num_edges = struct.unpack(, skelbuf[:8]) min_format_length = 8 + 12 * num_vertices + 8 * num_edges ...
Convert a buffer into a PrecomputedSkeleton object. Format: num vertices (Nv) (uint32) num edges (Ne) (uint32) XYZ x Nv (float32) edge x Ne (2x uint32) radii x Nv (optional, float32) vertex_type x Nv (optional, req radii, uint8) (SWC definition) More documentation: https://github....
346,568
def create_output(decoder_output, rows, cols, targets, hparams): del targets decoded_image = postprocess_image(decoder_output, rows, cols, hparams) batch = common_layers.shape_list(decoded_image)[0] depth = common_layers.shape_list(decoded_image)[-1] likelihood = getattr(hparams, "likelihood", Distributi...
Creates output from decoder output and vars. Args: decoder_output: Tensor of shape [batch, ...], where ... can be any rank such that the number of elements is batch * rows * cols * hparams.hidden_size. rows: Integer representing number of rows in a 2-D data point. cols: Integer representing number ...
346,569
def find_inouts_mp(voxel_grid, datapts, **kwargs): tol = kwargs.get(, 10e-8) num_procs = kwargs.get(, 4) with pool_context(processes=num_procs) as pool: filled = pool.map(partial(is_point_inside_voxel, ptsarr=datapts, tol=tol), voxel_grid) return filled
Multi-threaded ins and outs finding (using multiprocessing) :param voxel_grid: voxel grid :param datapts: data points :return: in-outs
346,570
def make_collaborations_regex_str(): def add_to_auth_list(s): s = ur"(?:the\s)?" + s.strip().replace(u, ur) + u"s?" auths.append(s) auths = [] fpath = CFG_REFEXTRACT_KBS[] try: fh = open(fpath, "r") except IOError: LOGGER.debug(u"Err...
From the authors knowledge-base, construct a single regex holding the or'd possibilities of patterns which should be included in $h subfields. The word 'Collaboration' is also converted to 'Coll', and used in finding matches. Letter case is not considered during the search. @return: (string) The single patt...
346,571
def config_for_set(uset, app, defaults=None): config = app.config prefix = % uset.name.upper() using_defaults = False if defaults is None: defaults = dict(dest=None, url=None) allow_extns = tuple(config.get(prefix + , ())) deny_extns = tuple(config.get(prefix + , ())) destinat...
This is a helper function for `configure_uploads` that extracts the configuration for a single set. :param uset: The upload set. :param app: The app to load the configuration from. :param defaults: A dict with keys `url` and `dest` from the `UPLOADS_DEFAULT_DEST` and `DEFAULT_UPLOA...
346,572
def is_relation_made(relation, keys=): if isinstance(keys, str): keys = [keys] for r_id in relation_ids(relation): for unit in related_units(r_id): context = {} for k in keys: context[k] = relation_get(k, rid=r_id, ...
Determine whether a relation is established by checking for presence of key(s). If a list of keys is provided, they must all be present for the relation to be identified as made
346,573
def get_object_name(obj): name_dispatch = { ast.Name: "id", ast.Attribute: "attr", ast.Call: "func", ast.FunctionDef: "name", ast.ClassDef: "name", ast.Subscript: "value", } if hasattr(ast, "arg"): name_dispatch[ast.arg] = "arg" while n...
Return the name of a given object
346,574
def scrypt_mcf_check(scrypt, mcf, password): if not isinstance(mcf, bytes): raise TypeError() if isinstance(password, unicode): password = password.encode() elif not isinstance(password, bytes): raise TypeError() N, r, p, salt, hash, hlen = _scrypt_mcf_decode(mcf) h = s...
Returns True if the password matches the given MCF hash Supports both the libscrypt $s1$ format and the $7$ format.
346,575
def unregister_child(self, child): self._children.remove(child) child.on_closed.disconnect(self.unregister_child)
Unregister an existing child that is no longer to be owned by the current instance. :param child: The child instance.
346,576
def available(software=True, drivers=True, summary=False, skip_installed=True, skip_hidden=True, skip_mandatory=False, skip_reboot=False, categories=None, severities=None,): <GUID>TitleKBGUIDDescriptionDo...
.. versionadded:: 2017.7.0 List updates that match the passed criteria. This allows for more filter options than :func:`list`. Good for finding a specific GUID or KB. Args: software (bool): Include software updates in the results (default is True) drivers (bool): ...
346,577
def inhull(self, xyz, pore, tol=1e-7): r xyz = np.around(xyz, 10) xmin = xyz[:, 0].min() xr = (np.ceil(xyz[:, 0].max())-np.floor(xmin)).astype(int)+1 ymin = xyz[:, 1].min() yr = (np.ceil(xyz[:, 1].max())-np.floor(ymin)).astype(int)+1 zmin = xyz[:, 2].min(...
r""" Tests whether points lie within a convex hull or not. Computes a tesselation of the hull works out the normals of the facets. Then tests whether dot(x.normals) < dot(a.normals) where a is the the first vertex of the facets
346,578
def find_connection_point(node, node_shp, graph, proj, conn_objects_min_stack, conn_dist_ring_mod, debug): node_connected = False for dist_min_obj in conn_objects_min_stack: nodes_are_members_of_ring = False if isinstance(dist_min_obj[], LineString): ...
Goes through the possible target connection objects in `conn_objects_min_stack` (from nearest to most far object) and tries to connect `node` to one of them. Function searches from nearest to most far object. Args ---- node: LVLoadAreaCentreDing0, i.e. Origin node - Ding0 graph obj...
346,579
def proxy_for(self, obj): obj_id = id(obj) if obj_id not in self._proxies: self._proxies[obj_id] = Proxy(obj) return self._proxies[obj_id]
Returns the ``Proxy`` for the target object, creating it if necessary. :param object obj: The object that will be doubled. :return: The mapped ``Proxy``. :rtype: Proxy
346,580
def _find_turning_points(mesh, tol=1.0): assert isinstance(mesh, RectangularMesh) azimuths = geodetic.azimuth(mesh.lons[0, :-1], mesh.lats[0, :-1], mesh.lons[0, 1:], mesh.lats[0, 1:]) naz = len(azimuths) azim = azimuths[0] idx = [0] for i in range(1, naz...
Identifies the turning points in a rectangular mesh based on the deviation in the azimuth between successive points on the upper edge. A turning point is flagged if the change in azimuth change is greater than the specified tolerance (in degrees) :param mesh: Mesh for downsampling as instance o...
346,581
def open_grpc_channel(endpoint): if (endpoint.startswith("https://")): return grpc.secure_channel(remove_http_https_prefix(endpoint), grpc.ssl_channel_credentials()) return grpc.insecure_channel(remove_http_https_prefix(endpoint))
open grpc channel: - for http:// we open insecure_channel - for https:// we open secure_channel (with default credentials) - without prefix we open insecure_channel
346,582
def new_freeform_sp(shape_id, name, x, y, cx, cy): tmpl = CT_Shape._freeform_sp_tmpl() xml = tmpl % (shape_id, name, x, y, cx, cy) sp = parse_xml(xml) return sp
Return new `p:sp` element tree configured as freeform shape. The returned shape has a `a:custGeom` subtree but no paths in its path list.
346,583
def _to_date_in_588(date_str): try: date_tokens = (int(x) for x in date_str.split(".")) except ValueError: return date_str return ".".join(str(x) for x in date_tokens)
Convert date in the format ala 03.02.2017 to 3.2.2017. Viz #100 for details.
346,584
def delete_all_couchdb_admins(): username = get_admin()[0] admins = get_couchdb_admins() for admin in admins: if admin == username: print "Delete {} later...".format(admin) else: print "Delete {}".format(admin) delete_couchdb_admin(adm...
Delete all CouchDB users
346,585
def update_profile_colors(self, **params): warnings.warn( , TwythonDeprecationWarning, stacklevel=2 ) return self.post(, params=params)
Sets one or more hex values that control the color scheme of the authenticating user's profile page on twitter.com. This method is deprecated, replaced by the ``profile_link_color`` parameter to :meth:`update_profile`. Docs: https://developer.twitter.com/en/docs/accounts-and-us...
346,586
async def offline_intervals(self, cd_ids: Union[str, Sequence[str]]) -> dict: LOGGER.debug(, cd_ids) rv = {} for cd_id in [cd_ids] if isinstance(cd_ids, str) else cd_ids: if not ok_cred_def_id(cd_id): LOGGER.debug(, cd_id) raise BadIdentifie...
Return default non-revocation intervals for input cred def ids, based on content of revocation cache, for augmentation into specification for Verifier.build_proof_req_json. Note that the close() call to set the anchor off-line extends all revocation cache registry delta entries to its time of execution:...
346,587
def merge_layouts(layouts): layout = layouts[0].clone() for l in layouts[1:]: layout.files.update(l.files) layout.domains.update(l.domains) for k, v in l.entities.items(): if k not in layout.entities: layout.entities[k] = v else: ...
Utility function for merging multiple layouts. Args: layouts (list): A list of BIDSLayout instances to merge. Returns: A BIDSLayout containing merged files and entities. Notes: Layouts will be merged in the order of the elements in the list. I.e., the first Layout will be up...
346,588
def Run(self, unused_arg, ttl=None): logging.debug("Sending startup information.") boot_time = rdfvalue.RDFDatetime.FromSecondsSinceEpoch(psutil.boot_time()) response = rdf_client.StartupInfo( boot_time=boot_time, client_info=GetClientInformation()) self.grr_worker.SendReply( respo...
Returns the startup information.
346,589
def observe(self, amount): self._sum.inc(amount) for i, bound in enumerate(self._upper_bounds): if amount <= bound: self._buckets[i].inc(1) break
Observe the given amount.
346,590
def to_type_with_default(value_type, value, default_value): result = TypeConverter.to_nullable_type(value_type, value) return result if result != None else default_value
Converts value into an object type specified by Type Code or returns default value when conversion is not possible. :param value_type: the TypeCode for the data type into which 'value' is to be converted. :param value: the value to convert. :param default_value: the default value to return if...
346,591
def dispatch(self, request, *args, **kwargs): def wrapper(request, *args, **kwargs): if not self.has_permission(request, *args, **kwargs): path = urlquote(request.get_full_path()) login_url = kwargs.pop(, settings.LOGIN_URL) redirect_field_nam...
Overloaded to check permissions if appropriate
346,592
def _str_iterator(self, iterator, name_callback=None, prefix="\n", left_paren=, right_paren=, depth=0): indent = 1 if depth > 0 else 0 s = [] s.append(.format(prefix, self._add_indent(left_paren, indent))) s_body = [] for k, v in iterator: k = k if name_ca...
turn an iteratable value into a string representation iterator -- iterator -- the value to be iterated through name_callback -- callback -- if not None, a function that will take the key of each iteration prefix -- string -- what will be prepended to the generated value left_paren -- st...
346,593
def combine(self, rhs): self._check_compatible_regs(rhs) combined_qregs = deepcopy(self.qregs) combined_cregs = deepcopy(self.cregs) for element in rhs.qregs: if element not in self.qregs: combined_qregs.append(element) for...
Append rhs to self if self contains compatible registers. Two circuits are compatible if they contain the same registers or if they contain different registers with unique names. The returned circuit will contain all unique registers between both circuits. Return self + rhs as ...
346,594
def _nac(self, q_direction): num_atom = self._pcell.get_number_of_atoms() nac_q = np.zeros((num_atom, num_atom, 3, 3), dtype=) if (np.abs(q_direction) < 1e-5).all(): return nac_q rec_lat = np.linalg.inv(self._pcell.get_cell()) nac_factor = self._dynmat.get_n...
nac_term = (A1 (x) A2) / B * coef.
346,595
def generateIntegers(api_key=None, api_version=None, **kwargs): ** ret = {: True} if not api_key or not api_version: try: options = __salt__[]() if not api_key: api_key = options.get() if not api_version: ...
Generate random integers :param api_key: The Random.org api key. :param api_version: The Random.org api version. :param number: The number of integers to generate :param minimum: The lower boundary for the range from which the random numbers will be picked. Must be within ...
346,596
def _get_cells_headers_ids(self, hed, index): ids = [] for row in hed: if row[index].get_tag_name() == : ids.append(row[index].get_attribute()) return ids
Returns a list with ids of rows of same column. :param hed: The list that represents the table header. :type hed: list(list(hatemile.util.html.htmldomelement.HTMLDOMElement)) :param index: The index of columns. :type index: int :return: The list with ids of rows of same column. ...
346,597
def restoreDefaultWCS(imageObjectList, output_wcs): if not isinstance(imageObjectList,list): imageObjectList = [imageObjectList] output_wcs.restoreWCS() updateImageWCS(imageObjectList, output_wcs)
Restore WCS information to default values, and update imageObject accordingly.
346,598
def writeDate(self, n): if isinstance(n, datetime.time): raise pyamf.EncodeError( % (n,)) self.stream.write(TYPE_DATE) ref = self.context.getObjectReference(n) if ref != -1: self._writeInteger(ref << 1) re...
Writes a C{datetime} instance to the stream. @type n: L{datetime} @param n: The C{Date} data to be encoded to the AMF3 data stream.
346,599
def certify_dict_schema( value, schema=None, key_certifier=None, value_certifier=None, required=None, allow_extra=None, ): if key_certifier is not None or value_certifier is not None: for key, val in value.items(): if key_certifier is not None: key_certifier(key) ...
Certify the dictionary schema. :param dict|Mapping|MutableMapping value: The mapping value to certify against the schema. :param object schema: The schema to validate with. :param callable key_certifier: A certifier to use on the dictionary's keys. :param callable value_certifie...