code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def add_job(self, queue_name, job, timeout=200, replicate=None, delay=None, retry=None, ttl=None, maxlen=None, asynchronous=None): """ Add a job to a queue. ADDJOB queue_name job <ms-timeout> [REPLICATE <count>] [DELAY <sec>] [RETRY <sec>] [TTL <sec>] [MAXLEN <count>...
Add a job to a queue. ADDJOB queue_name job <ms-timeout> [REPLICATE <count>] [DELAY <sec>] [RETRY <sec>] [TTL <sec>] [MAXLEN <count>] [ASYNC] :param queue_name: is the name of the queue, any string, basically. :param job: is a string representing the job. :param timeout: is...
def check_lines(self, lines, i): """check lines have less than a maximum number of characters """ max_chars = self.config.max_line_length ignore_long_line = self.config.ignore_long_lines def check_line(line, i): if not line.endswith("\n"): self.add_me...
check lines have less than a maximum number of characters
def serialize(self) -> dict: """ Serialize the message for sending to slack API Returns: serialized message """ data = {**self} if "attachments" in self: data["attachments"] = json.dumps(self["attachments"]) return data
Serialize the message for sending to slack API Returns: serialized message
def _construct_request(self): """ Utility for constructing the request header and connection """ if self.parsed_endpoint.scheme == 'https': conn = httplib.HTTPSConnection(self.parsed_endpoint.netloc) else: conn = httplib.HTTPConnection(self.parsed_endpoint...
Utility for constructing the request header and connection
def readAsync(self, fileName, callback, **kwargs): """ Interprets the specified file asynchronously, interpreting it as a model or a script file. As a side effect, it invalidates all entities (as the passed file can contain any arbitrary command); the lists of entities will be re...
Interprets the specified file asynchronously, interpreting it as a model or a script file. As a side effect, it invalidates all entities (as the passed file can contain any arbitrary command); the lists of entities will be re-populated lazily (at first access). Args: fileNam...
def top_stories(self, limit=5, first=None, last=None, json=False): """ Get the top story objects list params : limit = (default | 5) number of story objects needed json = (default | False) The method uses asynchronous grequest form gevent """ ...
Get the top story objects list params : limit = (default | 5) number of story objects needed json = (default | False) The method uses asynchronous grequest form gevent
def _replay_index(replay_dir): """Output information for a directory of replays.""" run_config = run_configs.get() replay_dir = run_config.abs_replay_path(replay_dir) print("Checking: ", replay_dir) with run_config.start(want_rgb=False) as controller: print("-" * 60) print(",".join(( "filenam...
Output information for a directory of replays.
def run(self): """Called when a file is changed to re-run the tests with nose.""" if self.auto_clear: os.system('cls' if os.name == 'nt' else 'auto_clear') else: print print 'Running unit tests...' if self.auto_clear: print subprocess.c...
Called when a file is changed to re-run the tests with nose.
def get_meta(cls): """ Collect all members of any contained :code:`Meta` class declarations from the given class or any of its base classes. (Sub class values take precedence.) :type cls: class :rtype: Struct """ merged_attributes = Struct() for class_ in reversed(cls.mr...
Collect all members of any contained :code:`Meta` class declarations from the given class or any of its base classes. (Sub class values take precedence.) :type cls: class :rtype: Struct
def initialize(self): """Instantiates the cache area to be ready for updates""" if self.collname not in self.current_kv_names(): r = self.request('post', self.url+"storage/collections/config", headers={'content-type': 'application/jso...
Instantiates the cache area to be ready for updates
def UploadFile(self, fd, offset=0, amount=None): """Uploads chunks of a given file descriptor to the transfer store flow. Args: fd: A file descriptor to upload. offset: An integer offset at which the file upload should start on. amount: An upper bound on number of bytes to stream. If it is `N...
Uploads chunks of a given file descriptor to the transfer store flow. Args: fd: A file descriptor to upload. offset: An integer offset at which the file upload should start on. amount: An upper bound on number of bytes to stream. If it is `None` then the whole file is uploaded. Retur...
def wrap_value(value, include_empty=False): """ :return: the value wrapped in a list unless it is already iterable (and not a dict); if so, empty values will be filtered out by default, and an empty list is returned. """ if value is None: return [None] if include_empty else [] elif hasa...
:return: the value wrapped in a list unless it is already iterable (and not a dict); if so, empty values will be filtered out by default, and an empty list is returned.
def recv_result_from_workers(self): """ Receives a results from the MPI worker pool and send it out via 0mq Returns: -------- result: task result from the workers """ info = MPI.Status() result = self.comm.recv(source=MPI.ANY_SOURCE, tag=RESULT_TAG, status=in...
Receives a results from the MPI worker pool and send it out via 0mq Returns: -------- result: task result from the workers
def register_reference(self, dispatcher, node): """ Register this identifier to the current scope, and mark it as referenced in the current scope. """ # the identifier node itself will be mapped to the current scope # for the resolve to work # This should probabl...
Register this identifier to the current scope, and mark it as referenced in the current scope.
def imagetransformer_base_10l_16h_big_dr01_imgnet(): """big 1d model for conditional image generation.""" hparams = imagetransformer_base_14l_8h_big_dr01() # num_hidden_layers hparams.num_decoder_layers = 10 hparams.num_heads = 16 hparams.hidden_size = 1024 hparams.filter_size = 4096 hparams.batch_size ...
big 1d model for conditional image generation.
def spin_px(self): """Returns the x-component of the spin of the primary mass.""" return conversions.primary_spin(self.mass1, self.mass2, self.spin1x, self.spin2x)
Returns the x-component of the spin of the primary mass.
def update(self, event): """ All messages from the Protocol get passed through this method. This allows the client to have an up-to-date state for the client. However, this method doesn't actually update right away. Instead, the acutal update happens in another thread, potentially later, in order to al...
All messages from the Protocol get passed through this method. This allows the client to have an up-to-date state for the client. However, this method doesn't actually update right away. Instead, the acutal update happens in another thread, potentially later, in order to allow user code to handle the event...
def detect_xid_devices(self): """ For all of the com ports connected to the computer, send an XID command '_c1'. If the device response with '_xid', it is an xid device. """ self.__xid_cons = [] for c in self.__com_ports: device_found = False ...
For all of the com ports connected to the computer, send an XID command '_c1'. If the device response with '_xid', it is an xid device.
def parse(filename_url_or_file, guess_charset=True, parser=None): """Parse a filename, URL, or file-like object into an HTML document tree. Note: this returns a tree, not an element. Use ``parse(...).getroot()`` to get the document root. """ if parser is None: parser = html_parser if n...
Parse a filename, URL, or file-like object into an HTML document tree. Note: this returns a tree, not an element. Use ``parse(...).getroot()`` to get the document root.
def get_packet(self, generation_time, sequence_number): """ Gets a single packet by its identifying key (gentime, seqNum). :param ~datetime.datetime generation_time: When the packet was generated (packet time) :param int sequence_number: Sequence number of the packet :rtype: .Pa...
Gets a single packet by its identifying key (gentime, seqNum). :param ~datetime.datetime generation_time: When the packet was generated (packet time) :param int sequence_number: Sequence number of the packet :rtype: .Packet
def create_long_form_weights(model_obj, wide_weights, rows_to_obs=None): """ Converts an array of weights with one element per observation (wide-format) to an array of weights with one element per observation per available alternative (long-format). Parameters ---------- model_obj : an inst...
Converts an array of weights with one element per observation (wide-format) to an array of weights with one element per observation per available alternative (long-format). Parameters ---------- model_obj : an instance or sublcass of the MNDC class. Should be the model object that correspon...
def remove_extra_packages(self, packages, dry_run=False): """ Remove all packages missing from list """ removal_list = self.determine_extra_packages(packages) if not removal_list: print("No packages to be removed") else: if dry_run: print("The fol...
Remove all packages missing from list
def login_required(fn): """Requires login before proceeding, but does not prompt the user to login. Decorator should be used only on Click CLI commands. Notes ----- Different means of authentication will be attempted in this order: 1. An API key present in the Click context object from a pr...
Requires login before proceeding, but does not prompt the user to login. Decorator should be used only on Click CLI commands. Notes ----- Different means of authentication will be attempted in this order: 1. An API key present in the Click context object from a previous successful authenticatio...
def isoformat(self, sep='T'): """Return the time formatted according to ISO. This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if self.microsecond == 0. If self.tzinfo is not None, the UTC offset is also attached, giving 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-...
Return the time formatted according to ISO. This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if self.microsecond == 0. If self.tzinfo is not None, the UTC offset is also attached, giving 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-MM-DD HH:MM:SS+HH:MM'. Optional ...
def put_skeleton_files_on_disk(metadata_type, where, github_template=None, params={}): """ Generates file based on jinja2 templates """ api_name = params["api_name"] file_name = github_template["file_name"] template_source = config.connection.get_plugin_client_setting('mm_template_source', '...
Generates file based on jinja2 templates
def _input_as_lines(self, data): """Write sequence of lines to temp file, return filename data: a sequence to be written to a file, each element of the sequence will compose a line in the file * Note: '\n' will be stripped off the end of each sequence element before wri...
Write sequence of lines to temp file, return filename data: a sequence to be written to a file, each element of the sequence will compose a line in the file * Note: '\n' will be stripped off the end of each sequence element before writing to a file in order to avoid ...
def xml(self, text=TEXT): """ Generate an XML output from the report data. """ def convert(line): xml = " <item>\n" for f in line.index: xml += " <field name=\"%s\">%s</field>\n" % (f, line[f]) xml += " </item>\n" return xml re...
Generate an XML output from the report data.
def update(self, scopes=[], add_scopes=[], rm_scopes=[], note='', note_url=''): """Update this authorization. :param list scopes: (optional), replaces the authorization scopes with these :param list add_scopes: (optional), scopes to be added :param list rm_sco...
Update this authorization. :param list scopes: (optional), replaces the authorization scopes with these :param list add_scopes: (optional), scopes to be added :param list rm_scopes: (optional), scopes to be removed :param str note: (optional), new note about authorization ...
def _state(self): """The internal state of the object. The api responses are not consistent so a retry is performed on every call with information updating the internally saved state refreshing the data. The info is cached for STATE_CACHING_SECONDS. :return: The current state o...
The internal state of the object. The api responses are not consistent so a retry is performed on every call with information updating the internally saved state refreshing the data. The info is cached for STATE_CACHING_SECONDS. :return: The current state of the toons' information stat...
def dl_file(url, dest, chunk_size=6553): """Download `url` to `dest`""" import urllib3 http = urllib3.PoolManager() r = http.request('GET', url, preload_content=False) with dest.open('wb') as out: while True: data = r.read(chunk_size) if data is None or len(data) == 0...
Download `url` to `dest`
def read_source_models(fnames, converter, monitor): """ :param fnames: list of source model files :param converter: a SourceConverter instance :param monitor: a :class:`openquake.performance.Monitor` instance :yields: SourceModel instances """ for fname in fna...
:param fnames: list of source model files :param converter: a SourceConverter instance :param monitor: a :class:`openquake.performance.Monitor` instance :yields: SourceModel instances
def make_config_data(*, guided): """ Makes the data necessary to construct a functional config file """ config_data = {} config_data[INCLUDE_DIRS_KEY] = _make_include_dirs(guided=guided) config_data[RUNTIME_DIRS_KEY] = _make_runtime_dirs(guided=guided) config_data[RUNTIME_KEY] = _make_runtim...
Makes the data necessary to construct a functional config file
def _open_connection(self): """Open a connection to the easyfire unit.""" if (self._mode == PROP_MODE_SERIAL): self._serial = serial.Serial(self._serial_device, self._serial_speed) elif (self._mode == PROP_MODE_TCP): self._socket = socket.socket(socket.AF_INET, socket.SOC...
Open a connection to the easyfire unit.
def add_task_status(self, name, **attrs): """ Add a Task status to the project and returns a :class:`TaskStatus` object. :param name: name of the :class:`TaskStatus` :param attrs: optional attributes for :class:`TaskStatus` """ return TaskStatuses(self.requester)...
Add a Task status to the project and returns a :class:`TaskStatus` object. :param name: name of the :class:`TaskStatus` :param attrs: optional attributes for :class:`TaskStatus`
def decorator_with_args(func, return_original=False, target_pos=0): """Enable a function to work with a decorator with arguments Args: func (callable): The input function. return_original (bool): Whether the resultant decorator returns the decorating target unchanged. If True, will return...
Enable a function to work with a decorator with arguments Args: func (callable): The input function. return_original (bool): Whether the resultant decorator returns the decorating target unchanged. If True, will return the target unchanged. Otherwise, return the returned value from ...
def initialize(self, length=None): """see ``__init__``""" if length is None: length = len(self.bounds) max_i = min((len(self.bounds) - 1, length - 1)) self._lb = array([self.bounds[min((i, max_i))][0] if self.bounds[min((i, max_i))][0] is not None ...
see ``__init__``
def GetFormatStringAttributeNames(self): """Retrieves the attribute names in the format string. Returns: set(str): attribute names. """ if self._format_string_attribute_names is None: self._format_string_attribute_names = [] for format_string_piece in self.FORMAT_STRING_PIECES: ...
Retrieves the attribute names in the format string. Returns: set(str): attribute names.
def generate_address(self): """ Creates a Bitcoin address from the public key. Details of the steps for creating the address are outlined in this link: https://en.bitcoin.it/wiki/Technical_background_of_version_1_Bitcoin_addresses The last step is Base58Check en...
Creates a Bitcoin address from the public key. Details of the steps for creating the address are outlined in this link: https://en.bitcoin.it/wiki/Technical_background_of_version_1_Bitcoin_addresses The last step is Base58Check encoding, which is similar to Base64 encoding but ...
def cli(env, zone): """Delete zone.""" manager = SoftLayer.DNSManager(env.client) zone_id = helpers.resolve_id(manager.resolve_ids, zone, name='zone') if not (env.skip_confirmations or formatting.no_going_back(zone)): raise exceptions.CLIAbort("Aborted.") manager.delete_zone(zone_id)
Delete zone.
def structure(cls): # type: () -> Text """Get the part structure, as a DNA regex pattern. The structure of most parts can be obtained automatically from the part signature and the restriction enzyme used in the Golden Gate assembly. Warning: If overloading t...
Get the part structure, as a DNA regex pattern. The structure of most parts can be obtained automatically from the part signature and the restriction enzyme used in the Golden Gate assembly. Warning: If overloading this method, the returned pattern must include 3 ...
def map_address(self, session, map_space, map_base, map_size, access=False, suggested=None): """Maps the specified memory space into the process's address space. Corresponds to viMapAddress function of the VISA library. :param session: Unique logical identifier to a session...
Maps the specified memory space into the process's address space. Corresponds to viMapAddress function of the VISA library. :param session: Unique logical identifier to a session. :param map_space: Specifies the address space to map. (Constants.*SPACE*) :param map_base: Offset (in byte...
def save(self, fname): """ saves a grid to file as ASCII text """ try: with open(fname, "w") as f: f.write(str(self)) except Exception as ex: print('ERROR = cant save grid results to ' + fname + str(ex))
saves a grid to file as ASCII text
def main(args=None, vc=None, cwd=None, apply_config=False): """PEP8 clean only the parts of the files touched since the last commit, a previous commit or branch.""" import signal try: # pragma: no cover # Exit on broken pipe. signal.signal(signal.SIGPIPE, signal.SIG_DFL) except Att...
PEP8 clean only the parts of the files touched since the last commit, a previous commit or branch.
def _precedence_parens(self, node, child, is_left=True): """Wrap child in parens only if required to keep same semantics""" if self._should_wrap(node, child, is_left): return "(%s)" % child.accept(self) return child.accept(self)
Wrap child in parens only if required to keep same semantics
def _PrintWarningsDetails(self, storage): """Prints the details of the warnings. Args: storage (BaseStore): storage. """ if not storage.HasWarnings(): self._output_writer.Write('No warnings stored.\n\n') return for index, warning in enumerate(storage.GetWarnings()): title =...
Prints the details of the warnings. Args: storage (BaseStore): storage.
def getInterfaceInAllSpeeds(interface, endpoint_list, class_descriptor_list=()): """ Produce similar fs, hs and ss interface and endpoints descriptors. Should be useful for devices desiring to work in all 3 speeds with maximum endpoint wMaxPacketSize. Reduces data duplication from descriptor declara...
Produce similar fs, hs and ss interface and endpoints descriptors. Should be useful for devices desiring to work in all 3 speeds with maximum endpoint wMaxPacketSize. Reduces data duplication from descriptor declarations. Not intended to cover fancy combinations. interface (dict): Keyword arg...
def _multi_blockify(tuples, dtype=None): """ return an array of blocks that potentially have different dtypes """ # group by dtype grouper = itertools.groupby(tuples, lambda x: x[2].dtype) new_blocks = [] for dtype, tup_block in grouper: values, placement = _stack_arrays(list(tup_block), ...
return an array of blocks that potentially have different dtypes
def __get_keys(self, name='master', passphrase=None): ''' Returns a key object for a key in the pki-dir ''' path = os.path.join(self.opts['pki_dir'], name + '.pem') if not os.path.exists(path): log.info('Generating %s keys: %s', name, self....
Returns a key object for a key in the pki-dir
def list_provincie_adapter(obj, request): """ Adapter for rendering a list of :class:`crabpy.gateway.crab.Provincie` to json. """ return { 'niscode': obj.niscode, 'naam': obj.naam, 'gewest': { 'id': obj.gewest.id, 'naam': obj.gewest.naam } ...
Adapter for rendering a list of :class:`crabpy.gateway.crab.Provincie` to json.
def _get_available_placements(D, tt): """ Called from: _prompt_placement() Get a list of possible places that we can put the new model data into. If no model exists yet, we'll use something like chron0model0. If other models exist, we'll go for the n+1 entry. ex: chron0model0 already exists, so...
Called from: _prompt_placement() Get a list of possible places that we can put the new model data into. If no model exists yet, we'll use something like chron0model0. If other models exist, we'll go for the n+1 entry. ex: chron0model0 already exists, so we'll look to chron0model1 next. :param dict...
def matrix_to_gl(matrix): """ Convert a numpy row- major homogenous transformation matrix to a flat column- major GLfloat transformation. Parameters ------------- matrix : (4,4) float Row- major homogenous transform Returns ------------- glmatrix : (16,) gl.GLfloat Tran...
Convert a numpy row- major homogenous transformation matrix to a flat column- major GLfloat transformation. Parameters ------------- matrix : (4,4) float Row- major homogenous transform Returns ------------- glmatrix : (16,) gl.GLfloat Transform in pyglet format
def last(self, values, axis=0): """return values at last occurance of its associated key Parameters ---------- values : array_like, [keys, ...] values to pick the last value of per group axis : int, optional alternative reduction axis for values ...
return values at last occurance of its associated key Parameters ---------- values : array_like, [keys, ...] values to pick the last value of per group axis : int, optional alternative reduction axis for values Returns ------- unique: nda...
def isLoopback (self, ifname): """Check whether interface is a loopback device. @param ifname: interface name @type ifname: string """ # since not all systems have IFF_LOOPBACK as a flag defined, # the ifname is tested first if ifname.startswith('lo'): ...
Check whether interface is a loopback device. @param ifname: interface name @type ifname: string
def fftconvolve(in1, in2, mode="full", axis=None): """ Convolve two N-dimensional arrays using FFT. See convolve. This is a fix of scipy.signal.fftconvolve, adding an axis argument and importing locally the stuff only needed for this function """ s1 = np.array(in1.shape) s2 = np.array(in2.shap...
Convolve two N-dimensional arrays using FFT. See convolve. This is a fix of scipy.signal.fftconvolve, adding an axis argument and importing locally the stuff only needed for this function
def add_port_profile_to_delete_table(self, profile_name, device_id): """Adds a port profile to the delete table.""" if not self.has_port_profile_to_delete(profile_name, device_id): port_profile = ucsm_model.PortProfileDelete( profile_id=profile_name, device_id=device_id) ...
Adds a port profile to the delete table.
def _find_line_start_index(self, index): """ For the index of a character at a certain line, calculate the index of the first character on that line. Return (row, index) tuple. """ indexes = self._line_start_indexes pos = bisect.bisect_right(indexes, index) - 1 ...
For the index of a character at a certain line, calculate the index of the first character on that line. Return (row, index) tuple.
def submitted_projects(raw_df): """ Return all submitted projects. """ df = raw_df.astype({'PRONAC': str, 'CgcCpf': str}) submitted_projects = df.groupby('CgcCpf')[ 'PRONAC' ].agg(['unique', 'nunique']) submitted_projects.columns = ['pronac_list', 'num_pronacs'] return submitte...
Return all submitted projects.
def _get_errors(self): """ Gets errors from HTTP response """ errors = self.json.get('data').get('failures') if errors: logger.error(errors) return errors
Gets errors from HTTP response
def list(region=None, key=None, keyid=None, profile=None): ''' List all trails Returns list of trails CLI Example: .. code-block:: yaml policies: - {...} - {...} ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) t...
List all trails Returns list of trails CLI Example: .. code-block:: yaml policies: - {...} - {...}
def wrapper__unignore(self, type_): """ Stop selectively ignoring certain types when wrapping attributes. :param class type: The class/type definition to stop ignoring. :rtype list(type): The current list of ignored types """ if type_ in self.__exclusion_list: ...
Stop selectively ignoring certain types when wrapping attributes. :param class type: The class/type definition to stop ignoring. :rtype list(type): The current list of ignored types
def find_substring_edge(self, substring, suffix_tree_id): """Returns an edge that matches the given substring. """ suffix_tree = self.suffix_tree_repo[suffix_tree_id] started = datetime.datetime.now() edge, ln = find_substring_edge(substring=substring, suffix_tree=suffix_tree, ed...
Returns an edge that matches the given substring.
def get_series(self, series): """ Returns a census series API handler. """ if series == "acs1": return self.census.acs1dp elif series == "acs5": return self.census.acs5 elif series == "sf1": return self.census.sf1 elif series ==...
Returns a census series API handler.
def parts(xs, number = None, length = None): """ Split a list into either the specified number of parts or a number of parts each of the specified length. The elements are distributed somewhat evenly among the parts if possible. >>> list(parts([1,2,3,4,5,6,7], length=1)) [[1], [2], [3], [4], [5...
Split a list into either the specified number of parts or a number of parts each of the specified length. The elements are distributed somewhat evenly among the parts if possible. >>> list(parts([1,2,3,4,5,6,7], length=1)) [[1], [2], [3], [4], [5], [6], [7]] >>> list(parts([1,2,3,4,5,6,7], length=2...
def unfinished_objects(self): ''' Leaves only versions of those objects that has some version with `_end == None` or with `_end > right cutoff`. ''' mask = self._end_isnull if self._rbound is not None: mask = mask | (self._end > self._rbound) oids = se...
Leaves only versions of those objects that has some version with `_end == None` or with `_end > right cutoff`.
def _extract_battery_info_from_acpi(self): """ Get the battery info from acpi # Example acpi -bi raw output (Discharging): Battery 0: Discharging, 94%, 09:23:28 remaining Battery 0: design capacity 5703 mAh, last full capacity 5283 mAh = 92% Battery 1: Unknown, 98% ...
Get the battery info from acpi # Example acpi -bi raw output (Discharging): Battery 0: Discharging, 94%, 09:23:28 remaining Battery 0: design capacity 5703 mAh, last full capacity 5283 mAh = 92% Battery 1: Unknown, 98% Battery 1: design capacity 1880 mAh, last full capacity 1370...
def assert_close(a, b, rtol=1e-07, atol=0, context=None): """ Compare for equality up to a given precision two composite objects which may contain floats. NB: if the objects are or contain generators, they are exhausted. :param a: an object :param b: another object :param rtol: relative tol...
Compare for equality up to a given precision two composite objects which may contain floats. NB: if the objects are or contain generators, they are exhausted. :param a: an object :param b: another object :param rtol: relative tolerance :param atol: absolute tolerance
def _parse_sigmak(line, lines): """Parse Energy, Re sigma xx, Im sigma xx, Re sigma zz, Im sigma zz""" split_line = line.split() energy = float(split_line[0]) re_sigma_xx = float(split_line[1]) im_sigma_xx = float(split_line[2]) re_sigma_zz = float(split_line[3]) im_sigma_zz = float(split_...
Parse Energy, Re sigma xx, Im sigma xx, Re sigma zz, Im sigma zz
def build_specfile_filesection(spec, files): """ builds the %file section of the specfile """ str = '%files\n' if 'X_RPM_DEFATTR' not in spec: spec['X_RPM_DEFATTR'] = '(-,root,root)' str = str + '%%defattr %s\n' % spec['X_RPM_DEFATTR'] supported_tags = { 'PACKAGING_CONFIG' ...
builds the %file section of the specfile
def get_content_type(self): """mime type of the attachment part""" ctype = self.part.get_content_type() # replace underspecified mime description by a better guess if ctype in ['octet/stream', 'application/octet-stream', 'application/octetstream']: ctype ...
mime type of the attachment part
def compress(func): """Compress result with deflate algorithm if the client ask for it.""" def wrapper(*args, **kwargs): """Wrapper that take one function and return the compressed result.""" ret = func(*args, **kwargs) logger.debug('Receive {} {} request with header: {}'.format( ...
Compress result with deflate algorithm if the client ask for it.
def href(*args, **kw): """ Simple function for URL generation. Position arguments are used for the URL path and keyword arguments are used for the url parameters. """ result = [(request.script_root if request else "") + "/"] for idx, arg in enumerate(args): result.append(("/" if idx els...
Simple function for URL generation. Position arguments are used for the URL path and keyword arguments are used for the url parameters.
def audits(self, ticket=None, include=None, **kwargs): """ Retrieve TicketAudits. If ticket is passed, return the tickets for a specific audit. If ticket_id is None, a TicketAuditGenerator is returned to handle pagination. The way this generator works is a different to the other Zenpy g...
Retrieve TicketAudits. If ticket is passed, return the tickets for a specific audit. If ticket_id is None, a TicketAuditGenerator is returned to handle pagination. The way this generator works is a different to the other Zenpy generators as it is cursor based, allowing you to change the directi...
def get_gpd_line(self,transcript_name=None,gene_name=None,direction=None): """Get the genpred format string representation of the mapping""" return transcript_to_gpd_line(self,transcript_name=transcript_name,gene_name=gene_name,direction=direction)
Get the genpred format string representation of the mapping
def load_umatrix(self, filename): """Load the umatrix from a file to the Somoclu object. :param filename: The name of the file. :type filename: str. """ self.umatrix = np.loadtxt(filename, comments='%') if self.umatrix.shape != (self._n_rows, self._n_columns): ...
Load the umatrix from a file to the Somoclu object. :param filename: The name of the file. :type filename: str.
def better_print(self, printer=None): """ Print the value using a *printer*. :param printer: Callable used to print the value, by default: :func:`pprint.pprint` """ printer = printer or pprint.pprint printer(self.value)
Print the value using a *printer*. :param printer: Callable used to print the value, by default: :func:`pprint.pprint`
def _send_reliable_message(self, msg): """Send msg to LightwaveRF hub.""" result = False max_retries = 15 trans_id = next(LWLink.transaction_id) msg = "%d,%s" % (trans_id, msg) try: with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) \ as...
Send msg to LightwaveRF hub.
def delete_node_1ton(node_list, begin, node, end): # type: ([],LinkedNode, LinkedNode, LinkedNode)->[] """ delete the node which has 1-input and n-output """ if end is None: assert end is not None end = node.successor elif not isinstance(end, list): ...
delete the node which has 1-input and n-output
def ticket_fields(self): """ | Comment: ids of all ticket fields which are in this ticket form """ if self.api and self.ticket_field_ids: return self.api._get_ticket_fields(self.ticket_field_ids)
| Comment: ids of all ticket fields which are in this ticket form
def delete_cookie(self, key, path='/', domain=None): """Delete a cookie. Fails silently if key doesn't exist. :param key: the key (name) of the cookie to be deleted. :param path: if the cookie that should be deleted was limited to a path, the path has to be defined here. ...
Delete a cookie. Fails silently if key doesn't exist. :param key: the key (name) of the cookie to be deleted. :param path: if the cookie that should be deleted was limited to a path, the path has to be defined here. :param domain: if the cookie that should be deleted was l...
def tf_import_demo_experience(self, states, internals, actions, terminal, reward): """ Imports a single experience to memory. """ return self.demo_memory.store( states=states, internals=internals, actions=actions, terminal=terminal, ...
Imports a single experience to memory.
def matrixfromDicts(dicts): """ Give a list of dicts (or list of list of dicts) return a structured array. Headings will be sorted in alphabetical order. """ if 'numpy' in str(type(dicts)): return dicts #already an array? names=set([]) dicts=dictFlat(dicts) for item in dicts: ...
Give a list of dicts (or list of list of dicts) return a structured array. Headings will be sorted in alphabetical order.
def _schema_to_json_file_object(self, schema_list, file_obj): """Helper function for schema_to_json that takes a schema list and file object and writes the schema list to the file object with json.dump """ json.dump(schema_list, file_obj, indent=2, sort_keys=True)
Helper function for schema_to_json that takes a schema list and file object and writes the schema list to the file object with json.dump
def initFilter(input, filterInfo = None): """ Initializes internal filter variables for further processing. Returns a tuple (function to call,parameters for the filter call) The filterInfo is a dict. Here is an example structure: {fieldName: {'min': x, 'max': y, 'type': 'cat...
Initializes internal filter variables for further processing. Returns a tuple (function to call,parameters for the filter call) The filterInfo is a dict. Here is an example structure: {fieldName: {'min': x, 'max': y, 'type': 'category', # or 'number' 'acceptVa...
def get(self, date, page_no=1, page_size=40, fields=[]): '''taobao.taobaoke.report.get 淘宝客报表查询 淘宝客报表查询''' request = TOPRequest('taobao.taobaoke.items.get') request['date'] = date request['page_no'] = page_no request['page_size'] = page_size if not fields:...
taobao.taobaoke.report.get 淘宝客报表查询 淘宝客报表查询
def orientation(point_p, point_q, point_r): """ To find orientation of ordered triplet (p, q, r). :param point_p: :type point_p: models.Point :param point_q: :type point_q: models.Point :param point_r: :type point_r: models.Point :return: 0: p, q and r are colinear 1: c...
To find orientation of ordered triplet (p, q, r). :param point_p: :type point_p: models.Point :param point_q: :type point_q: models.Point :param point_r: :type point_r: models.Point :return: 0: p, q and r are colinear 1: clockwise 2: counterclockwise :rtype: in...
def yield_module_imports(root, checks=string_imports()): """ Gather all require and define calls from unbundled JavaScript source files and yield all module names. The imports can either be of the CommonJS or AMD syntax. """ if not isinstance(root, asttypes.Node): raise TypeError('prov...
Gather all require and define calls from unbundled JavaScript source files and yield all module names. The imports can either be of the CommonJS or AMD syntax.
def tree(self): """Tree with branch lengths in codon substitutions per site. The tree is a `Bio.Phylo.BaseTree.Tree` object. This is the current tree after whatever optimizations have been performed so far. """ bs = self.model.branchScale for node in self._tree....
Tree with branch lengths in codon substitutions per site. The tree is a `Bio.Phylo.BaseTree.Tree` object. This is the current tree after whatever optimizations have been performed so far.
def expand(self, line, do_expand, force=False, vislevels=0, level=-1): """Multi-purpose expand method from original STC class""" lastchild = self.GetLastChild(line, level) line += 1 while line <= lastchild: if force: if vislevels > 0: sel...
Multi-purpose expand method from original STC class
def _GetMessage(self, message_file_key, lcid, message_identifier): """Retrieves a specific message from a specific message table. Args: message_file_key (int): message file key. lcid (int): language code identifier (LCID). message_identifier (int): message identifier. Returns: str:...
Retrieves a specific message from a specific message table. Args: message_file_key (int): message file key. lcid (int): language code identifier (LCID). message_identifier (int): message identifier. Returns: str: message string or None if not available. Raises: RuntimeError:...
def police_priority_map_exceed_map_pri2_exceed(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") police_priority_map = ET.SubElement(config, "police-priority-map", xmlns="urn:brocade.com:mgmt:brocade-policer") name_key = ET.SubElement(police_priority_map, ...
Auto Generated Code
def scale_rows_by_largest_entry(S): """Scale each row in S by it's largest in magnitude entry. Parameters ---------- S : csr_matrix Returns ------- S : csr_matrix Each row has been scaled by it's largest in magnitude entry Examples -------- >>> from pyamg.gallery impor...
Scale each row in S by it's largest in magnitude entry. Parameters ---------- S : csr_matrix Returns ------- S : csr_matrix Each row has been scaled by it's largest in magnitude entry Examples -------- >>> from pyamg.gallery import poisson >>> from pyamg.util.utils imp...
def group(self, base_dn, samaccountname, attributes=(), explicit_membership_only=False): """Produces a single, populated ADGroup object through the object factory. Does not populate attributes for the caller instance. sAMAccountName may not be present in group objects in modern AD schemas. ...
Produces a single, populated ADGroup object through the object factory. Does not populate attributes for the caller instance. sAMAccountName may not be present in group objects in modern AD schemas. Searching by common name and object class (group) may be an alternative approach if requ...
def to_cloudformation(self, **kwargs): """Returns the Lambda Permission resource allowing SNS to invoke the function this event source triggers. :param dict kwargs: no existing resources need to be modified :returns: a list of vanilla CloudFormation Resources, to which this SNS event expands ...
Returns the Lambda Permission resource allowing SNS to invoke the function this event source triggers. :param dict kwargs: no existing resources need to be modified :returns: a list of vanilla CloudFormation Resources, to which this SNS event expands :rtype: list
def normalize_layout(layout, min_percentile=1, max_percentile=99, relative_margin=0.1): """Removes outliers and scales layout to between [0,1].""" # compute percentiles mins = np.percentile(layout, min_percentile, axis=(0)) maxs = np.percentile(layout, max_percentile, axis=(0)) # add margins m...
Removes outliers and scales layout to between [0,1].
def is_friend(self): """:class:`bool`: Checks if the user is your friend. .. note:: This only applies to non-bot accounts. """ r = self.relationship if r is None: return False return r.type is RelationshipType.friend
:class:`bool`: Checks if the user is your friend. .. note:: This only applies to non-bot accounts.
def num2tamilstr_american( *args ): number = args[0] """ work till 1000 trillion - 1 - i.e = 1e12*1e3 - 1. turn number into a numeral, American style. Fractions upto 1e-30. """ if not any( filter( lambda T: isinstance( number, T), [int, str, unicode, long, float]) ) or isinstance(number,complex):...
work till 1000 trillion - 1 - i.e = 1e12*1e3 - 1. turn number into a numeral, American style. Fractions upto 1e-30.
def login(request, template_name='ci/login.html', redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationForm): """ Displays the login form and handles the login action. """ redirect_to = request.POST.get(redirect_field_name, req...
Displays the login form and handles the login action.
def collapse(dataframe, groupe, var): ''' Pour une variable, fonction qui calcule la moyenne pondérée au sein de chaque groupe. ''' grouped = dataframe.groupby([groupe]) var_weighted_grouped = grouped.apply(lambda x: wavg(groupe = x, var = var)) return var_weighted_grouped
Pour une variable, fonction qui calcule la moyenne pondérée au sein de chaque groupe.
def __get_rectangle_description(block, pair): """! @brief Create rectangle description for block in specific dimension. @param[in] pair (tuple): Pair of coordinate index that should be displayed. @param[in] block (bang_block): BANG-block that should be displayed @return ...
! @brief Create rectangle description for block in specific dimension. @param[in] pair (tuple): Pair of coordinate index that should be displayed. @param[in] block (bang_block): BANG-block that should be displayed @return (tuple) Pair of corners that describes rectangle.
def lookup(self, allowed_types, **kwargs): """Lookup an object of type (allowed_types). kwargs is sent directly to the catalog. """ at = getToolByName(self, 'archetype_tool') for portal_type in allowed_types: catalog = at.catalog_map.get(portal_type, [None])[0] ...
Lookup an object of type (allowed_types). kwargs is sent directly to the catalog.