Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
11,700
def recursive_dictionary_get(keys, dictionary): if "." in keys and len(keys) > 1: key = keys.split(".", 1) new_dict = dictionary.get(key[0]) if not new_dict or not hasattr(new_dict, "get"): return None return recursive_dictionary_get(key[1], new_dict) el...
Gets contents of requirement key recursively so users can search for specific keys inside nested requirement dicts. :param keys: key or dot separated string of keys to look for. :param dictionary: Dictionary to search from :return: results of search or None
11,701
def html_temp_launch(html): fname = tempfile.gettempdir()+"/swhlab/temp.html" with open(fname,) as f: f.write(html) webbrowser.open(fname)
given text, make it a temporary HTML file and launch it.
11,702
def init_app(self, app): if not hasattr(app, ): app.extensions = {} app.extensions[] = self self._set_default__configuration_options(app)
Register this extension with the flask app. :param app: A flask application
11,703
def _simple_command(self, command, arg=None, **kwargs): self._protocol.send_command(command, arg) return self._protocol.handle_simple_responses(**kwargs)
Send a simple command.
11,704
def open(self, vendor_id: int = 0x16c0, product_id: int = 0x5dc, bus: int = None, address: int = None) -> bool: kwargs = {} if vendor_id: kwargs["idVendor"] = vendor_id if product_id: kwargs["idProduct"] = product_id if bus: kwargs["bus"] = bu...
Open the first device that matches the search criteria. Th default parameters are set up for the likely most common case of a single uDMX interface. However, for the case of multiple uDMX interfaces, you can use the bus and address paramters to further specifiy the uDMX interface to be o...
11,705
def remove(self, item): check_not_none(item, "Value can't be None") item_data = self._to_data(item) return self._encode_invoke(list_remove_codec, value=item_data)
Removes the specified element's first occurrence from the list if it exists in this list. :param item: (object), the specified element. :return: (bool), ``true`` if the specified element is present in this list.
11,706
def close(self): try: if not self.session.closed: if self.session._connector_owner: self.session._connector.close() self.session._connector = None except Exception as e: Config.dummy_logger.error("can not close session ...
Should be closed[explicit] while using external session or connector, instead of close by self.__del__.
11,707
def _xml_element_value(el: Element, int_tags: list): if el.text is None: return None try: if el.tag in int_tags: return int(el.text) except: pass s = str(el.text).strip() return s if s else None
Gets XML Element value. :param el: Element :param int_tags: List of tags that should be treated as ints :return: value of the element (int/str)
11,708
def find_bindmounts(self): for mountpoint, (orig, fs, opts) in self.mountpoints.items(): if in opts and re.match(self.re_pattern, mountpoint): yield mountpoint
Finds all bind mountpoints that are inside mounts that match the :attr:`re_pattern`
11,709
def is_data_dependent(fmto, data): if callable(fmto.data_dependent): return fmto.data_dependent(data) return fmto.data_dependent
Check whether a formatoption is data dependent Parameters ---------- fmto: Formatoption The :class:`Formatoption` instance to check data: xarray.DataArray The data array to use if the :attr:`~Formatoption.data_dependent` attribute is a callable Returns ------- bool ...
11,710
def add_tcp_flag(self, tcp_flag): if tcp_flag not in [1, 2, 4, 8, 16, 32, 64, 128]: raise ValueError("Invalid TCP flag. Valid: [1, 2, 4, 8, 16,32, 64, 128]") prev_size = 0 if self._json_dict.get() is None: self._json_dict[] = 0 else: prev_s...
Add a single TCP flag - will be OR'd into the existing bitmask
11,711
def load_command_table(self, args): with CommandSuperGroup(__name__, self, ) as super_group: with super_group.group() as group: group.command(, ) with CommandSuperGroup(__name__, self, , client...
Load all Service Fabric commands
11,712
def handle_stranded_tasks(self, engine): lost = self.pending[engine] for msg_id in lost.keys(): if msg_id not in self.pending[engine]: continue raw_msg = lost[msg_id].raw_msg idents,msg = self.session.feed_identities(raw_msg,...
Deal with jobs resident in an engine that died.
11,713
def syncFlags(self): self.flags = set(self.skype.conn("GET", SkypeConnection.API_FLAGS, auth=SkypeConnection.Auth.SkypeToken).json())
Update the cached list of all enabled flags, and store it in the :attr:`flags` attribute.
11,714
def live_profile(script, argv, profiler_factory, interval, spawn, signum, pickle_protocol, mono): filename, code, globals_ = script sys.argv[:] = [filename] + list(argv) parent_sock, child_sock = socket.socketpair() stderr_r_fd, stderr_w_fd = os.pipe() pid = os.fork() if pi...
Profile a Python script continuously.
11,715
def convert_sum( params, w_name, scope_name, inputs, layers, weights, names ): print() def target_layer(x): import keras.backend as K return K.sum(x) lambda_layer = keras.layers.Lambda(target_layer) layers[scope_name] = lambda_layer(layers[inputs[0]])
Convert sum. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for keras layers
11,716
def bounded_uniform(cls, lowest, highest, weight_interval=None): if weight_interval is None: weights = [(lowest, 1), (highest, 1)] else: i = lowest weights = [] while i < highest: weights.append((i, 1)) i += weight_...
Initialize with a uniform distribution between two values. If no ``weight_interval`` is passed, this weight distribution will just consist of ``[(lowest, 1), (highest, 1)]``. If specified, weights (still with uniform weight distribution) will be added every ``weight_interval``. Use this...
11,717
def add_auth_to_method(self, path, method_name, auth, api): method_authorizer = auth and auth.get() if method_authorizer: api_auth = api.get() api_authorizers = api_auth and api_auth.get() default_authorizer = api_auth and api_auth.get() self.set...
Adds auth settings for this path/method. Auth settings currently consist solely of Authorizers but this method will eventually include setting other auth settings such as API Key, Resource Policy, etc. :param string path: Path name :param string method_name: Method name :param d...
11,718
def get_providers(self, security_filter, name_filter=, only_providers_flag=, internal_external=, ordering_authority=, real_provider=): magic = self._magic_json( action=TouchWorksMag...
invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action :param security_filter - This is the EntryCode of the Security_Code_DE dictionary for the providers being sought. A list of valid security codes can be obtained from GetDictionary on the Security_Code_DE dictio...
11,719
def _toplevel(cls): superclasses = ( list(set(ClosureModel.__subclasses__()) & set(cls._meta.get_parent_list())) ) return next(iter(superclasses)) if superclasses else cls
Find the top level of the chain we're in. For example, if we have: C inheriting from B inheriting from A inheriting from ClosureModel C._toplevel() will return A.
11,720
def register(self, renewable, timeout=300): starttime = renewable_start_time(renewable) renew_future = asyncio.ensure_future(self._auto_lock_renew(renewable, starttime, timeout), loop=self.loop) self._futures.append(renew_future)
Register a renewable entity for automatic lock renewal. :param renewable: A locked entity that needs to be renewed. :type renewable: ~azure.servicebus.aio.async_message.Message or ~azure.servicebus.aio.async_receive_handler.SessionReceiver :param timeout: A time in seconds that the loc...
11,721
def _get_dependency_specification(dep_spec: typing.List[tuple]) -> str: return ",".join(dep_range[0] + dep_range[1] for dep_range in dep_spec)
Get string representation of dependency specification as provided by PythonDependencyParser.
11,722
def Zuo_Stenby(T, Tc, Pc, omega): r Tc_1, Pc_1, omega_1 = 190.56, 4599000.0/1E5, 0.012 Tc_2, Pc_2, omega_2 = 568.7, 2490000.0/1E5, 0.4 Pc = Pc/1E5 def ST_r(ST, Tc, Pc): return log(1 + ST/(Tc**(1/3.0)*Pc**(2/3.0))) ST_1 = 40.520*(1 - T/Tc)**1.287 ST_2 = 52.095*(1 - T/Tc)**1.21548 ...
r'''Calculates air-water surface tension using the reference fluids methods of [1]_. .. math:: \sigma^{(1)} = 40.520(1-T_r)^{1.287} \sigma^{(2)} = 52.095(1-T_r)^{1.21548} \sigma_r = \sigma_r^{(1)}+ \frac{\omega - \omega^{(1)}} {\omega^{(2)}-\omega^{(1)}} (\sigma_r^{(2)}-\sigma_r...
11,723
def create_tag(self, name): return self._tag(self.request(, method=, data={ "name": name, })["tag"])
.. versionadded:: 0.2.0 Add a new tag resource to the account :param str name: the name of the new tag :rtype: Tag :raises DOAPIError: if the API endpoint replies with an error
11,724
def find_weights(self, scorer, test_size=0.2, method=): p = Optimizer(self.models, test_size=test_size, scorer=scorer) return p.minimize(method)
Finds optimal weights for weighted average of models. Parameters ---------- scorer : function Scikit-learn like metric. test_size : float, default 0.2 method : str Type of solver. Should be one of: - 'Nelder-Mead' - 'Powell' ...
11,725
def _modelmat(self, X, term=-1): X = check_X(X, n_feats=self.statistics_[], edge_knots=self.edge_knots_, dtypes=self.dtype, features=self.feature, verbose=self.verbose) return self.terms.build_columns(X, term=term)
Builds a model matrix, B, out of the spline basis for each feature B = [B_0, B_1, ..., B_p] Parameters --------- X : array-like of shape (n_samples, m_features) containing the input dataset term : int, optional term index for which to compute the model m...
11,726
def upload_file_content(self, file_id, etag=None, source=None, content=None): "71e1ed9ee52e565a56aec66bc648a32c""71e1ed9ee52e565a56aec66bc648a32c" if not is_valid_uuid(file_id): raise StorageArgumentException( .format(file_id)) if not (source or content) or (source a...
Upload a file content. The file entity must already exist. If an ETag is provided the file stored on the server is verified against it. If it does not match, StorageException is raised. This means the client needs to update its knowledge of the resource before attempting to update again...
11,727
def into(self, val: str) -> Union[, ]: if val in self.paths: return self.paths[val] if self.param: return self.param raise IndexError(_("Value {} is missing from api").format(val))
Get another leaf node with name `val` if possible
11,728
def _checkgrad(self, target_param=None, verbose=False, step=1e-6, tolerance=1e-3, df_tolerance=1e-12): if not self._model_initialized_: import warnings warnings.warn("This model has not been initialized, try model.inititialize_model()", RuntimeWarning) return False ...
Check the gradient of the ,odel by comparing to a numerical estimate. If the verbose flag is passed, individual components are tested (and printed) :param verbose: If True, print a "full" checking of each parameter :type verbose: bool :param step: The size of the step around wh...
11,729
def updateResults(self, newResults, **kwArgs): if in kwArgs.keys(): reset = kwArgs[] else: reset = 0 if reset == 0: for key in newResults.keys(): if key == or key == : continue self....
Update the results related to this request excluding the 'response' and 'logEntries' values. We specifically update (if present): overallRC, rc, rs, errno. Input: Dictionary containing the results to be updated or an empty dictionary the reset keyword was spe...
11,730
def metadata(self): if self._metadata is None: try: with open(self.paths.metadata()) as metadata_fd: self._metadata = json.load(metadata_fd) except IOError: self._metadata = {} return self._metadata
Retrieve the metadata info for this prefix Returns: dict: metadata info
11,731
def _assemble_with_columns(self, sql_str, columns, *args, **kwargs): qcols = [] for col in columns: if in col: wlist = col.split() qcols.append(sql.SQL().join([sql.Identifier(x) for x in wlist])) ...
Format a select statement with specific columns :sql_str: An SQL string template :columns: The columns to be selected and put into {0} :*args: Arguments to use as query parameters. :returns: Psycopg2 compiled query
11,732
def daemon_start(main, pidfile, daemon=True, workspace=None): logger.debug("start daemon application pidfile={pidfile} daemon={daemon} workspace={workspace}.".format(pidfile=pidfile, daemon=daemon, workspace=workspace)) new_pid = os.getpid() workspace = workspace or os.getcwd() os.chdir(workspace) ...
Start application in background mode if required and available. If not then in front mode.
11,733
def create_entity2user(enti_uid, user_id): record = TabEntity2User.select().where( (TabEntity2User.entity_id == enti_uid) & (TabEntity2User.user_id == user_id) ) if record.count() > 0: record = record.get() MEntity2User.count_increate(record.uid, rec...
create entity2user record in the database.
11,734
def _yield_exercises(self): for day in self.days: for dynamic_ex in day.dynamic_exercises: yield dynamic_ex for static_ex in day.static_exercises: yield static_ex
A helper function to reduce the number of nested loops. Yields ------- (dynamic_ex) or (static_ex) Yields the exercises in the program.
11,735
def link_with_parents(self, parent, c_selectors, c_rules): parent_found = None for p_selectors, p_rules in self.parts.items(): _p_selectors, _, _ = p_selectors.partition() _p_selectors = _p_selectors.split() new_selectors = set() found = False ...
Link with a parent for the current child rule. If parents found, returns a list of parent rules to the child
11,736
def match_member_id(self, member_conf, current_member_confs): if current_member_confs is None: return None for curr_mem_conf in current_member_confs: if is_same_address(member_conf[], curr_mem_conf[]): return curr_mem_conf[] return None
Attempts to find an id for member_conf where fom current members confs there exists a element. Returns the id of an element of current confs WHERE member_conf.host and element.host are EQUAL or map to same host
11,737
def _load_tsv_variables(layout, suffix, dataset=None, columns=None, prepend_type=False, scope=, **selectors): scanssessionsparticipantsageparticipants.ages get() method; can be used to constrain which data are loaded. Returns: A NodeIndex instance. scansrunsessionssessio...
Reads variables from scans.tsv, sessions.tsv, and participants.tsv. Args: layout (BIDSLayout): The BIDSLayout to use. suffix (str): The suffix of file to read from. Must be one of 'scans', 'sessions', or 'participants'. dataset (NodeIndex): A BIDS NodeIndex container. If None, a...
11,738
def get_field(name, data, default="object", document_object_field=None, is_document=False): if isinstance(data, AbstractField): return data data = keys_to_string(data) _type = data.get(, default) if _type == "string": return StringField(name=name, **data) elif _type == "binary":...
Return a valid Field by given data
11,739
def execute(self, task): try: return task.run() except Exception: if task.retries > 0: task.retries -= 1 task.to_retrying() if task.async: data = task.serialize() ...
Given a task instance, this runs it. This includes handling retries & re-raising exceptions. Ex:: task = Task(async=False, retries=5) task.to_call(add, 101, 35) finished_task = gator.execute(task) :param task_id: The identifier of the task to process ...
11,740
def auth_required(self): if self._auth: return self._auth, self return self.__parent__.auth_required()
If any ancestor required an authentication, this node needs it too.
11,741
def DeleteInstance(r, instance, dry_run=False): return r.request("delete", "/2/instances/%s" % instance, query={"dry-run": dry_run})
Deletes an instance. @type instance: str @param instance: the instance to delete @rtype: int @return: job id
11,742
def check_email_syntax (self, mail): if len(mail) > 256: self.set_result(_("Mail address `%(addr)s in mail address `%(addr)s.") % \ {"addr": mail}, valid=False, overwrite=False) return if not domain: self.set_result(_("...
Check email syntax. The relevant RFCs: - How to check names (memo): http://tools.ietf.org/html/rfc3696 - Email address syntax http://tools.ietf.org/html/rfc2822 - SMTP protocol http://tools.ietf.org/html/rfc5321#section-4.1.3 - IPv6 http://tools.ie...
11,743
def insort_right(a, x, lo=0, hi=None): if lo < 0: raise ValueError() if hi is None: hi = len(a) while lo < hi: mid = (lo+hi)//2 if x < a[mid]: hi = mid else: lo = mid+1 a.insert(lo, x)
Insert item x in list a, and keep it sorted assuming a is sorted. If x is already in a, insert it to the right of the rightmost x. Optional args lo (default 0) and hi (default len(a)) bound the slice of a to be searched.
11,744
def forms(self): forms = FormsDict() for name, item in self.POST.iterallitems(): if not hasattr(item, ): forms[name] = item return forms
Form values parsed from an `url-encoded` or `multipart/form-data` encoded POST or PUT request body. The result is retuned as a :class:`FormsDict`. All keys and values are strings. File uploads are stored separately in :attr:`files`.
11,745
def axis_bounds(self) -> Dict[str, Tuple[float, float]]: return {ax: (0, pos+0.5) for ax, pos in _HOME_POSITION.items() if ax not in }
The (minimum, maximum) bounds for each axis.
11,746
def fmt_duration(secs): return .join(fmt.human_duration(secs, 0, precision=2, short=True).strip().split())
Format a duration in seconds.
11,747
def login_required(request): "Lookup decorator to require the user to be authenticated." user = getattr(request, , None) if user is None or not user.is_authenticated: return HttpResponse(status=401)
Lookup decorator to require the user to be authenticated.
11,748
def loadResults(resultsFile): with open(resultsFile) as f: raw=f.read().split("\n") foldersByDay={} for line in raw: folder=line.split()[1]+"\\" line=[]+line.split()[2].split(", ") for day in line[1:]: if not day in foldersByDay: fol...
returns a dict of active folders with days as keys.
11,749
def _build(self, input_batch, is_training, test_local_stats=False): input_shape = input_batch.get_shape() if not self._data_format: if len(input_shape) == 2: self._data_format = "NC" elif len(input_shape) == 3: self._data_format = "NWC" ...
Connects the BatchNormV2 module into the graph. Args: input_batch: A Tensor of the same dimension as `len(data_format)`. is_training: A boolean to indicate if the module should be connected in training mode, meaning the moving averages are updated. Can be a Tensor. test_local_stats: A boo...
11,750
def get_proxy_parts(proxy): proxy_parts = {: None, : None, : None, : None, : None, } results = re.match(proxy_parts_pattern, proxy) if results: matched = results.groupdict() for key in pr...
Take a proxy url and break it up to its parts
11,751
def find_usage(self): logger.debug("Checking usage for service %s", self.service_name) self.connect() for lim in self.limits.values(): lim._reset_usage() self._find_usage_vpcs() subnet_to_az = self._find_usage_subnets() self._find_usage_ACLs() ...
Determine the current usage for each limit of this service, and update corresponding Limit via :py:meth:`~.AwsLimit._add_current_usage`.
11,752
def peukerdouglas(np, fel, streamSkeleton, workingdir=None, mpiexedir=None, exedir=None, log_file=None, runtime_file=None, hostfile=None): fname = TauDEM.func_name() return TauDEM.run(FileClass.get_executable_fullpath(fname, exedir), {: fel}, work...
Run peuker-douglas function
11,753
def process_needlist(app, doctree, fromdocname): env = app.builder.env for node in doctree.traverse(Needlist): if not app.config.needs_include_needs: for att in (, , , ): node[att] = [] node.re...
Replace all needlist nodes with a list of the collected needs. Augment each need with a backlink to the original location.
11,754
def generate_exercises_from_importstudioid(self, args, options): print() self.studioapi = StudioApi(token=args[]) channel_dict = self.studioapi.get_tree_for_studio_id(args[]) json.dump(channel_dict, open(, ), indent=4, ensure_ascii=False, sort_keys=True) soure_ids_seen ...
Create rows in Exercises.csv and ExerciseQuestions.csv from a Studio channel, specified based on a studio_id (e.g. studio_id of main_tree for some channel)'
11,755
def query_sequence_length(self): if self.entries.seq: return len(self.entries.seq) if not self.entries.cigar: raise ValueError() return sum([x[0] for x in self.cigar_array if re.match(,x[1])])
does not include hard clipped
11,756
def _iparam_objectname(objectname, arg_name): if isinstance(objectname, (CIMClassName, CIMInstanceName)): objectname = objectname.copy() objectname.host = None objectname.namespace = None elif isinstance(objectname, six.string_types): objectname ...
Convert an object name (= class or instance name) specified in an operation method into a CIM object that can be passed to imethodcall().
11,757
def loess_inline(h,x,cut,nan=True): n=np.size(h) if n == 1 : lf = h[0] else : pass l_c=cut/2.0 w=np.zeros(n) lf = np.repeat(np.NaN,n) flag = ~np.isnan(h) fcnt = flag.sum() fnt = np.arange(n).compress(flag) ...
#This is a raw, inline version of the loess filtering function. Runs much more slowlier.
11,758
def example4(): transform_matrix = create_transformation_matrix() result = tl.prepro.affine_transform_cv2(image, transform_matrix) coords = [[(50, 100), (100, 100), (100, 50), (200, 200)], [(250, 50), (200, 50), (200, 100)]] coords_result = tl.prepro.affine_transform_keypoints(coords, transf...
Example 4: Transforming coordinates using affine matrix.
11,759
def assertDateTimesLagEqual(self, sequence, lag, msg=None): == if not isinstance(sequence, collections.Iterable): raise TypeError() if not isinstance(lag, timedelta): raise TypeError() if isinstance(max(sequence), datetime): target =...
Fail unless max element in ``sequence`` is separated from the present by ``lag`` as determined by the '==' operator. If the max element is a datetime, "present" is defined as ``datetime.now()``; if the max element is a date, "present" is defined as ``date.today()``. This is equ...
11,760
def main(argv=None): args = parse_arguments(sys.argv if argv is None else argv) temp_dir = os.path.join(args.output, ) if args.cloud: pipeline_name = else: pipeline_name = os.environ[]= options = { : args.job_name, : temp_dir, : args.project_id, : os.p...
Run Preprocessing as a Dataflow.
11,761
def load(self, path): fieldnames = [, ] with open(path, , encoding=, newline=) as fh: reader = csv.DictReader(fh, delimiter=, fieldnames=fieldnames, skipinitialspace=True) for row in reader: work, label = row[], row[] ...
Loads the data from `path` into the catalogue. :param path: path to catalogue file :type path: `str`
11,762
def pluginSetting(name, namespace=None, typ=None): def _find_in_cache(name, key): for setting in _settings[namespace]: if setting["name"] == name: return setting[key] return None def _type_map(t): if t == BOOL: return bool el...
Returns the value of a plugin setting. :param name: the name of the setting. It is not the full path, but just the last name of it :param namespace: The namespace. If not passed or None, the namespace will be inferred from the caller method. Normally, this should not be passed, since it suffices to let thi...
11,763
def watch_statuses(self, observer, batch_ids): with self._lock: statuses = self.get_statuses(batch_ids) if self._has_no_pendings(statuses): observer.notify_batches_finished(statuses) else: self._observers[observer] = statuses
Allows a component to register to be notified when a set of batches is no longer PENDING. Expects to be able to call the "notify_batches_finished" method on the registered component, sending the statuses of the batches. Args: observer (object): Must implement "notify_batches...
11,764
def _band_calculations(self, rsr, flux, scale, **options): from scipy.interpolate import InterpolatedUnivariateSpline if in options: detector = options[] else: detector = 1 if self.wavespace == : if in rsr: wvl = r...
Derive the inband solar flux or inband solar irradiance for a given instrument relative spectral response valid for an earth-sun distance of one AU. rsr: Relative Spectral Response (one detector only) Dictionary with two members 'wavelength' and 'response' options: detec...
11,765
def render(request, template_name, context=None, content_type=None, status=None, using=None, logs=None): if logs: obj_logger = ObjectLogger() if not isinstance(logs, list): logs = [logs, ] for log in logs: log = obj_logger.log_response( log, ...
Wrapper around Django render method. Can take one or a list of logs and logs the response. No overhead if no logs are passed.
11,766
def _parse_led(self, keypad, component_xml): component_num = int(component_xml.get()) led_num = component_num - 80 led = Led(self._lutron, keypad, name=( % led_num), led_num=led_num, component_num=component_num) return led
Parses an LED device that part of a keypad.
11,767
def do_wait(coro: Callable) -> Any: event_loop = None try: event_loop = asyncio.get_event_loop() except RuntimeError: event_loop = asyncio.new_event_loop() asyncio.set_event_loop(event_loop) return event_loop.run_until_complete(coro)
Perform aynchronous operation; await then return the result. :param coro: coroutine to await :return: coroutine result
11,768
def make_all_uppercase( lst: Union[list, tuple, str, set] ) -> Union[list, tuple, str, set]: if not isinstance(lst, (list, tuple, str, set)): raise TypeError() if isinstance(lst, str): return lst.upper() arr = list(lst) ...
Make all characters uppercase. It supports characters in a (mix of) list, tuple, set or string. The return value is of the same type of the input value.
11,769
def namedTempFileReader(self) -> NamedTempFileReader: directory = self._directory() assert isinstance(directory, Directory), ( "Expected Directory, receieved %s" % directory) return NamedTempFileReader(directory, self)
Named Temporary File Reader This provides an object compatible with NamedTemporaryFile, used for reading this files contents. This will still delete after the object falls out of scope. This solves the problem on windows where a NamedTemporaryFile can not be read while it's being writt...
11,770
def check_data_complete(data, parameter_columns): param_edges = [p[1:] for p in parameter_columns if isinstance(p, (Tuple, List))] for p in param_edges: other_params = [p_ed[0] for p_ed in param_edges if p_ed != p] if other_params: sub_tables = data.groupby(list(other_p...
For any parameters specified with edges, make sure edges don't overlap and don't have any gaps. Assumes that edges are specified with ends and starts overlapping (but one exclusive and the other inclusive) so can check that end of previous == start of current. If multiple parameters, make sure all ...
11,771
def merge(d1, d2): d1, d2 = deepcopy(d1), deepcopy(d2) if d1 == {} or type(d1) is not dict: return _merge_fix(d2) for key in d2.keys(): if key[0] == : data = d2[key] key = key[1:] if key in d1: if type(d1[key]) is dict and ty...
This method does cool stuff like append and replace for dicts d1 = { "steve": 10, "gary": 4 } d2 = { "&steve": 11, "-gary": null } result = { "steve": [10, 11] }
11,772
def dump_by_server(self, hosts): dump_by_endpoint = {} for endpoint in self._to_endpoints(hosts): try: out = self.cmd([endpoint], "dump") except self.CmdFailed as ex: out = "" dump_by_endpoint[endpoint] = out return d...
Returns the output of dump for each server. :param hosts: comma separated lists of members of the ZK ensemble. :returns: A dictionary of ((server_ip, port), ClientInfo).
11,773
def translate_aliases(kwargs, aliases): result = {} for given_key, value in kwargs.items(): canonical_key = aliases.get(given_key, given_key) if canonical_key in result: key_names = .join("{}".format(k) for k in kwargs if aliases.g...
Given a dict of keyword arguments and a dict mapping aliases to their canonical values, canonicalize the keys in the kwargs dict. :return: A dict continaing all the values in kwargs referenced by their canonical key. :raises: `AliasException`, if a canonical key is defined more than once.
11,774
def get_clean_factor(factor, forward_returns, groupby=None, binning_by_group=False, quantiles=5, bins=None, groupby_labels=None, max_loss=0.35, zero_awa...
Formats the factor data, forward return data, and group mappings into a DataFrame that contains aligned MultiIndex indices of timestamp and asset. The returned data will be formatted to be suitable for Alphalens functions. It is safe to skip a call to this function and still make use of Alphalens funct...
11,775
def cvtToBlocks(rh, diskSize): rh.printSysLog("Enter generalUtils.cvtToBlocks") blocks = 0 results = {: 0, : 0, : 0, : 0} blocks = diskSize.strip().upper() lastChar = blocks[-1] if lastChar == or lastChar == : byteSize = blocks[:-1] if byteSize == : ...
Convert a disk storage value to a number of blocks. Input: Request Handle Size of disk in bytes Output: Results structure: overallRC - Overall return code for the function: 0 - Everything went ok 4 - Input validation error ...
11,776
def post(self, request, pzone_pk): pzone = None try: pzone = PZone.objects.get(pk=pzone_pk) except PZone.DoesNotExist: raise Http404("Cannot find given pzone.") json_obj = [] http_status = 500 json_op = json.loads(request.body....
Add a new operation to the given pzone, return json of the new operation.
11,777
def _create(self, format, args): constructor = self._LEAF_CONSTRUCTORS.get(format[0]) if constructor: if args is not None: if not args: raise TypeError() v = constructor(args[0]) return (v, format[1:], args...
Create a GVariant object from given format and argument list. This method recursively calls itself for complex structures (arrays, dictionaries, boxed). Return a tuple (variant, rest_format, rest_args) with the generated GVariant, the remainder of the format string, and the remainder o...
11,778
def add_curie(self, name, href): self.draft.set_curie(self, name, href) return self
Adds a CURIE definition. A CURIE link with the given ``name`` and ``href`` is added to the document. This method returns self, allowing it to be chained with additional method calls.
11,779
def update_metric(self, eval_metric, labels, pre_sliced=False): if self._label_shapes is None: return if pre_sliced: raise RuntimeError("PythonModule does not support presliced labels") eval_metric.update(labels, self.get_outp...
Evaluates and accumulates evaluation metric on outputs of the last forward computation. Subclass should override this method if needed. Parameters ---------- eval_metric : EvalMetric labels : list of NDArray Typically ``data_batch.label``.
11,780
def search_agents(self, start=0, limit=100, filter={}, **kwargs): genericmy Agent request_data = {: start, : limit, : filter} request_data.update(kwargs) return self._call_rest_api(, , data=request_data, error=)
search_agents(self, start=0, limit=100, filter={}, **kwargs) Search agents :Parameters: * *start* (`int`) -- start index to retrieve from. Default is 0 * *limit* (`int`) -- maximum number of entities to retrieve. Default is 100 * *filter* (`object`) -- free text search pattern ...
11,781
def from_binary(self, d): p = MsgEphemerisGPSDepF._parser.parse(d) for n in self.__class__.__slots__: setattr(self, n, getattr(p, n))
Given a binary payload d, update the appropriate payload fields of the message.
11,782
def build_fptree(self, transactions, root_value, root_count, frequent, headers): root = FPNode(root_value, root_count, None) for transaction in transactions: sorted_items = [x for x in transaction if x in frequent] sorted_items.sort(key=lambda x: fr...
Build the FP tree and return the root node.
11,783
async def set_heater_temp(self, device_id, set_temp): payload = {"homeType": 0, "timeZoneNum": "+02:00", "deviceId": device_id, "value": int(set_temp), "key": "holidayTemp"} await self.request("changeDeviceInfo", payloa...
Set heater temp.
11,784
def _fill_function(*args): if len(args) == 2: func = args[0] state = args[1] elif len(args) == 5: func = args[0] keys = [, , , ] state = dict(zip(keys, args[1:])) elif len(args) == 6: func = args[0] keys = [, , ...
Fills in the rest of function data into the skeleton function object The skeleton itself is create by _make_skel_func().
11,785
def absent(name=None, start_addr=None, end_addr=None, data=None, **api_opts): vlan10 ret = {: name, : False, : , : {}} if not data: data = {} if not in data: data.update({: name}) if not in data: data.update({: start_addr}) if not in data: data.update({: end_a...
Ensure the range is removed Supplying the end of the range is optional. State example: .. code-block:: yaml infoblox_range.absent: - name: 'vlan10' infoblox_range.absent: - name: - start_addr: 127.0.1.20
11,786
def advisory_lock(dax, key, lock_mode=LockMode.wait, xact=False): if lock_mode == LockMode.wait: obtain_lock(dax, key, lock_mode, xact) else: got_lock = obtain_lock(dax, key, lock_mode, xact) if not got_lock: if lock_mode == LockMode.error: raise Exception("Unable to obtain advisory loc...
A context manager for obtaining a lock, executing code, and then releasing the lock. A boolean value is passed to the block indicating whether or not the lock was obtained. :dax: a DataAccess instance :key: either a big int or a 2-tuple of integers :lock_mode: a member of the LockMode enum. Determines how...
11,787
def _get_samples(n, sim, inc_warmup=True): return pystan._misc.get_samples(n, sim, inc_warmup)
Get chains for `n`th parameter. Parameters ---------- n : int sim : dict A dictionary tied to a StanFit4Model instance. Returns ------- chains : list of array Each chain is an element in the list.
11,788
def presign_v4(method, url, access_key, secret_key, session_token=None, region=None, headers=None, expires=None, response_headers=None, request_date=None): if not access_key or not secret_key: raise InvalidArgumentError() if region is None: region = ...
Calculates signature version '4' for regular presigned URLs. :param method: Method to be presigned examples 'PUT', 'GET'. :param url: URL to be presigned. :param access_key: Access key id for your AWS s3 account. :param secret_key: Secret access key for your AWS s3 account. :param session_token: Se...
11,789
def is_cgi(self): collapsed_path = _url_collapse_path(self.path) dir_sep = collapsed_path.find(, 1) head, tail = collapsed_path[:dir_sep], collapsed_path[dir_sep+1:] if head in self.cgi_directories: self.cgi_info = head, tail return True return Fa...
Test whether self.path corresponds to a CGI script. Returns True and updates the cgi_info attribute to the tuple (dir, rest) if self.path requires running a CGI script. Returns False otherwise. If any exception is raised, the caller should assume that self.path was rejected as ...
11,790
def peek(self, eof_token=False): if len(self.queue) == 0: self._refill(eof_token) return self.queue[-1]
Same as :meth:`next`, except the token is not dequeued.
11,791
def get_payments_of_credit_note_per_page(self, credit_note_id, per_page=1000, page=1): return self._get_resource_per_page( resource=CREDIT_NOTE_PAYMENTS, per_page=per_page, page=page, params={: credit_note_id}, )
Get payments of credit note per page :param credit_note_id: the credit note id :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :return: list
11,792
def _von_mises_cdf_normal(x, concentration, dtype): def cdf_func(concentration): z = ((np.sqrt(2. / np.pi) / tf.math.bessel_i0e(concentration)) * tf.sin(.5 * x)) z2 = z ** 2 z3 = z2 * z z4 = z2 ** 2 c = 24. * concentration c1 = 56. xi = z - z3 / ((c - 2. ...
Computes the von Mises CDF and its derivative via Normal approximation.
11,793
def open_document(self, path, encoding=None, replace_tabs_by_spaces=True, clean_trailing_whitespaces=True, safe_save=True, restore_cursor_position=True, preferred_eol=0, autodetect_eol=True, show_whitespaces=False, **kwargs): original_pa...
Opens a document. :param path: Path of the document to open :param encoding: The encoding to use to open the file. Default is locale.getpreferredencoding(). :param replace_tabs_by_spaces: Enable/Disable replace tabs by spaces. Default is true. :param clean_traili...
11,794
def ParseFileObject(self, parser_mediator, file_object): regf_file = pyregf.file() try: regf_file.open_file_object(file_object) except IOError: return root_key = regf_file.get_root_key() if root_key is None: regf_file.close() return root_file_key = r...
Parses an Amcache.hve file for events. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): file-like object.
11,795
def glob (dirs, patterns): result = [] dirs = to_seq (dirs) patterns = to_seq (patterns) splitdirs = [] for dir in dirs: splitdirs += dir.split (os.pathsep) for dir in splitdirs: for pattern in patterns: p = os....
Returns the list of files matching the given pattern in the specified directory. Both directories and patterns are supplied as portable paths. Each pattern should be non-absolute path, and can't contain "." or ".." elements. Each slash separated element of pattern can contain the following special char...
11,796
def set_data(self, data): self.shape = data.shape if self._data is None: assert self._deferred_init, \ "Parameter has not been initialized"%self.name self._deferred_init = self._deferred_init[:3] + (data,) return if self._t...
Sets this parameter's value on all contexts.
11,797
async def is_owner(self, user): if self.owner_id is None: app = await self.application_info() self.owner_id = owner_id = app.owner.id return user.id == owner_id return user.id == self.owner_id
Checks if a :class:`~discord.User` or :class:`~discord.Member` is the owner of this bot. If an :attr:`owner_id` is not set, it is fetched automatically through the use of :meth:`~.Bot.application_info`. Parameters ----------- user: :class:`.abc.User` The use...
11,798
def get_free_gpus(max_procs=0): logger = logging.getLogger(__name__) try: py3nvml.nvmlInit() except: str_ = warnings.warn(str_, RuntimeWarning) logger.warn(str_) return [] num_gpus = py3nvml.nvmlDeviceGetCount() gpu_free = [False]*num_gpus for ...
Checks the number of processes running on your GPUs. Parameters ---------- max_procs : int Maximum number of procs allowed to run on a gpu for it to be considered 'available' Returns ------- availabilities : list(bool) List of length N for an N-gpu system. The nth value...
11,799
def get_dataset_files(in_path): audio_files = [] for ext in ds_config.audio_exts: audio_files += glob.glob( os.path.join(in_path, ds_config.audio_dir, "*" + ext)) utils.ensure_dir(os.path.join(in_path, ds_config.features_dir)) utils.ensure_dir(os.path.join(in_path, ds...
Gets the files of the given dataset.