Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
373,700
def get(self, resource, **params): return self._execute(self.session.get, , resource, **params)
Generic TeleSign REST API GET handler. :param resource: The partial resource URI to perform the request against, as a string. :param params: Body params to perform the GET request with, as a dictionary. :return: The RestClient Response object.
373,701
def to_UNIXtime(timeobject): if isinstance(timeobject, int): if timeobject < 0: raise ValueError("The time value is a negative number") return timeobject elif isinstance(timeobject, datetime): return _datetime_to_UNIXtime(timeobject) elif isinstance(timeobject, str):...
Returns the UNIXtime corresponding to the time value conveyed by the specified object, which can be either a UNIXtime, a ``datetime.datetime`` object or an ISO8601-formatted string in the format `YYYY-MM-DD HH:MM:SS+00``. :param timeobject: the object conveying the time value :type timeobject: int,...
373,702
async def play(self): if self.repeat and self.current is not None: self.queue.append(self.current) self.current = None self.position = 0 self._paused = False if not self.queue: await self.stop() else: self._is_playing = True ...
Starts playback from lavalink.
373,703
def set_canvas_properties(self, canvas, x_title=None, y_title=None, x_lim=None, y_lim=None, x_labels=True, y_labels=True): self.__canvases[canvas] = canvas_descr(x_title, y_title, x_lim, y_lim, x_labels, y_labels);
! @brief Set properties for specified canvas. @param[in] canvas (uint): Index of canvas whose properties should changed. @param[in] x_title (string): Title for X axis, if 'None', then nothing is displayed. @param[in] y_title (string): Title for Y axis, if 'None', then nothing is di...
373,704
def get_users_with_permission(obj, permission): user_model = get_user_model() return user_model.objects.filter( userobjectpermission__object_pk=obj.pk, userobjectpermission__permission__codename=permission, ).distinct()
Return users with specific permission on object. :param obj: Object to return users for :param permission: Permission codename
373,705
def _folder_item_duedate(self, analysis_brain, item): due_date = analysis_brain.getDueDate if not due_date: return None due_date_str = self.ulocalized_time(due_date, long_format=0) item[] = due_date_str capture_date = ana...
Set the analysis' due date to the item passed in. :param analysis_brain: Brain that represents an analysis :param item: analysis' dictionary counterpart that represents a row
373,706
def get_assets_by_provider(self, resource_id=None): return AssetList(self._provider_session.get_assets_by_provider(resource_id), self._config_map)
Gets an ``AssetList`` from the given provider. In plenary mode, the returned list contains all known assets or an error results. Otherwise, the returned list may contain only those assets that are accessible through this session. arg: resource_id (osid.id.Id): a resource ``Id`` ...
373,707
def introspect_operation(self, operation): return { : operation.py_name, : operation.name, : self.convert_docs(operation.documentation), : self.parse_params(operation.params), : operation.output, }
Introspects an entire operation, returning:: * the method name (to expose to the user) * the API name (used server-side) * docs * introspected information about the parameters * information about the output :param operation: The operation to introspect :type ope...
373,708
def _request(self, endpoint, method, data=None, **kwargs): final_url = self.url + endpoint if not self._is_authenticated: raise LoginRequired rq = self.session if method == : request = rq.get(final_url, **kwargs) else: request = rq.p...
Method to hanle both GET and POST requests. :param endpoint: Endpoint of the API. :param method: Method of HTTP request. :param data: POST DATA for the request. :param kwargs: Other keyword arguments. :return: Response for the request.
373,709
def recall(): a = TpPd(pd=0x3) b = MessageType(mesType=0xb) c = RecallType() d = Facility() packet = a / b / c / d return packet
RECALL Section 9.3.18a
373,710
def remove(self, method_or_response=None, url=None): if isinstance(method_or_response, BaseResponse): response = method_or_response else: response = BaseResponse(method=method_or_response, url=url) while response in self._matches: self._matches.remov...
Removes a response previously added using ``add()``, identified either by a response object inheriting ``BaseResponse`` or ``method`` and ``url``. Removes all matching responses. >>> response.add(responses.GET, 'http://example.org') >>> response.remove(responses.GET, 'http://example.org...
373,711
def namedb_get_name(cur, name, current_block, include_expired=False, include_history=True, only_registered=True): if not include_expired: unexpired_fragment, unexpired_args = namedb_select_where_unexpired_names(current_block, only_registered=only_registered) select_query = "SELECT name_record...
Get a name and all of its history. Note: will return a revoked name Return the name + history on success Return None if the name doesn't exist, or is expired (NOTE: will return a revoked name)
373,712
def threshold(self, scalars, vmin=None, vmax=None, useCells=False): if utils.isSequence(scalars): self.addPointScalars(scalars, "threshold") scalars = "threshold" elif self.scalars(scalars) is None: colors.printc("~times No scalars found with name", scalars, ...
Extracts cells where scalar value satisfies threshold criterion. :param scalars: name of the scalars array. :type scalars: str, list :param float vmin: minimum value of the scalar :param float vmax: maximum value of the scalar :param bool useCells: if `True`, assume array scalar...
373,713
def topWindow(): import_qt(globals()) window = QtGui.QApplication.instance().activeWindow() if not window: return None parent = window.parent() while parent: window = parent parent = window.parent() return window
Returns the very top window for all Qt purposes. :return <QWidget> || None
373,714
def make_helix(aa, axis_distance, z_shift, phi, splay, off_plane): start = numpy.array([axis_distance, 0 + z_shift, 0]) end = numpy.array([axis_distance, (aa * 1.52) + z_shift, 0]) mid = (start + end) / 2 helix = Helix.from_start_and_end(start, end, aa=aa) helix.rotate(...
Builds a helix for a given set of parameters.
373,715
def _first_stoppoint(self, irsb, extra_stop_points=None): if self._stop_points is None and extra_stop_points is None and self.project is None: return None first_imark = True for stmt in irsb.statements: if type(stmt) is pyvex.stmt.IMark: addr =...
Enumerate the imarks in the block. If any of them (after the first one) are at a stop point, returns the address of the stop point. None is returned otherwise.
373,716
def get_vm_host_info(hostip, auth, url): hostId = get_dev_details(hostip, auth, url)[] get_vm_host_info_url = "/imcrs/vrm/host?hostId=" + str(hostId) f_url = url + get_vm_host_info_url payload = None r = requests.get(f_url, auth=auth, headers=HEADERS) try: ...
function takes hostId as input to RESTFUL call to HP IMC :param hostip: int or string of hostip of Hypervisor host :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 pyhpeimc.auth.authclass :return: Dict...
373,717
def get_portchannel_info_by_intf_output_lacp_actor_priority(self, **kwargs): config = ET.Element("config") get_portchannel_info_by_intf = ET.Element("get_portchannel_info_by_intf") config = get_portchannel_info_by_intf output = ET.SubElement(get_portchannel_info_by_intf, "output...
Auto Generated Code
373,718
def cal_gpa(grades): courses_sum = len(grades) points_sum = 0 credit_sum = 0 gpa_points_sum = 0 for grade in grades: point = get_point(grade.get() or grade[]) credit = float(grade[]) points_sum += point credit_sum += credit gpa_points...
根据成绩数组计算课程平均绩点和 gpa, 算法不一定与学校一致, 结果仅供参考 :param grades: :meth:`models.StudentSession.get_my_achievements` 返回的成绩数组 :return: 包含了课程平均绩点和 gpa 的元组
373,719
def getSchema(cls): schema = [] for name, atr in cls.__attributes__: atr = atr.__get__(None, cls) if isinstance(atr, SQLAttribute): schema.append((name, atr)) cls.getSchema = staticmethod(lambda schema=schema: schema) return schema
return all persistent class attributes
373,720
def remove_imaginary_terms(pauli_sums: PauliSum) -> PauliSum: if not isinstance(pauli_sums, PauliSum): raise TypeError("not a pauli sum. please give me one") new_term = sI(0) * 0.0 for term in pauli_sums: new_term += term_with_coeff(term, term.coefficient.real) return new_term
Remove the imaginary component of each term in a Pauli sum. :param pauli_sums: The Pauli sum to process. :return: a purely Hermitian Pauli sum.
373,721
def _lint(self): command = self._get_command() process = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) LOG.info(, .join(command)) stdout, stderr = self._get_output_lines(process) return self._linter.parse(stdou...
Run linter in a subprocess.
373,722
def get_empty_dimension(**kwargs): dimension = JSONObject(Dimension()) dimension.id = None dimension.name = dimension.description = dimension.project_id = None dimension.units = [] return dimension
Returns a dimension object initialized with empty values
373,723
def propertySearch(self, pid, getall=0): matches = [] for n in self: if n.has_key(pid): matches.append(n) if not getall: break else: for v in self.variations: matches = matches + v.propertySearch(pid, getall) if not getall and matches: break return GameTree(matches)
Searches this 'GameTree' for nodes containing matching properties. Returns a 'GameTree' containing the matched node(s). Arguments: - pid : string -- ID of properties to search for. - getall : boolean -- Set to true (1) to return all 'Node''s that match, or to false (0) to return only the first match.
373,724
def get_dataframe(self, force_computation=False): if self.df is not None and not force_computation: return self.df self.df = self.fetch(self.context) self.df = self.preprocess(self.df) self.transform(self.df) return self.df
Preprocesses then transforms the return of fetch(). Args: force_computation (bool, optional) : Defaults to False. If set to True, forces the computation of DataFrame at each call. Returns: pandas.DataFrame: Preprocessed and transformed DataFrame.
373,725
def _check_accessed_members(self, node, accessed): excs = ("AttributeError", "Exception", "BaseException") for attr, nodes in accessed.items(): try: node.local_attr(attr) continue except astroid.N...
check that accessed members are defined
373,726
def modules(): * cmd = .format(_detect_os()) ret = {} ret[] = [] ret[] = [] out = __salt__[](cmd).splitlines() for line in out: comps = line.split() if not comps: continue if in line: ret[].append(comps[0]) if in line: ret...
Return list of static and shared modules (``apachectl -M``) CLI Example: .. code-block:: bash salt '*' apache.modules
373,727
def read_storage_class(self, name, **kwargs): kwargs[] = True if kwargs.get(): return self.read_storage_class_with_http_info(name, **kwargs) else: (data) = self.read_storage_class_with_http_info(name, **kwargs) return data
read the specified StorageClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_storage_class(name, async_req=True) >>> result = thread.get() :param async_req bool :param str ...
373,728
def metar(data: MetarData, units: Units) -> str: speech = [] if data.wind_direction and data.wind_speed: speech.append(wind(data.wind_direction, data.wind_speed, data.wind_gust, data.wind_variable_direction, units.wind_speed)) if data.visibi...
Convert MetarData into a string for text-to-speech
373,729
def get_success_enrollment_message(cls, users, enrolled_in): enrolled_count = len(users) return ( , ungettext( , , enrolled_count, ).format( enrolled_count=enrolled_count, enrolle...
Create message for the users who were enrolled in a course or program. Args: users: An iterable of users who were successfully enrolled enrolled_in (str): A string identifier for the course or program the users were enrolled in Returns: tuple: A 2-tuple containing a...
373,730
def get_route_to(self, destination=, protocol=): routes = {} if destination: destination = "<destination>{0}</destination>".format(destination) if protocol: protocol = "<type>{0}</type>".format(protocol) cmd = "<show><routing...
Return route details to a specific destination, learned from a certain protocol.
373,731
def copy(self): return Particle(copy(self.position), copy(self.velocity), self.fitness)
Creates a copy of itself
373,732
def parallel_bulk( client, actions, thread_count=4, chunk_size=500, max_chunk_bytes=100 * 1024 * 1024, queue_size=4, expand_action_callback=expand_action, *args, **kwargs ): from multiprocessing.pool import ThreadPool actions = map(expand_action_callback, acti...
Parallel version of the bulk helper run in multiple threads at once. :arg client: instance of :class:`~elasticsearch.Elasticsearch` to use :arg actions: iterator containing the actions :arg thread_count: size of the threadpool to use for the bulk requests :arg chunk_size: number of docs in one chunk se...
373,733
def circles(st, layer, axis, ax=None, talpha=1.0, cedge=, cface=): pos = st.obj_get_positions() rad = st.obj_get_radii() shape = st.ishape.shape.tolist() shape.pop(axis) if ax is None: fig = plt.figure() axisbg = if cface == else sx, sy = ((1,shape[1]/float(shape[0])...
Plots a set of circles corresponding to a slice through the platonic structure. Copied from twoslice_overlay with comments, standaloneness. Inputs ------ pos : array of particle positions; [N,3] rad : array of particle radii; [N] ax : plt.axis instance layer : Which layer of...
373,734
def _syspath(dev): dev = _devbase(dev) dev = re.sub(r, r, dev) return os.path.join(, dev)
Full SysFS path of a device
373,735
def update_note(note, **kwargs): note_i = _get_note(note.id) if note.ref_key != note_i.ref_key: raise HydraError("Cannot convert a %s note to a %s note. Please create a new note instead."%(note_i.ref_key, note.ref_key)) note_i.set_ref(note.ref_key, note.ref_id) note_i.value = note.value ...
Update a note
373,736
def server_list(endpoint_id): endpoint, server_list = get_endpoint_w_server_list(endpoint_id) if server_list == "S3": server_list = {"s3_url": endpoint["s3_url"]} fields = [("S3 URL", "s3_url")] text_format = FORMAT_TEXT_RECORD else: fields = ( ("ID...
Executor for `globus endpoint server list`
373,737
def add_hotkey(control, key, func, id = None): if win32con is None: raise RuntimeError() logger.debug(, key, control, func) modifiers, keycode = str_to_key(key, key_table = win32con, accel_format = , key_format = , key_transpositions = {: }) id = get_id(id) control.Bind(wx.EVT_HOTKEY, func, id = id) l = _hotk...
Add a global hotkey bound to control via id that should call func. control: The control to bind to. key: The hotkey to use. func: The func to call. id: The new ID to use (defaults to creating a new ID.
373,738
def modify_product(self, product_id, name=None, description=None, attributes={}): request_data = {: product_id} if name: request_data[]=name if description: request_data[]=description if attributes: request_data[]=attributes return self._call_rest_api(, , data=request_da...
modify_product(self, product_id, name=None, description=None, attributes={}) Modify an existing product :Parameters: * *product_id* (`string`) -- identifier of an existing product * *name* (`string`) -- name of the product * *description* (`string`) -- product description ...
373,739
def name_scope(name=None): def name_scope_wrapper_decorator(method): @functools.wraps(method) def name_scope_wrapper(*args, **kwargs): scope_name = name if name is not None else method.__name__ with tf.name_scope(scope_name): return method(*args, **kwargs...
This decorator wraps a function so that it runs inside a TensorFlow name scope. The name is given by the `name` option; if this is None, then the name of the function will be used. ``` >>> @name_scope() >>> def foo(...): >>> # now runs inside scope "foo" >>> @name_scope('bar') >>> de...
373,740
def build_vep_string(vep_info, vep_columns): logger = getLogger(__name__) logger.debug("Building vep string from {0}".format(vep_info)) logger.debug("Found vep headers {0}".format(vep_columns)) vep_strings = [] for vep_annotation in vep_info: try: vep_info_list = [ ...
Build a vep string formatted string. Take a list with vep annotations and build a new vep string Args: vep_info (list): A list with vep annotation dictionaries vep_columns (list): A list with the vep column names found in the header of the vcf Returns: string: ...
373,741
def _attempting(self, text): consumed = len(self.original_text) - len(text) self.most_consumed = max(consumed, self.most_consumed)
Keeps track of the furthest point in the source code the parser has reached to this point.
373,742
def Pn(x): Pn = {} Pn[] = P0(x) Pn[] = P1(x) Pn[] = P2(x) Pn[] = P3(x) Pn[] = P4(x) Pn[] = P5(x) Pn[] = P6(x) Pn[] = P8(x) Pn[] = P10(x) Pn[] = P12(x) Pn[] = P14(x) Pn[] = P16(x) Pn[] = P18(x) Pn[] = P20(x) Pn[] = P22(x) Pn[] = P24(x) Pn[] = P...
Calculate Legendre polyomials P0 to P28 and returns them in a dictionary ``Pn``. :param float x: argument to calculate Legendre polynomials :return Pn: dictionary which contains order of Legendre polynomials (from 0 to 28) as keys and the corresponding evaluation ...
373,743
def get_rsa_pub_key(path): log.debug() if HAS_M2: with salt.utils.files.fopen(path, ) as f: data = f.read().replace(b, b) bio = BIO.MemoryBuffer(data) key = RSA.load_pub_key_bio(bio) else: with salt.utils.files.fopen(path) as f: key = RSA.importKe...
Read a public key off the disk.
373,744
def from_config(cls, cp, **kwargs): r args = cls._init_args_from_config(cp) args[] = low_frequency_cutoff_from_config(cp) args[] = high_frequency_cutoff_from_config(cp) ignore_args = [, , ] args.update(cls.extra_args_from_config(cp, "model", ...
r"""Initializes an instance of this class from the given config file. Parameters ---------- cp : WorkflowConfigParser Config file parser to read. \**kwargs : All additional keyword arguments are passed to the class. Any provided keyword will over ride...
373,745
def on_connection_open(self, connection): LOGGER.debug() connection.add_on_connection_blocked_callback( self.on_connection_blocked) connection.add_on_connection_unblocked_callback( self.on_connection_unblocked) connection.add_backpressure_callback(self.on...
This method is called by pika once the connection to RabbitMQ has been established. :type connection: pika.TornadoConnection
373,746
def get_string_plus_property_value(value): if value: if isinstance(value, str): return [value] if isinstance(value, list): return value if isinstance(value, tuple): return list(value) return None
Converts a string or list of string into a list of strings :param value: A string or a list of strings :return: A list of strings or None
373,747
def _curvelength(self, x0, y0, x1, y1, x2, y2, x3, y3, n=20): length = 0 xi = x0 yi = y0 for i in range(n): t = 1.0 * (i + 1) / n pt_x, pt_y, pt_c1x, pt_c1y, pt_c2x, pt_c2y = \ self._curvepoint(t, x0, y0, x1, y1, x2, y2, x3, y3) ...
Returns the length of the spline. Integrates the estimated length of the cubic bezier spline defined by x0, y0, ... x3, y3, by adding the lengths of lineair lines between points at t. The number of points is defined by n (n=10 would add the lengths of lines between 0.0 an...
373,748
def split_sequence_as_iterable(self, values): print(self.count) s = iter(self.index.sorter) for c in self.count: yield (values[i] for i in itertools.islice(s, int(c)))
Group sequence into iterables Parameters ---------- values : iterable of length equal to keys iterable of values to be grouped Yields ------ iterable of items in values Notes ----- This is the preferred method if values has random ac...
373,749
def from_grpc_status(status_code, message, **kwargs): error_class = exception_class_for_grpc_status(status_code) error = error_class(message, **kwargs) if error.grpc_status_code is None: error.grpc_status_code = status_code return error
Create a :class:`GoogleAPICallError` from a :class:`grpc.StatusCode`. Args: status_code (grpc.StatusCode): The gRPC status code. message (str): The exception message. kwargs: Additional arguments passed to the :class:`GoogleAPICallError` constructor. Returns: Google...
373,750
def clean(self): logger.info() shutil.move( os.path.join( self.data_dir, ), self.final_path ) shutil.rmtree(os.path.join(self.data_dir, )) os.remove(self.zip_path)
Get the .txt file from within the many-layered directory structure, then delete the directories.
373,751
def update_submit_s3_uri(estimator, job_name): if estimator.uploaded_code is None: return pattern = r submit_uri = estimator.uploaded_code.s3_prefix submit_uri = re.sub(pattern, job_name, submit_uri) script_name = estimator.uploaded_code.script_name estimator.uploaded_co...
Updated the S3 URI of the framework source directory in given estimator. Args: estimator (sagemaker.estimator.Framework): The Framework estimator to update. job_name (str): The new job name included in the submit S3 URI Returns: str: The updated S3 URI of framework source directory
373,752
def p_LD_reg_val(p): s = % p[2] if p[2] in REGS16: s += p[0] = Asm(p.lineno(1), s, p[4])
asm : LD reg8 COMMA expr | LD reg8 COMMA pexpr | LD reg16 COMMA expr | LD reg8_hl COMMA expr | LD A COMMA expr | LD SP COMMA expr | LD reg8i COMMA expr
373,753
def scheduler(ctx, xmlrpc, xmlrpc_host, xmlrpc_port, inqueue_limit, delete_time, active_tasks, loop_limit, fail_pause_num, scheduler_cls, threads, get_object=False): g = ctx.obj Scheduler = load_cls(None, None, scheduler_cls) kwargs = dict(taskdb=g.taskdb, projectdb=g.proje...
Run Scheduler, only one scheduler is allowed.
373,754
def delete_model_translation(self, request, translation): master = translation.master for qs in self.get_translation_objects(request, translation.language_code, obj=master, inlines=self.delete_inline_translations): if isinstance(qs, (tuple, list)): ...
Hook for deleting a translation. This calls :func:`get_translation_objects` to collect all related objects for the translation. By default, that includes the translations for inline objects.
373,755
def is_floating(self): return ( self.is_numpy_compatible and np.issubdtype(self.as_numpy_dtype, np.floating) ) or self.base_dtype == bfloat16
Returns whether this is a (non-quantized, real) floating point type.
373,756
def getstats(self, save=True, filename=None, samples=None, subset=None, ablation_time=False): slst = [] if samples is not None: subset = self.make_subset(samples) samples = self._get_samples(subset) for s in self.stats_calced: for nm in [n for n in sam...
Return pandas dataframe of all sample statistics.
373,757
def handle(self, argv=None): desc = ( ) parser = argparse.ArgumentParser(description=desc) parser.add_argument( , , action=, version=pkg_resources.get_distribution("zappa").version, help= ) parser.add_argument( ...
Main function. Parses command, load settings and dispatches accordingly.
373,758
def serviceQueues(self, limit=None): r = self.dequeue_pre_prepares() r += self.inBoxRouter.handleAllSync(self.inBox, limit) r += self.send_3pc_batch() r += self._serviceActions() return r
Process `limit` number of messages in the inBox. :param limit: the maximum number of messages to process :return: the number of messages successfully processed
373,759
def dereplicate_seqs(seqs_fp, output_fp, min_size=2, use_log=False, threads=1): logger = logging.getLogger(__name__) logger.info( % seqs_fp) log_name = "%s.log" % output_fp params = [, , seqs_fp, , o...
Dereplicate FASTA sequences and remove singletons using VSEARCH. Parameters ---------- seqs_fp : string filepath to FASTA sequence file output_fp : string file path to dereplicated sequences (FASTA format) min_size : integer, optional discard sequences with an abundance valu...
373,760
def from_spec(spec, kwargs=None): layer = util.get_object( obj=spec, predefined_objects=tensorforce.core.networks.layers, kwargs=kwargs ) assert isinstance(layer, Layer) return layer
Creates a layer from a specification dict.
373,761
def lines(self): if self._cache.lines is None: self._cache.lines = _ImmutableLineList(self.text.split()) return self._cache.lines
Array of all the lines.
373,762
def get_rsn_ie(defcipher, defauth, data): answers = dict() answers[] = data[0] + (data[1] << 8) data = data[2:] if len(data) < 4: answers[] = answers[] = defcipher return answers answers[] = get_cipher(data) data = data[4:] if len(data) < 2: answers[] = defciphe...
http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n441. Positional arguments: defcipher -- default cipher if not in data (string). defauth -- default authentication suites if not in data (string). data -- bytearray data to read. Returns: Dict.
373,763
def root(self): sector = self.header.directory_sector_start position = (sector + 1) << self.header.sector_shift return RootEntry(self, position)
Property provides access to root object in CFB.
373,764
def songs_iter(self, *, continuation_token=None, export_type=1): def track_info_to_dict(track_info): return dict( (field.name, value) for field, value in track_info.ListFields() ) while True: response = self._call( mm_calls.ExportIDs, self.uploader_id, continuation_token=continuati...
Get a paged iterator of Music Library songs. Parameters: continuation_token (str, Optional): The token of the page to return. Default: Not sent to get first page. export_type (int, Optional): The type of tracks to return. 1 for all tracks, 2 for promotional and purchased. Default: ``1`` Yields: l...
373,765
def _cdata_io(self, action, data, ctype, frames): assert ctype in _ffi_types.values() self._check_if_closed() if self.seekable(): curr = self.tell() func = getattr(_snd, + action + + ctype) frames = func(self._file, data, frames) _error_check(self._...
Call one of libsndfile's read/write functions.
373,766
def set_attributes(self, **kwargs): self.clear_derived() kwargs = dict(kwargs) for name, value in kwargs.items(): try: self.getp(name) except KeyError: print ("Warning: %s does not have attribute %s" % ...
Set a group of attributes (parameters and members). Calls `setp` directly, so kwargs can include more than just the parameter value (e.g., bounds, free, etc.).
373,767
def pairdists(alignment, subs_model, alpha=None, ncat=4, tolerance=1e-6, verbose=False): if not isinstance(subs_model, phylo_utils.models.Model): raise ValueError("Can't handle this model: {}".format(model)) if alpha is None: alpha = 1.0 ncat = 1 tm = TransitionMatr...
Load an alignment, calculate all pairwise distances and variances model parameter must be a Substitution model type from phylo_utils
373,768
def prep_hla(work_dir, sample, calls, hlas, normal_bam, tumor_bam): work_dir = utils.safe_makedir(os.path.join(work_dir, sample, "inputs")) hla_file = os.path.join(work_dir, "%s-hlas.txt" % sample) with open(calls) as in_handle: with open(hla_file, "w") as out_handle: next(in_handle...
Convert HLAs into ABSOLUTE format for use with LOHHLA. LOHHLA hard codes names to hla_a, hla_b, hla_c so need to move
373,769
def evaluation_get(self, service_staff_id, start_date, end_date, session): request = TOPRequest() request[] = service_staff_id request[] = start_date request[] = end_date self.create(self.execute(request, session)) return self.staff_eval_stat_on_days
taobao.wangwang.eservice.evaluation.get 客服评价统计 根据操作者ID,返回被查者ID指定日期内每个帐号每日的"客服评价统计" 备注: - 1、如果是操作者ID=被查者ID,返回被查者ID的"客服评价统计"。 - 2、如果操作者是组管理员,他可以查询他的组中的所有子帐号的"客服评价统计"。 - 3、如果操作者是主账户,他可以查询所有子帐号的"客服评价统计"。 - 4、被查者ID可以是多个,用 "," 隔开,id数不能超过30。 - 5、开始时间与结束时间之间...
373,770
def genealogic_types(self): types = [] parent = self while parent: types.append(parent.rest_name) parent = parent.parent_object return types
Get genealogic types Returns: Returns a list of all parent types
373,771
def _delete(self, namespace, stream, start_id, end_time, configuration): start_id_event = Event(start_id) end_id_event = Event(uuid_from_kronos_time(end_time, _type=UUIDType.HIGHEST)) stream_events = self.db[namespace][stream] lo = bisect.bisect_...
Delete events with id > `start_id` and end_time <= `end_time`.
373,772
def delete_lbaas_member(self, lbaas_member, lbaas_pool): return self.delete(self.lbaas_member_path % (lbaas_pool, lbaas_member))
Deletes the specified lbaas_member.
373,773
def json_minify(string, strip_space=True): in_string = False in_multi = False in_single = False new_str = [] index = 0 for match in re.finditer(TOKENIZER, string): if not (in_multi or in_single): tmp = string[index:match.start()] if not in_string and stri...
Removes whitespace from json strings, returning the string
373,774
def removeFriend(self, friend_id=None): payload = {"friend_id": friend_id, "unref": "none", "confirm": "Confirm"} r = self._post(self.req_url.REMOVE_FRIEND, payload) query = parse_qs(urlparse(r.url).query) if "err" not in query: log.debug("Remove was successful!") ...
Removes a specifed friend from your friend list :param friend_id: The ID of the friend that you want to remove :return: Returns error if the removing was unsuccessful, returns True when successful.
373,775
def create(obj: PersistedObject, obj_type: Type[T], errors: Dict[Type, Exception]): e = NoParserFoundForUnionType( .format(obj=obj, typ=get_pretty_type_str(obj_type), errs=errors)) e.errors = errors ...
Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests https://github.com/nose-devs/nose/issues/725 :param obj: :param errors: a dictionary of the errors raised for each alternate type tried :return:
373,776
def delete_joined_table_sql(qualified_name, removing_qualified_name, primary_key): condition_template = where_clause = .join(condition_template.format(pkey, pkey) for pkey in primary_key) delete_statement = ( ).format(table=qualified_name, ...
SQL statement for a joined delete from. Generate SQL statement for deleting the intersection of rows between both tables from table referenced by tablename.
373,777
def parse_colors(path): if path.endswith(".txt"): return parse_rgb_txt_file(path) elif path.endswith(".json"): return parse_json_color_file(path) raise TypeError("colorful only supports .txt and .json files for colors")
Parse the given color files. Supported are: * .txt for X11 colors * .json for colornames
373,778
def has_option(self, option_name): if self.prefix: option_name = self.prefix + self.seperator + option_name item_names = option_name.split(self.seperator) node = self._storage for item_name in item_names: if node is None: return False if not item_name in node: return False node = node[ite...
Check that an option exists. :param str option_name: The name of the option to check. :return: True of the option exists in the configuration. :rtype: bool
373,779
def derive_from_seed(self, offset): seed = int(hexlify(bytes(self)).decode("ascii"), 16) z = int(hexlify(offset).decode("ascii"), 16) order = ecdsa.SECP256k1.order secexp = (seed + z) % order secret = "%0x" % secexp if len(secret) < 64: secret = ("0"...
Derive private key using "generate_from_seed" method. Here, the key itself serves as a `seed`, and `offset` is expected to be a sha256 digest.
373,780
def __shouldSysExit(self, iteration): if self._exitAfter is None \ or iteration < self._exitAfter: return False results = self._jobsDAO.modelsGetFieldsForJob(self._jobID, []) modelIDs = [e[0] for e in results] modelNums = [json.loads(e[1][0])[][] for e in results] sameModelNumb...
Checks to see if the model should exit based on the exitAfter dummy parameter
373,781
def items_to_extract(self, offset=0, length=None): endoffset = length and offset + length qs = self.origin_data()[offset:endoffset] self.items_to_extract_length = qs.count() return qs
Return an iterable of specific items to extract. As a side-effect, set self.items_to_extract_length. :param offset: where to start extracting :param length: how many to extract :return: An iterable of the specific
373,782
def team_absent(name, profile="github", **kwargs): test ret = { : name, : {}, : None, : } target = __salt__[](name, profile=profile, **kwargs) if not target: ret[] = .format(name) ret[] = True return ret else: if __opts__[]: ...
Ensure a team is absent. Example: .. code-block:: yaml ensure team test is present in github: github.team_absent: - name: 'test' The following parameters are required: name This is the name of the team in the organization. .. versionadded:: 2016.11....
373,783
def findCaller(self, stack_info=False, callers=0): f = logging.currentframe() sinfo = sinfo[:-1] sio.close() rv = (co.co_filename, f.f_lineno, co.co_name, sinfo) break return rv
Find the stack frame of the caller so that we can note the source file name, line number and function name. Not only ignore this class's and logger's source, but also as many callers as requested.
373,784
def _call_lrem(self, command, count, value, *args, **kwargs): if not count: if self.indexable: self.deindex([value]) return self._traverse_command(command, count, value, *args, **kwargs) else: return self._reset(command, count, value, *args, *...
If count is 0, we remove all elements equal to value, so we know we have nothing to index, and this value to deindex. In other case, we don't know how much elements will remain in the list, so we have to do a full deindex/reindex. So do it carefuly.
373,785
def ellplot (mjr, mnr, pa): _ellcheck (mjr, mnr, pa) import omega as om th = np.linspace (0, 2 * np.pi, 200) x, y = ellpoint (mjr, mnr, pa, th) return om.quickXY (x, y, % (mjr, mnr, pa * 180 / np.pi))
Utility for debugging.
373,786
def members(self, as_set=False): if as_set: return frozenset(map(self._members.__getitem__, self._indexes())) return tuple(map(self._members.__getitem__, self._indexes()))
Return the set members tuple/frozenset.
373,787
def get_context_from_xlsx(self): if re.search(, self.project.CONTEXT_SOURCE_FILE): resp = requests.get(self.project.CONTEXT_SOURCE_FILE) content = resp.content else: try: with open(self.project.CONTEXT_SOURCE_FILE) as xlsxfile: ...
Get context from an Excel file
373,788
def update_repository(self, repository_form): if self._catalog_session is not None: return self._catalog_session.update_catalog(catalog_form=repository_form) collection = JSONClientValidated(, collection=, ...
Updates an existing repository. arg: repository_form (osid.repository.RepositoryForm): the form containing the elements to be updated raise: IllegalState - ``repository_form`` already used in an update transaction raise: InvalidArgument - the form contains a...
373,789
def as_list(self): "return some attributes as a list" netloc = if self.vpath_connector: netloc = +self.vpath_connector+ elif self.authority: netloc = self.authority else: netloc = self.netloc return [ self.scheme, ...
return some attributes as a list
373,790
def grab_zipped_url(zipped_url, ensure=True, appname=, download_dir=None, force_commonprefix=True, cleanup=False, redownload=False, spoof=False): r zipped_url = clean_dropbox_link(zipped_url) zip_fname = split(zipped_url)[1] data_name = split_archive_ext(zip_fname...
r""" downloads and unzips the url Args: zipped_url (str): url which must be either a .zip of a .tar.gz file ensure (bool): eager evaluation if True(default = True) appname (str): (default = 'utool') download_dir (str): containing downloading directory force_commonprefix...
373,791
def _diff_and_summarize(from_csv, to_csv, index_columns, stream=sys.stdout, sep=, ignored_columns=None, significance=None): from_records = list(records.load(from_csv, sep=sep)) to_records = records.load(to_csv, sep=sep) diff = patch.create(from_records, to_records, index_column...
Print a summary of the difference between the two files.
373,792
def refreshResults( self ): if ( self.currentMode() == XOrbBrowserWidget.Mode.Detail ): self.refreshDetails() elif ( self.currentMode() == XOrbBrowserWidget.Mode.Card ): self.refreshCards() else: self.refreshThumbnails()
Joins together the queries from the fixed system, the search, and the query builder to generate a query for the browser to display.
373,793
def _set_collector_ip(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=collector_ip.collector_ip, is_container=, presence=False, yang_name="collector-ip", rest_name="ip", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register...
Setter method for collector_ip, mapped from YANG variable /telemetry/collector/collector_ip (container) If this variable is read-only (config: false) in the source YANG file, then _set_collector_ip is considered as a private method. Backends looking to populate this variable should do so via calling thi...
373,794
def is_dec(ip): try: dec = int(str(ip)) except ValueError: return False if dec > 4294967295 or dec < 0: return False return True
Return true if the IP address is in decimal notation.
373,795
def check_membership(self, groups): if not groups or groups == []: return True if self.request.user.is_superuser: return True user_groups = self.request.user.groups.values_list("name", flat=True) return set(groups).intersection(set(user_groups))
Allows for objects with no required groups
373,796
def connect(self, output_port, input_port): ConnectionClass = output_port.connection_class self.connections.append(ConnectionClass(output_port, input_port))
Connect two :class:`.Effect` instances in this pedalboard. For this, is necessary informs the output port origin and the input port destination:: >>> pedalboard.append(driver) >>> pedalboard.append(reverb) >>> driver_output = driver.outputs[0] >>> reverb_input = ...
373,797
def get_hla(sample, cromwell_dir, hla_glob): hla_dir = glob.glob(os.path.join(cromwell_dir, hla_glob, "align", sample, "hla"))[0] fastq = os.path.join(hla_dir, "OptiType-HLA-A_B_C-input.fq") calls = os.path.join(hla_dir, "%s-optitype.csv" % sample) return fastq, calls
Retrieve HLA calls and input fastqs for a sample.
373,798
def set_max_image_pixels(self, pixels): if (pixels): Image.MAX_IMAGE_PIXELS = pixels Image.warnings.simplefilter( , Image.DecompressionBombWarning)
Set PIL limit on pixel size of images to load if non-zero. WARNING: This is a global setting in PIL, it is not local to this manipulator instance! Setting a value here will not only set the given limit but also convert the PIL "DecompressionBombWarning" into an error. Thus sett...
373,799
def _compute_stddevs(self, C, mag, rjb, imt, stddev_types): sigma_ale_m = np.interp(mag, [5.0, 5.5, 8.0], [C[], C[], C[]]) sigma_ale_rjb = np.interp(rjb, [5.0, 20.0], [C[], C[]]) sigma_ale = np.sqrt(sigma_ale_m ** 2 + sigma_ale_rjb ** 2) ...
Compute total standard deviation, equations 5 and 6, page 48.