Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
14,700
def safe_dump(data, stream=None, **kwargs): if not in kwargs: kwargs[] = True return yaml.dump(data, stream, Dumper=SafeOrderedDumper, **kwargs)
Use a custom dumper to ensure that defaultdict and OrderedDict are represented properly. Ensure that unicode strings are encoded unless explicitly told not to.
14,701
def load(steps, reload=False): if reload: _STEP_CACHE.clear() if callable(steps): steps = steps() if not isinstance(steps, collections.Iterable): return load([steps])[0] loaded = [] for s in steps: digest = s._digest if digest in _STEP_CACHE: ...
safely load steps in place, excluding those that fail Args: steps: the steps to load
14,702
def resfinderreporter(self): resistance_classes = ResistanceNotes.classes(self.targetpath) workbook = xlsxwriter.Workbook(os.path.join(self.reportpath, .format(self.analysistype))) worksheet = workbook.add_worksheet() bold = workbook....
Custom reports for ResFinder analyses. These reports link the gene(s) found to their resistance phenotypes
14,703
def proxyval(self, visited): if self.as_address() in visited: return ProxyAlreadyVisited() visited.add(self.as_address()) pyop_attr_dict = self.get_attr_dict() if pyop_attr_dict: attr_dict = pyop_attr_dict.proxyval(visited) else: ...
Support for new-style classes. Currently we just locate the dictionary using a transliteration to python of _PyObject_GetDictPtr, ignoring descriptors
14,704
def get_gatk_annotations(config, include_depth=True, include_baseqranksum=True, gatk_input=True): broad_runner = broad.runner_from_config(config) anns = ["MappingQualityRankSumTest", "MappingQualityZero", "QualByDepth", "ReadPosRankSumTest", "RMSMappingQuality"] if ...
Retrieve annotations to use for GATK VariantAnnotator. If include_depth is false, we'll skip annotating DP. Since GATK downsamples this will undercount on high depth sequencing and the standard outputs from the original callers may be preferable. BaseQRankSum can cause issues with some MuTect2 and oth...
14,705
def from_client_secrets_file(cls, client_secrets_file, scopes, **kwargs): with open(client_secrets_file, ) as json_file: client_config = json.load(json_file) return cls.from_client_config(client_config, scopes=scopes, **kwargs)
Creates a :class:`Flow` instance from a Google client secrets file. Args: client_secrets_file (str): The path to the client secrets .json file. scopes (Sequence[str]): The list of scopes to request during the flow. kwargs: Any additional param...
14,706
def xspec_cosmo(H0=None,q0=None,lambda_0=None): current_settings = _xspec.get_xscosmo() if (H0 is None) and (q0 is None) and (lambda_0 is None): return current_settings else: user_inputs = [H0, q0, lambda_0] for i, current_setting in enumerate(current_settings):...
Define the Cosmology in use within the XSpec models. See Xspec manual for help: http://heasarc.nasa.gov/xanadu/xspec/manual/XScosmo.html All parameters can be modified or just a single parameter :param H0: the hubble constant :param q0: :param lambda_0: :return: Either none or the current...
14,707
def refresh_token(self, refresh_token): url = data = {: self.client_id, : , : refresh_token} r = requests.post(url, data=data) check_error(r) return r.json()
return origin json
14,708
def readdir(path): * path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError() if not os.path.isdir(path): raise SaltInvocationError() dirents = [, ] dirents.extend(os.listdir(path)) return dirents
.. versionadded:: 2014.1.0 Return a list containing the contents of a directory CLI Example: .. code-block:: bash salt '*' file.readdir /path/to/dir/
14,709
def process(obj): merged = merge(obj) if obj.get(): print .format(obj[], len(merged)/1024.0) _save(obj[], merged) else: print .format(len(merged)/1024.0) if obj.get(): jsMin(merged, obj[]) if obj.get(): cssMin(merged, obj[])
Process each block of the merger object.
14,710
def connection_lost(self, exc): if exc: self.log.exception() else: self.log.info() self._closed.set()
Stop when connection is lost.
14,711
def print_status(self, indent="", recurse=False): print ("%s%30s : %15s : %20s" % (indent, "Linkname", "Link Status", "Jobs Status")) for link in self._links.values(): if hasattr(link, ): status_vect = link.check_status( stream=sys....
Print a summary of the job status for each `Link` in this `Chain`
14,712
def revoke_access(src, dst=, port=None, proto=None): return modify_access(src, dst=dst, port=port, proto=proto, action=)
Revoke access to an address or subnet :param src: address (e.g. 192.168.1.234) or subnet (e.g. 192.168.1.0/24). :param dst: destiny of the connection, if the machine has multiple IPs and connections to only one of those have to accepted this is the field has to b...
14,713
def cut(list_, index=0): if isinstance(index, int): cut_ = lambda x: x[index] else: cut_ = lambda x: getattr(x, index) return list(map(cut_, list_))
Cut a list by index or arg
14,714
async def _build_rr_state_json(self, rr_id: str, timestamp: int) -> (str, int): LOGGER.debug(, rr_id, timestamp) if not ok_rev_reg_id(rr_id): LOGGER.debug(, rr_id) raise BadIdentifier(.format(rr_id)) rr_json = None ledger_timestamp = None get_...
Build rev reg state json at a given requested timestamp. Return rev reg state json and its transaction time on the distributed ledger, with upper bound at input timestamp of interest. Raise AbsentRevReg if no revocation registry exists on input rev reg id, or BadRevStateTime if request...
14,715
def Eps(value=None, loc=None): @llrule(loc, lambda parser: []) def rule(parser): return value return rule
A rule that accepts no tokens (epsilon) and returns ``value``.
14,716
def display(result, stream): if result is None: return elif isinstance(result, basestring): pass elif isinstance(result, collections.Mapping): result = u.join(u % (k, v) for k, v in result.iteritems() if v is not None) elif isinstance(result, coll...
Intelligently print the result (or pass if result is None). :param result: :return: None
14,717
def _update_pop(self, pop_size): valid_particles = [] invalid_particles = [] for part in self.population: if any(x > 1 or x < -1 for x in part): invalid_particles.append(part) else: valid_particles.append(part) self._model_...
Assigns fitnesses to particles that are within bounds.
14,718
def start(self): connect_thread = threading.Thread(target=self._connect) connect_thread.start()
Start the connection to a transport.
14,719
def nguHanhNapAm(diaChi, thienCan, xuatBanMenh=False): banMenh = { "K1": "HẢI TRUNG KIM", "T1": "GIÁNG HẠ THỦY", "H1": "TÍCH LỊCH HỎA", "O1": "BÍCH THƯỢNG THỔ", "M1": "TANG ÐỐ MỘC", "T2": "ÐẠI KHÊ THỦY", "H2": "LƯ TRUNG HỎA", "O2": "THÀNH ÐẦU THỔ"...
Sử dụng Ngũ Hành nạp âm để tính Hành của năm. Args: diaChi (integer): Số thứ tự của địa chi (Tý=1, Sửu=2,...) thienCan (integer): Số thứ tự của thiên can (Giáp=1, Ất=2,...) Returns: Trả về chữ viết tắt Hành của năm (K, T, H, O, M)
14,720
def process_internal_commands(self): with self._main_lock: self.check_output_redirect() program_threads_alive = {} all_threads = threadingEnumerate() program_threads_dead = [] with self._lock_running_thread_ids: reset_cache = ...
This function processes internal commands
14,721
def decode(token, key, algorithms=None, options=None, audience=None, issuer=None, subject=None, access_token=None): defaults = { : True, : True, : True, : True, : True, : True, : True, : True, : True, : False, :...
Verifies a JWT string's signature and validates reserved claims. Args: token (str): A signed JWS to be verified. key (str or dict): A key to attempt to verify the payload with. Can be individual JWK or JWK set. algorithms (str or list): Valid algorithms that should be used to ve...
14,722
def same_page(c): return all( [ _to_span(c[i]).sentence.is_visual() and bbox_from_span(_to_span(c[i])).page == bbox_from_span(_to_span(c[0])).page for i in range(len(c)) ] )
Return true if all the components of c are on the same page of the document. Page numbers are based on the PDF rendering of the document. If a PDF file is provided, it is used. Otherwise, if only a HTML/XML document is provided, a PDF is created and then used to determine the page number of a Mention. ...
14,723
def add_component(self, entity: int, component_instance: Any) -> None: component_type = type(component_instance) if component_type not in self._components: self._components[component_type] = set() self._components[component_type].add(entity) if entity not in self....
Add a new Component instance to an Entity. Add a Component instance to an Entiy. If a Component of the same type is already assigned to the Entity, it will be replaced. :param entity: The Entity to associate the Component with. :param component_instance: A Component instance.
14,724
def fetchone(table, cols="*", where=(), group="", order=(), limit=(), **kwargs): return select(table, cols, where, group, order, limit, **kwargs).fetchone()
Convenience wrapper for database SELECT and fetch one.
14,725
def policy_map_clss_set_set_dscp_dscp(self, **kwargs): config = ET.Element("config") policy_map = ET.SubElement(config, "policy-map", xmlns="urn:brocade.com:mgmt:brocade-policer") po_name_key = ET.SubElement(policy_map, "po-name") po_name_key.text = kwargs.pop() clss = E...
Auto Generated Code
14,726
def _find_lang(langdict, lang, script, region): full_locale = _full_locale(lang, script, region) if (full_locale in _LOCALE_NORMALIZATION_MAP and _LOCALE_NORMALIZATION_MAP[full_locale] in langdict): return langdict[_LOCALE_NORMALIZATION_MAP[full_locale]] if full_locale in lang...
Return the entry in the dictionary for the given language information.
14,727
def get_node_by_path(self, path): if path==".": return self elif path.lstrip().startswith((".", "./")) or not isinstance(path, str): logger.warning("%s.get_node_by_path: arg «path»=«%s», not correctly specified." % (self.__class__.__name__, path)) return None...
Get a node from a node path. Warning: use of this method assumes that sibling nodes have unique names, if this is not assured the `get_node_by_coord` method can be used instead. | Example with absolute node path: | `node.get_node_by_path('/root.name/child.name/gchild.name')` ...
14,728
def enable_inheritance(path, objectType, clear=False): minion-id dc = daclConstants() objectType = dc.getObjectTypeBit(objectType) path = dc.processPath(path, objectType) return _set_dacl_inheritance(path, objectType, True, None, clear)
enable/disable inheritance on an object Args: path: The path to the object objectType: The type of object (FILE, DIRECTORY, REGISTRY) clear: True will remove non-Inherited ACEs from the ACL Returns (dict): A dictionary containing the results CLI Example: .. code-block:: bash ...
14,729
def print_infos(results): print( % results.total_transactions) print( % results.total_timers) print( % results.total_errors) print( % results.start_datetime) print( % results.finish_datetime)
Print informations in standard output :param ReportResults results: the report result containing all compiled informations
14,730
def InitAgeCheck(self): self.panel = wx.Panel(self, style=wx.SIMPLE_BORDER) text = label = wx.StaticText(self.panel, label=text) self.items = self.er_magic_data.data_lists[self.er_magic_data.age_type][0] self.grid_builder = grid_frame2.GridBuilder(self.er_magic_data,...
make an interactive grid in which users can edit ages
14,731
def select_serial_number_row(self, serial_number): sheet = self.table col = self.db_sheet_cols.id rows = sheet.loc[:, col] == serial_number return sheet.loc[rows, :]
Select row for identification number serial_number Args: serial_number: serial number Returns: pandas.DataFrame
14,732
def find_library_full_path(name): from ctypes.util import find_library if os.name == "posix" and sys.platform == "darwin": return find_library(name) def _use_proc_maps(name): procmap = os.path.join(, str(os.getpid()), ) if not os.path.isfile(procmap): ...
Similar to `from ctypes.util import find_library`, but try to return full path if possible.
14,733
def load_include_path(paths): for path in paths: if not os.path.isdir(path): continue if path not in sys.path: sys.path.insert(1, path) for f in os.listdir(path): fpath = os.path.join(path, f) ...
Scan for and add paths to the include path
14,734
def _wait_for_disk_threads(self, terminate): if terminate: self._upload_terminate = terminate for thr in self._disk_threads: thr.join()
Wait for disk threads :param Uploader self: this :param bool terminate: terminate threads
14,735
def _ctype_key_value(keys, vals): if isinstance(keys, (tuple, list)): assert(len(keys) == len(vals)) c_keys = [] c_vals = [] use_str_keys = None for key, val in zip(keys, vals): c_key_i, c_val_i, str_keys_i = _ctype_key_value(key, val) c_keys += c...
Returns ctype arrays for the key-value args, and the whether string keys are used. For internal use only.
14,736
def submitter(self, f): f = self._wrap_coro_function_with_sem(f) @wraps(f) def wrapped(*args, **kwargs): return self.submit(f(*args, **kwargs)) return wrapped
Decorator to submit a coro-function as NewTask to self.loop with sem control. Use default_callback frequency of loop.
14,737
def calculate_size(name, entry_processor): data_size = 0 data_size += calculate_size_str(name) data_size += calculate_size_data(entry_processor) return data_size
Calculates the request payload size
14,738
def get_relaxation(self, A_configuration, B_configuration, I): coefficients = collinsgisin_to_faacets(I) M, ncIndices = get_faacets_moment_matrix(A_configuration, B_configuration, coefficients) self.n_vars = M.max() - 1 bs = len(M...
Get the sparse SDP relaxation of a Bell inequality. :param A_configuration: The definition of measurements of Alice. :type A_configuration: list of list of int. :param B_configuration: The definition of measurements of Bob. :type B_configuration: list of list of int. :param I: T...
14,739
def from_veto_def(cls, veto): name = % (veto.ifo, veto.name) try: name += % int(veto.version) except TypeError: pass if veto.end_time == 0: veto.end_time = +inf known = Segment(veto.start_time, veto.end_time) pad = (veto.star...
Define a `DataQualityFlag` from a `VetoDef` Parameters ---------- veto : :class:`~ligo.lw.lsctables.VetoDef` veto definition to convert from
14,740
def verify(self, **kwargs): super(MetadataStatement, self).verify(**kwargs) if "signing_keys" in self: if in self: raise VerificationError( ) else: kj = KeyJar() tr...
Verifies that an instance of this class adheres to the given restrictions. :param kwargs: A set of keyword arguments :return: True if it verifies OK otherwise False.
14,741
def _add_tag_manifest_file(zip_file, dir_name, tag_info_list): _add_tag_file( zip_file, dir_name, tag_info_list, _gen_tag_manifest_file_tup(tag_info_list) )
Generate the tag manifest file and add it to the zip.
14,742
def prepare_all_data(data_dir, block_pct_tokens_thresh=0.1): gs_blocks_dir = os.path.join(data_dir, GOLD_STANDARD_BLOCKS_DIRNAME) gs_blocks_filenames = get_filenames( gs_blocks_dir, full_path=False, match_regex=re.escape(GOLD_STANDARD_BLOCKS_EXT)) gs_blocks_fileroots = ( re.search(r + r...
Prepare data for all HTML + gold standard blocks examples in ``data_dir``. Args: data_dir (str) block_pct_tokens_thresh (float): must be in [0.0, 1.0] Returns: List[Tuple[str, List[float, int, List[str]], List[float, int, List[str]]]] See Also: :func:`prepare_data`
14,743
def register(self, perm_func=None, model=None, allow_staff=None, allow_superuser=None, allow_anonymous=None, unauthenticated_handler=None, request_types=None, name=None, replace=False, _return_entry=False): allow_staff = _default(allow_staff, self._allow_staff) ...
Register permission function & return the original function. This is typically used as a decorator:: permissions = PermissionsRegistry() @permissions.register def can_do_something(user): ... For internal use only: you can pass ``_return_entry=True``...
14,744
def memoized_ignoreargs(func): def wrapper(*args, **kwargs): if func not in _MEMOIZED_NOARGS: res = func(*args, **kwargs) _MEMOIZED_NOARGS[func] = res return res return _MEMOIZED_NOARGS[func] return wrapper
A decorator. It performs memoization ignoring the arguments used to call the function.
14,745
def calc_rate_susceptibility(self, rate_std=None, params=None): params = params or {} if rate_std is None: if not (self.clock_model[] and in self.clock_model): self.logger("ClockTree.calc_rate_susceptibility: need valid standard deviation of the clock rate to estima...
return the time tree estimation of evolutionary rates +/- one standard deviation form the ML estimate. Returns ------- TreeTime.return_code : str success or failure
14,746
def add_subsegment(self, subsegment): super(Segment, self).add_subsegment(subsegment) self.increment()
Add input subsegment as a child subsegment and increment reference counter and total subsegments counter.
14,747
def is_in_plane(self, pp, dist_tolerance): return np.abs(np.dot(self.normal_vector, pp) + self._coefficients[3]) <= dist_tolerance
Determines if point pp is in the plane within the tolerance dist_tolerance :param pp: point to be tested :param dist_tolerance: tolerance on the distance to the plane within which point pp is considered in the plane :return: True if pp is in the plane, False otherwise
14,748
def _handle_get_application_request(self, app_id, semver, key, logical_id): get_application = (lambda app_id, semver: self._sar_client.get_application( ApplicationId=self._sanitize_sar_str_param(app_id), SemanticVersion=self._sanitiz...
Method that handles the get_application API call to the serverless application repo This method puts something in the `_applications` dictionary because the plugin expects something there in a later event. :param string app_id: ApplicationId :param string semver: SemanticVersion ...
14,749
def remove_pickle_problems(obj): if hasattr(obj, "doc_loader"): obj.doc_loader = None if hasattr(obj, "embedded_tool"): obj.embedded_tool = remove_pickle_problems(obj.embedded_tool) if hasattr(obj, "steps"): obj.steps = [remove_pickle_problems(s) for s in obj.steps] return o...
doc_loader does not pickle correctly, causing Toil errors, remove from objects.
14,750
def recv_message(self, debug=False): if debug: packet = self.sock.recv(1024) hexdump(packet) packet_length_data = self.sock.recv(4) if len(packet_length_data) < 4: raise Exception("Nothing in the socket!") packet_length = struct.unpack("...
Reading socket and receiving message from server. Check the CRC32.
14,751
def inverse_kinematics( self, target_position_right, target_orientation_right, target_position_left, target_orientation_left, rest_poses, ): ndof = 48 ik_solution = list( p.calculateInverseKinematics( self.ik_robo...
Helper function to do inverse kinematics for a given target position and orientation in the PyBullet world frame. Args: target_position_{right, left}: A tuple, list, or numpy array of size 3 for position. target_orientation_{right, left}: A tuple, list, or numpy array of size 4 ...
14,752
def open(self): if self.conn is not None: self.close() self.conn = sqlite3.connect(self.filename) self.cursor = self.conn.cursor() c = self.cursor c.execute() if (u,) in c: c.execute() if self.verbose: print(...
Open a connection to the database. If a connection appears to be open already, transactions are committed and it is closed before proceeding. After establishing the connection, the searchIndex table is prepared (and dropped if it already exists).
14,753
def getValidCertifications(self): certs = [] today = date.today() for c in self.getCertifications(): validfrom = c.getValidFrom() if c else None validto = c.getValidTo() if validfrom else None if not validfrom or not validto: continue ...
Returns the certifications fully valid
14,754
def choice_input(options=[], prompt=, showopts=True, qopt=False): choice = None if showopts: prompt = prompt + + str(options) if qopt: prompt = prompt + while not choice: try: choice = string_input(prompt + ) except SyntaxError: ...
Get input from a list of choices (q to quit)
14,755
def vectorizable_features(fcs): is_mapping = lambda obj: isinstance(obj, collections.Mapping) return sorted(set([name for fc in fcs for name in fc if is_mapping(fc[name])]))
Discovers the ordered set of vectorizable features in ``fcs``. Returns a list of feature names, sorted lexicographically. Feature names are only included if the corresponding features are vectorizable (i.e., they are an instance of :class:`collections.Mapping`).
14,756
def get_remote_url(path, remote="origin"): path = get_path(path) cmd = ["config", "--get", "remote.%s.url" % remote] return __run_git(cmd, path)[0]
Run git config --get remote.<remote>.url in path. :param path: Path where git is to be run :param remote: Remote name :return: str or None
14,757
def visit_Assign(self, node): if self._in_class(node): element_full_name = self._pop_indent_stack(node, "prop") code_id = (self._fname, node.lineno) self._processed_line = node.lineno ...
Implement assignment walker. Parse class properties defined via the property() function
14,758
def methodcall(obj, method_name, *args, **kwargs): this_engine = distob.engine.eid args = [obj] + list(args) prefer_local = kwargs.pop(, None) if prefer_local is None: if isinstance(obj, Remote): prefer_local = obj.prefer_local else: prefer_local = True b...
Call a method of `obj`, either locally or remotely as appropriate. obj may be an ordinary object, or a Remote object (or Ref or object Id) If there are multiple remote arguments, they must be on the same engine. kwargs: prefer_local (bool, optional): Whether to return cached local results if ...
14,759
def read_namespaced_pod_disruption_budget_status(self, name, namespace, **kwargs): kwargs[] = True if kwargs.get(): return self.read_namespaced_pod_disruption_budget_status_with_http_info(name, namespace, **kwargs) else: (data) = self.read_namespaced_pod_disrupti...
read status of the specified PodDisruptionBudget This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_pod_disruption_budget_status(name, namespace, async_req=True) >>> result = thread.ge...
14,760
def A(self): return fft(np.dstack([np.eye(self.m), -self.b]), self.nfft * 2 - 1)[:, :, :self.nfft]
Spectral VAR coefficients. .. math:: \mathbf{A}(f) = \mathbf{I} - \sum_{k=1}^{p} \mathbf{a}^{(k)} \mathrm{e}^{-2\pi f}
14,761
def matches_count(count, options): if options.get("count") is not None: return count == int(options["count"]) if options.get("maximum") is not None and int(options["maximum"]) < count: return False if options.get("minimum") is not None and int(options["minimum"]) > count: retur...
Returns whether the given count matches the given query options. If no quantity options are specified, any count is considered acceptable. Args: count (int): The count to be validated. options (Dict[str, int | Iterable[int]]): A dictionary of query options. Returns: bool: Whether ...
14,762
def accumulate_from_superclasses(cls, propname): cachename = "__cached_all" + propname if cachename not in cls.__dict__: s = set() for c in inspect.getmro(cls): if issubclass(c, HasProps) and hasattr(c, propname): base = getattr(c, propname) ...
Traverse the class hierarchy and accumulate the special sets of names ``MetaHasProps`` stores on classes: Args: name (str) : name of the special attribute to collect. Typically meaningful values are: ``__container_props__``, ``__properties__``, ``__properties_with_refs__``
14,763
def bin_to_edge_slice(s, n): s = canonify_slice(s, n) start = s.start stop = s.stop if start > stop: _stop = start + 1 start = stop + 1 stop = _stop start = max(start - 1, 0) step = abs(s.step) if stop <= 1 or start >= n - 1 or stop == start + 1: return s...
Convert a bin slice into a bin edge slice.
14,764
def zip_strip_namespace(zip_src, namespace, logger=None): namespace_prefix = "{}__".format(namespace) lightning_namespace = "{}:".format(namespace) zip_dest = zipfile.ZipFile(io.BytesIO(), "w", zipfile.ZIP_DEFLATED) for name in zip_src.namelist(): orig_content = zip_src.read(name) t...
Given a namespace, strips 'namespace__' from all files and filenames in the zip
14,765
def tag(name, tag_name): with LOCK: metric(name) TAGS.setdefault(tag_name, set()).add(name)
Tag the named metric with the given tag.
14,766
def _delete_fw(self, tenant_id, data): LOG.debug("In Delete fw data is %s", data) in_sub = self.get_in_subnet_id(tenant_id) out_sub = self.get_out_subnet_id(tenant_id) arg_dict = self._create_arg_dict(tenant_id, data, in_sub, out_sub) if arg_dict.get() is None: ...
Internal routine called when a FW is deleted.
14,767
def enc(data, **kwargs): if in kwargs: salt.utils.versions.warn_until( , keyfile\ sk_file\ ) kwargs[] = kwargs[] if in kwargs: salt.utils.versions.warn_until( , key\ sk\ ) kwargs[] = k...
Alias to `{box_type}_encrypt` box_type: secretbox, sealedbox(default)
14,768
def GetFormatSpecification(cls): format_specification = specification.FormatSpecification(cls.NAME) format_specification.AddNewSignature(b, offset=0) return format_specification
Retrieves the format specification. Returns: FormatSpecification: format specification.
14,769
def _load_cell(args, schema): name = args[] table = _get_table(name) if not table: table = datalab.bigquery.Table(name) if table.exists(): if args[] == : raise Exception( % name) elif schema: table.create(json.loads(schema)) elif not args[]: raise Exception( )
Implements the BigQuery load magic used to load data from GCS to a table. The supported syntax is: %bigquery load -S|--source <source> -D|--destination <table> <other_args> Args: args: the arguments following '%bigquery load'. schema: a JSON schema for the destination table. Returns: A mes...
14,770
def get_run_states(self) -> List[RunState]: raw_states = self.get_state() if not raw_states: _LOGGER.warning("Could not fetch runstates from ZoneMinder") return [] run_states = [] for i in raw_states[]: raw_state = i[] _LOGGER.inf...
Get a list of RunStates from the ZoneMinder API.
14,771
def save_hex(hex_file, path): if not hex_file: raise ValueError() if not path.endswith(): raise ValueError() with open(path, ) as output: output.write(hex_file.encode())
Given a string representation of a hex file, this function copies it to the specified path thus causing the device mounted at that point to be flashed. If the hex_file is empty it will raise a ValueError. If the filename at the end of the path does not end in '.hex' it will raise a ValueError.
14,772
def reload_solver(self, constraints=None): if constraints is None: constraints = self._solver.constraints self._stored_solver = None self._solver.add(constraints)
Reloads the solver. Useful when changing solver options. :param list constraints: A new list of constraints to use in the reloaded solver instead of the current one
14,773
def packet_from_xml_packet(xml_pkt, psml_structure=None): if not isinstance(xml_pkt, lxml.objectify.ObjectifiedElement): parser = lxml.objectify.makeparser(huge_tree=True) xml_pkt = lxml.objectify.fromstring(xml_pkt, parser) if psml_structure: return _packet_from_psml_packet(xml_pkt...
Gets a TShark XML packet object or string, and returns a pyshark Packet objec.t :param xml_pkt: str or xml object. :param psml_structure: a list of the fields in each packet summary in the psml data. If given, packets will be returned as a PacketSummary object. :return: Packet object.
14,774
def _create_any_group(self, parent_node, name, type_name, instance=None, constructor=None, args=None, kwargs=None): if args is None: args = [] if kwargs is None: kwargs = {} full_name = self._make_full_name(parent_node.v_full_name, na...
Generically creates a new group inferring from the `type_name`.
14,775
def model_code_key_prefix(code_location_key_prefix, model_name, image): training_job_name = sagemaker.utils.name_from_image(image) return .join(filter(None, [code_location_key_prefix, model_name or training_job_name]))
Returns the s3 key prefix for uploading code during model deployment The location returned is a potential concatenation of 2 parts 1. code_location_key_prefix if it exists 2. model_name or a name derived from the image Args: code_location_key_prefix (str): the s3 key prefix from code_l...
14,776
def parse(readDataInstance): if len(readDataInstance) == consts.IMAGE_NUMBEROF_DIRECTORY_ENTRIES * 8: newDataDirectory = DataDirectory() for i in range(consts.IMAGE_NUMBEROF_DIRECTORY_ENTRIES): newDataDirectory[i].name.value = dirs[i] newDataDirec...
Returns a L{DataDirectory}-like object. @type readDataInstance: L{ReadData} @param readDataInstance: L{ReadData} object to read from. @rtype: L{DataDirectory} @return: The L{DataDirectory} object containing L{consts.IMAGE_NUMBEROF_DIRECTORY_ENTRIES} L{Directory} objects...
14,777
def submit_cookbook(self, cookbook, params={}, _extra_params={}): self._check_user_parameters(params) files = {: cookbook} return self._submit(params, files, _extra_params=_extra_params)
Submit a cookbook.
14,778
def get(self, request): self.app_list = site.get_app_list(request) self.apps_dict = self.create_app_list_dict() items = get_config() if not items: voices = self.get_default_voices() else: voices = [] for item in items: ...
Returns a json representing the menu voices in a format eaten by the js menu. Raised ImproperlyConfigured exceptions can be viewed in the browser console
14,779
def convert_examples_to_features(examples, seq_length, tokenizer): features = [] for (ex_index, example) in enumerate(examples): tokens_a = tokenizer.tokenize(example.text_a) tokens_b = None if example.text_b: tokens_b = tokenizer.tokenize(example.text_b) if t...
Loads a data file into a list of `InputFeature`s.
14,780
def add_group(self, groupname, statements): msg = OmapiMessage.open(b"group") msg.message.append(("create", struct.pack("!I", 1))) msg.obj.append(("name", groupname)) msg.obj.append(("statements", statements)) response = self.query_server(msg) if response.opcode != OMAPI_OP_UPDATE: raise OmapiError("a...
Adds a group @type groupname: bytes @type statements: str
14,781
def from_httplib(ResponseCls, r, **response_kw): headers = HTTPHeaderDict() for k, v in r.getheaders(): headers.add(k, v) return ResponseCls(body=r, headers=headers, status=r.status, ...
Given an :class:`httplib.HTTPResponse` instance ``r``, return a corresponding :class:`urllib3.response.HTTPResponse` object. Remaining parameters are passed to the HTTPResponse constructor, along with ``original_response=r``.
14,782
def user_field(user, field, *args): if not field: return User = get_user_model() try: field_meta = User._meta.get_field(field) max_length = field_meta.max_length except FieldDoesNotExist: if not hasattr(user, field): return max_length = None i...
Gets or sets (optional) user model fields. No-op if fields do not exist.
14,783
def set2d(self): glDisable(GL_LIGHTING) glPolygonMode( GL_FRONT_AND_BACK, GL_FILL) width, height = self.get_size() glDisable(GL_DEPTH_TEST) glViewport(0, 0, width, height) glMatrixMode(GL_PROJECTION) glLoadIden...
Configures OpenGL to draw in 2D. Note that wireframe mode is always disabled in 2D-Mode, but can be re-enabled by calling ``glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)``\ .
14,784
def __on_presence(self, data): room_jid = data[].bare muc_presence = data[] room = muc_presence[] nick = muc_presence[] with self.__lock: try: room_data = self.__rooms[room] if room_data.nick != nick: ...
Got a presence stanza
14,785
def pack_req(cls, code, pl_ratio_min, pl_ratio_max, trd_env, acc_id, trd_mkt, conn_id): from futuquant.common.pb.Trd_GetPositionList_pb2 import Request req = Request() req.c2s.header.trdEnv = TRD_ENV_MAP[trd_env] req.c2s.header.accID = acc_id req.c2s.hea...
Convert from user request for trading days to PLS request
14,786
def log_normalization(self, name="log_normalization"): with self._name_scope(name): return (self.df * self.scale_operator.log_abs_determinant() + 0.5 * self.df * self.dimension * math.log(2.) + self._multi_lgamma(0.5 * self.df, self.dimension))
Computes the log normalizing constant, log(Z).
14,787
def _index(self, model): doc_type = model if not isinstance(model, str): doc_type = model.__table__.name index_name = doc_type if hasattr(model, "__msearch_index__"): index_name = model.__msearch_index__ if doc_type not in self._indexs: ...
Elasticsearch multi types has been removed Use multi index unless set __msearch_index__.
14,788
def _begin_request(self): headers = self.m2req.headers self._request = HTTPRequest(connection=self, method=headers.get("METHOD"), uri=self.m2req.path, version=headers.get("VERSION"), headers=headers, remote_ip=headers.get("x-forwarded...
Actually start executing this request.
14,789
def alpha3(self, code): code = self.alpha2(code) try: return self.alt_codes[code][0] except KeyError: return ""
Return the ISO 3166-1 three letter country code matching the provided country code. If no match is found, returns an empty string.
14,790
def main(): print_head() puts("Welcome to the will project generator.") puts("") if args.config_dist_only: print("Generating config.py.dist...") else: print("\nGenerating will scaffold...") current_dir = os.getcwd() plugins_dir = os.path.join(current_dir, "plugins") ...
Creates the following structure: /plugins __init__.py hello.py /templates blank.html .gitignore run_will.py requirements.txt Procfile README.md
14,791
def push(self, instance, action, success, idxs=_marker): uid = api.get_uid(instance) info = self.objects.get(uid, {}) idx = [] if idxs is _marker else idxs info[action] = {: success, : idx} self.objects[uid] = info
Adds an instance into the pool, to be reindexed on resume
14,792
def extract_jwt_token(self, token): with InvalidTokenHeader.handle_errors(): data = jwt.decode( token, self.encode_key, algorithms=self.allowed_algorithms, options={: False}, ) self._validate_jwt_da...
Extracts a data dictionary from a jwt token
14,793
def modify_virtual(hostname, username, password, name, destination, pool=None, address_status=None, auto_lasthop=None, bwc_policy=None, cmp_enabled=None, connection_limit=None, dhcp_relay...
Modify an virtual server. modify an existing virtual. Only parameters specified will be enforced. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the virtual to create destinatio...
14,794
def add_hyperedge(self, tail, head, attr_dict=None, **attr): attr_dict = self._combine_attribute_arguments(attr_dict, attr) if not tail and not head: raise ValueError("tail and head arguments \ cannot both be empty.") frozen_t...
Adds a hyperedge to the hypergraph, along with any related attributes of the hyperedge. This method will automatically add any node from the tail and head that was not in the hypergraph. A hyperedge without a "weight" attribute specified will be assigned the default value of 1. ...
14,795
def lstm_cell(inputs, state, num_units, use_peepholes=False, cell_clip=0.0, initializer=None, num_proj=None, num_unit_shards=None, num_proj_shards=None, reuse=None, name=None): ...
Full LSTM cell.
14,796
def setAnimated(self, state): self._animated = state self.setAttribute(Qt.WA_TranslucentBackground, state)
Sets whether or not the popup widget should animate its opacity when it is shown. :param state | <bool>
14,797
def run(self, loopinfo=None, batch_size=1): logger.info("{}.Starting...".format(self.__class__.__name__)) if loopinfo: while True: for topic in self.topics: self.call_kafka(topic, batch_size) time.sleep(loopinfo.sleep) else...
Run consumer
14,798
def split(self, X, y=None, groups=None): X, y, groups = indexable(X, y, groups) cgrs = [~r for r in X] condition_structure = defaultdict(set) for structure, condition in zip(cgrs, groups): condition_structure[condition].add(structure) train_data = defaultd...
Generate indices to split data into training and test set. Parameters ---------- X : array-like, of length n_samples Training data, includes reaction's containers y : array-like, of length n_samples The target variable for supervised learning problems. gro...
14,799
def fit_overlays(self, text, start=None, end=None, **kw): for ovl in text.overlays: if ovl.match(props=self.props_match, rng=(start, end)): yield ovl
Get an overlay thet fits the range [start, end).