code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def acquire_connection(settings, tag=None, logger_name=None, auto_commit=False): """ Return a connection to a Relational DataBase Management System (RDBMS) the most appropriate for the service requesting this connection. @param settings: a dictionary of connection properties:: ...
Return a connection to a Relational DataBase Management System (RDBMS) the most appropriate for the service requesting this connection. @param settings: a dictionary of connection properties:: { None: { 'rdbms_hostname': "...", ...
def plot_xtf(fignum, XTF, Fs, e, b): """ function to plot series of chi measurements as a function of temperature, holding field constant and varying frequency """ plt.figure(num=fignum) plt.xlabel('Temperature (K)') plt.ylabel('Susceptibility (m^3/kg)') k = 0 Flab = [] for freq in X...
function to plot series of chi measurements as a function of temperature, holding field constant and varying frequency
def distance_to_edge(labels): '''Compute the distance of a pixel to the edge of its object labels - a labels matrix returns a matrix of distances ''' colors = color_labels(labels) max_color = np.max(colors) result = np.zeros(labels.shape) if max_color == 0: return resul...
Compute the distance of a pixel to the edge of its object labels - a labels matrix returns a matrix of distances
def _parse_mirteFile(path, logger=None): """ Open and parses the mirteFile at <path>. """ l = logging.getLogger('_parse_mirteFile') if logger is None else logger cache_path = os.path.join(os.path.dirname(path), CACHE_FILENAME_TEMPLATE % os.path.basename(path)) if (os.path.e...
Open and parses the mirteFile at <path>.
def transform_obs(self, obs): """Render some SC2 observations into something an agent can handle.""" empty = np.array([], dtype=np.int32).reshape((0, 7)) out = named_array.NamedDict({ # Fill out some that are sometimes empty. "single_select": empty, "multi_select": empty, "build_que...
Render some SC2 observations into something an agent can handle.
def _simplify_non_context_field_binary_composition(expression): """Return a simplified BinaryComposition if either operand is a TrueLiteral. Args: expression: BinaryComposition without any ContextField operand(s) Returns: simplified expression if the given expression is a disjunction/conju...
Return a simplified BinaryComposition if either operand is a TrueLiteral. Args: expression: BinaryComposition without any ContextField operand(s) Returns: simplified expression if the given expression is a disjunction/conjunction and one of it's operands is a TrueLiteral, and t...
def __is_valid_type(self, typ, typlist): """ Check if type is valid based on input type list "string" is special because it can be used for stringlist :param typ: the type to check :param typlist: the list of type to check :return: True on success, False otherwise ""...
Check if type is valid based on input type list "string" is special because it can be used for stringlist :param typ: the type to check :param typlist: the list of type to check :return: True on success, False otherwise
def dump(deposition, from_date, with_json=True, latest_only=False, **kwargs): """Dump the deposition object as dictionary.""" # Serialize the __getstate__ and fall back to default serializer dep_json = json.dumps(deposition.__getstate__(), default=default_serializer) dep_dict =...
Dump the deposition object as dictionary.
def is_valid_short_number_for_region(short_numobj, region_dialing_from): """Tests whether a short number matches a valid pattern in a region. Note that this doesn't verify the number is actually in use, which is impossible to tell by just looking at the number itself. Arguments: short_numobj -- th...
Tests whether a short number matches a valid pattern in a region. Note that this doesn't verify the number is actually in use, which is impossible to tell by just looking at the number itself. Arguments: short_numobj -- the short number to check as a PhoneNumber object. region_dialing_from -- the ...
def create_project(self, name=None, project_id=None, path=None): """ Create a project and keep a references to it in project manager. See documentation of Project for arguments """ if project_id is not None and project_id in self._projects: return self._projects[pro...
Create a project and keep a references to it in project manager. See documentation of Project for arguments
def get_vcs_details_output_vcs_details_principal_switch_wwn(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_vcs_details = ET.Element("get_vcs_details") config = get_vcs_details output = ET.SubElement(get_vcs_details, "output") vcs_det...
Auto Generated Code
def getPort(self): """ Helper method for testing; returns the TCP port used for this registration, even if it was specified as 0 and thus allocated by the OS. """ disp = self.pbmanager.dispatchers[self.portstr] return disp.port.getHost().port
Helper method for testing; returns the TCP port used for this registration, even if it was specified as 0 and thus allocated by the OS.
def _stdin_raw_block(self): """Use a blocking stdin read""" # The big problem with the blocking read is that it doesn't # exit when it's supposed to in all contexts. An extra # key-press may be required to trigger the exit. try: data = sys.stdin.read(1) da...
Use a blocking stdin read
def bovy_text(*args,**kwargs): """ NAME: bovy_text PURPOSE: thin wrapper around matplotlib's text and annotate use keywords: 'bottom_left=True' 'bottom_right=True' 'top_left=True' 'top_right=True' 'title=True' to place t...
NAME: bovy_text PURPOSE: thin wrapper around matplotlib's text and annotate use keywords: 'bottom_left=True' 'bottom_right=True' 'top_left=True' 'top_right=True' 'title=True' to place the text in one of the corners or use it as ...
def generate_messages(outf, msgs): """Generate Swift structs to represent all MAVLink messages""" print("Generating Messages") t.write(outf, """ // MARK: MAVLink messages /** Message protocol describes common for all MAVLink messages properties and methods requirements */ public protocol Message: M...
Generate Swift structs to represent all MAVLink messages
def _fix_component_id(self, component): 'Fix name of component ad all of its children' theID = getattr(component, "id", None) if theID is not None: setattr(component, "id", self._fix_id(theID)) try: for c in component.children: self._fix_component...
Fix name of component ad all of its children
def get_interval_timedelta(self): """ Spits out the timedelta in days. """ now_datetime = timezone.now() current_month_days = monthrange(now_datetime.year, now_datetime.month)[1] # Two weeks if self.interval == reminders_choices.INTERVAL_2_WEEKS: interval_timedelta ...
Spits out the timedelta in days.
def basic_qos(self, prefetch_size, prefetch_count, a_global): """Specify quality of service This method requests a specific quality of service. The QoS can be specified for the current channel or for all channels on the connection. The particular properties and semantics of a ...
Specify quality of service This method requests a specific quality of service. The QoS can be specified for the current channel or for all channels on the connection. The particular properties and semantics of a qos method always depend on the content class semantics. Though t...
def from_json(cls, data): """Create a Sky Condition from a dictionary. Args: data = { "solar_model": string, "month": int, "day_of_month": int, "clearness": float, "daylight_savings_indicator": string // "Yes" or "No"} """ ...
Create a Sky Condition from a dictionary. Args: data = { "solar_model": string, "month": int, "day_of_month": int, "clearness": float, "daylight_savings_indicator": string // "Yes" or "No"}
def romanize(text: str, engine: str = "royin") -> str: """ Rendering Thai words in the Latin alphabet or "romanization", using the Royal Thai General System of Transcription (RTGS), which is the official system published by the Royal Institute of Thailand. ถอดเสียงภาษาไทยเป็นอักษรละติน :param st...
Rendering Thai words in the Latin alphabet or "romanization", using the Royal Thai General System of Transcription (RTGS), which is the official system published by the Royal Institute of Thailand. ถอดเสียงภาษาไทยเป็นอักษรละติน :param str text: Thai text to be romanized :param str engine: 'royin' (d...
def deploy_api_gateway( self, api_id, stage_name, stage_description="", description="", cache_cluster_enabled=False, cache_cluster_size='0.5', ...
Deploy the API Gateway! Return the deployed API URL.
def guess_format( filename, ext, formats, io_table ): """ Guess the format of filename, candidates are in formats. """ ok = False for format in formats: output( 'guessing %s' % format ) try: ok = io_table[format].guess( filename ) except AttributeError: ...
Guess the format of filename, candidates are in formats.
def get_field_lookups(field_type, nullable): """ Return lookup table value and append isnull if this is a nullable field """ return LOOKUP_TABLE.get(field_type) + ['isnull'] if nullable else LOOKUP_TABLE.get(field_type)
Return lookup table value and append isnull if this is a nullable field
def total(self): """Total cost of the order """ total = 0 for item in self.items.all(): total += item.total return total
Total cost of the order
def element(self, inp=None): """Return an element from ``inp`` or from scratch.""" if inp is not None: s = str(inp)[:self.length] s += ' ' * (self.length - len(s)) return s else: return ' ' * self.length
Return an element from ``inp`` or from scratch.
def comment(self, text, comment_prefix='#'): """Creates a comment block Args: text (str): content of comment without # comment_prefix (str): character indicating start of comment Returns: self for chaining """ comment = Comment(self._containe...
Creates a comment block Args: text (str): content of comment without # comment_prefix (str): character indicating start of comment Returns: self for chaining
def _add_default_exposure_class(layer): """The layer doesn't have an exposure class, we need to add it. :param layer: The vector layer. :type layer: QgsVectorLayer """ layer.startEditing() field = create_field_from_definition(exposure_class_field) layer.keywords['inasafe_fields'][exposure_...
The layer doesn't have an exposure class, we need to add it. :param layer: The vector layer. :type layer: QgsVectorLayer
def len_cdc_tube(FlowPlant, ConcDoseMax, ConcStock, DiamTubeAvail, HeadlossCDC, LenCDCTubeMax, temp, en_chem, KMinor): """The length of tubing may be longer than the max specified if the stock concentration is too high to give a viable solution with the specified length of tub...
The length of tubing may be longer than the max specified if the stock concentration is too high to give a viable solution with the specified length of tubing.
def current_version(): """ Get the current version number from setup.py """ # Monkeypatch setuptools.setup so we get the verison number import setuptools version = [None] def monkey_setup(**settings): version[0] = settings['version'] old_setup = setuptools.setup setuptools...
Get the current version number from setup.py
def from_json(json_data): """ Returns a pyalveo.OAuth2 given a json string built from the oauth.to_json() method. """ #If we have a string, then decode it, otherwise assume it's already decoded if isinstance(json_data, str): data = json.loads(json_data) el...
Returns a pyalveo.OAuth2 given a json string built from the oauth.to_json() method.
def headers(self): ''' An instance of :class:`HeaderDict`, a case-insensitive dict-like view on the response headers. ''' self.__dict__['headers'] = hdict = HeaderDict() hdict.dict = self._headers return hdict
An instance of :class:`HeaderDict`, a case-insensitive dict-like view on the response headers.
def extract_first_jpeg_in_pdf(fstream): """ Reads a given PDF file and scans for the first valid embedded JPEG image. Returns either None (if none found) or a string of data for the image. There is no 100% guarantee for this code, yet it seems to work fine with most scanner-produced images around. ...
Reads a given PDF file and scans for the first valid embedded JPEG image. Returns either None (if none found) or a string of data for the image. There is no 100% guarantee for this code, yet it seems to work fine with most scanner-produced images around. More testing might be needed though. Note th...
def load(self, filename=None): """ load runtime configuration from given filename. If filename is None try to read from default file from default location. """ if not filename: filename = self.default_config_file files = self._cfgs_to_read() # insert last, so...
load runtime configuration from given filename. If filename is None try to read from default file from default location.
def _connect(self, config): """Establish a connection with a MySQL database.""" if 'connection_timeout' not in self._config: self._config['connection_timeout'] = 480 try: self._cnx = connect(**config) self._cursor = self._cnx.cursor() self._printer...
Establish a connection with a MySQL database.
def copy_file( host, file_path, remote_path='.', username=None, key_path=None, action='put' ): """ Copy a file via SCP, proxied through the mesos master :param host: host or IP of the machine to execute the command on :type host: str :param fi...
Copy a file via SCP, proxied through the mesos master :param host: host or IP of the machine to execute the command on :type host: str :param file_path: the local path to the file to be copied :type file_path: str :param remote_path: the remote path to copy the file to :...
def picard_index_ref(picard, ref_file): """Provide a Picard style dict index file for a reference genome. """ dict_file = "%s.dict" % os.path.splitext(ref_file)[0] if not file_exists(dict_file): with file_transaction(picard._config, dict_file) as tx_dict_file: opts = [("REFERENCE", r...
Provide a Picard style dict index file for a reference genome.
def add_file_dep(self, doc, value): """Raises OrderError if no package or file defined. """ if self.has_package(doc) and self.has_file(doc): self.file(doc).add_depend(value) else: raise OrderError('File::Dependency')
Raises OrderError if no package or file defined.
def _get_kvc(kv_arg): '''Returns a tuple keys, values, count for kv_arg (which can be a dict or a tuple containing keys, values and optinally count.''' if isinstance(kv_arg, Mapping): return six.iterkeys(kv_arg), six.itervalues(kv_arg), len(kv_arg) assert 2 <= len(kv_arg) <= 3, \ 'Ar...
Returns a tuple keys, values, count for kv_arg (which can be a dict or a tuple containing keys, values and optinally count.
def check_entry_points(dist, attr, value): """Verify that entry_points map is parseable""" try: pkg_resources.EntryPoint.parse_map(value) except ValueError, e: raise DistutilsSetupError(e)
Verify that entry_points map is parseable
def get_repository_state(self, relaPath=None): """ Get a list representation of repository state along with useful information. List state is ordered relativeley to directories level :Parameters: #. relaPath (None, str): relative directory path from where to s...
Get a list representation of repository state along with useful information. List state is ordered relativeley to directories level :Parameters: #. relaPath (None, str): relative directory path from where to start. If None all repository representation is returned. :...
def toDict(self): """ Get information about the HSP as a dictionary. @return: A C{dict} representation of the HSP. """ result = _Base.toDict(self) result['score'] = self.score.score return result
Get information about the HSP as a dictionary. @return: A C{dict} representation of the HSP.
def get_template(self, project, template_id): """GetTemplate. Gets a specific build definition template. :param str project: Project ID or project name :param str template_id: The ID of the requested template. :rtype: :class:`<BuildDefinitionTemplate> <azure.devops.v5_0.build.mod...
GetTemplate. Gets a specific build definition template. :param str project: Project ID or project name :param str template_id: The ID of the requested template. :rtype: :class:`<BuildDefinitionTemplate> <azure.devops.v5_0.build.models.BuildDefinitionTemplate>`
def add_source(zone, source, permanent=True): ''' Bind a source to a zone .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' firewalld.add_source zone 192.168.1.0/24 ''' if source in get_sources(zone, permanent): log.info('Source is already bound to zon...
Bind a source to a zone .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' firewalld.add_source zone 192.168.1.0/24
def delete(self, block_type, block_num): """ Deletes a block :param block_type: Type of block :param block_num: Bloc number """ logger.info("deleting block") blocktype = snap7.snap7types.block_types[block_type] result = self.library.Cli_Delete(sel...
Deletes a block :param block_type: Type of block :param block_num: Bloc number
def listen_error_messages_raylet(worker, task_error_queue, threads_stopped): """Listen to error messages in the background on the driver. This runs in a separate thread on the driver and pushes (error, time) tuples to the output queue. Args: worker: The worker class that this thread belongs to...
Listen to error messages in the background on the driver. This runs in a separate thread on the driver and pushes (error, time) tuples to the output queue. Args: worker: The worker class that this thread belongs to. task_error_queue (queue.Queue): A queue used to communicate with the ...
def instance(cls): """ Singleton to return only one instance of BaseManager. :returns: instance of BaseManager """ if not hasattr(cls, "_instance") or cls._instance is None: cls._instance = cls() return cls._instance
Singleton to return only one instance of BaseManager. :returns: instance of BaseManager
def stats(self): """Return dictionay with all stats at this level.""" load_count = self.last_level_load.MISS_count load_byte = self.last_level_load.MISS_byte if self.last_level_load.victims_to is not None: # If there is a victim cache between last_level and memory, subtract ...
Return dictionay with all stats at this level.
def inspect(self): """ Inspect access attempt, used for catpcha flow :return: """ last_attempt = self.get_last_failed_access_attempt( ip_address=self.ip, captcha_enabled=True, captcha_passed=False, is_expired=False ) ...
Inspect access attempt, used for catpcha flow :return:
def structure(self, obj, cl): # type: (Any, Type[T]) -> T """Convert unstructured Python data structures to structured data.""" return self._structure_func.dispatch(cl)(obj, cl)
Convert unstructured Python data structures to structured data.
def _ProcessGrepSource(self, source): """Find files fulfilling regex conditions.""" attributes = source.base_source.attributes paths = artifact_utils.InterpolateListKbAttributes( attributes["paths"], self.knowledge_base, self.ignore_interpolation_errors) regex = utils.RegexListDisjunctio...
Find files fulfilling regex conditions.
def bll_version(self): """Get the BLL version this session is connected to. Return: Version string if session started. None if session not started. """ if not self.started(): return None status, data = self._rest.get_request('objects', 'system1', ...
Get the BLL version this session is connected to. Return: Version string if session started. None if session not started.
def get_serializer(name): ''' Return the serialize function. ''' try: log.debug('Using %s as serializer', name) return SERIALIZER_LOOKUP[name] except KeyError: msg = 'Serializer {} is not available'.format(name) log.error(msg, exc_info=True) raise InvalidSeria...
Return the serialize function.
def generate_changelog(from_version: str, to_version: str = None) -> dict: """ Generates a changelog for the given version. :param from_version: The last version not in the changelog. The changelog will be generated from the commit after this one. :param to_version: The last ve...
Generates a changelog for the given version. :param from_version: The last version not in the changelog. The changelog will be generated from the commit after this one. :param to_version: The last version in the changelog. :return: a dict with different changelog sections
def reverse_taskname(name: str) -> str: """ Reverses components in the name of task. Reversed convention is used for filenames since it groups log/scratch files of related tasks together 0.somejob.somerun -> somerun.somejob.0 0.somejob -> somejob.0 somename -> somename Args: name: name of task ""...
Reverses components in the name of task. Reversed convention is used for filenames since it groups log/scratch files of related tasks together 0.somejob.somerun -> somerun.somejob.0 0.somejob -> somejob.0 somename -> somename Args: name: name of task
def _validate_columns(self): """Validate the options in the styles""" geom_cols = {'the_geom', 'the_geom_webmercator', } col_overlap = set(self.style_cols) & geom_cols if col_overlap: raise ValueError('Style columns cannot be geometry ' 'columns. ...
Validate the options in the styles
def nested_assign(self, key_list, value): """ Set the value of nested LIVVDicts given a list """ if len(key_list) == 1: self[key_list[0]] = value elif len(key_list) > 1: if key_list[0] not in self: self[key_list[0]] = LIVVDict() self[key_list[0...
Set the value of nested LIVVDicts given a list
def _prepare_text(self, text): """Returns `text` with each consituent token wrapped in HTML markup for later match annotation. :param text: text to be marked up :type text: `str` :rtype: `str` """ # Remove characters that should be escaped for XML input (but ...
Returns `text` with each consituent token wrapped in HTML markup for later match annotation. :param text: text to be marked up :type text: `str` :rtype: `str`
def get_diff(self, rev1, rev2, path='', ignore_whitespace=False, context=3): """ Returns (git like) *diff*, as plain text. Shows changes introduced by ``rev2`` since ``rev1``. :param rev1: Entry point from which diff is shown. Can be ``self.EMPTY_CHANGESET`` ...
Returns (git like) *diff*, as plain text. Shows changes introduced by ``rev2`` since ``rev1``. :param rev1: Entry point from which diff is shown. Can be ``self.EMPTY_CHANGESET`` - in this case, patch showing all the changes since empty state of the repository until ``rev2`` ...
async def deserialize(data: dict): """ Create the object from a previously serialized object. :param data: The output of the "serialize" call Example: data = await connection1.serialize() connection2 = await Connection.deserialize(data) :return: A re-instantiated...
Create the object from a previously serialized object. :param data: The output of the "serialize" call Example: data = await connection1.serialize() connection2 = await Connection.deserialize(data) :return: A re-instantiated object
def issuer_cert_urls(self): """ :return: A list of unicode strings that are URLs that should contain either an individual DER-encoded X.509 certificate, or a DER-encoded CMS message containing multiple certificates """ if self._issuer_cert_urls is Non...
:return: A list of unicode strings that are URLs that should contain either an individual DER-encoded X.509 certificate, or a DER-encoded CMS message containing multiple certificates
def create(self, **kwargs): """ Creates a new object with the given kwargs, saving it to the database and returning the created object. """ obj = self.model(**kwargs) meta = obj.get_meta() meta.connection = get_es_connection(self.es_url, self.es_kwargs) me...
Creates a new object with the given kwargs, saving it to the database and returning the created object.
def validate(self, value): """validate""" # obj can be None or a DataFrame if value is None: return True else: try: with value.open() as hdulist: self.validate_hdulist(hdulist) except Exception: _type...
validate
def custom(command, user=None, conf_file=None, bin_env=None): ''' Run any custom supervisord command user user to run supervisorctl as conf_file path to supervisord config file bin_env path to supervisorctl bin or path to virtualenv with supervisor installed CLI...
Run any custom supervisord command user user to run supervisorctl as conf_file path to supervisord config file bin_env path to supervisorctl bin or path to virtualenv with supervisor installed CLI Example: .. code-block:: bash salt '*' supervisord.custom "...
def send_message(message, params, site, logger): """Send a message to the Sentry server""" client.capture( 'Message', message=message, params=tuple(params), data={ 'site': site, 'logger': logger, }, )
Send a message to the Sentry server
async def _start(self): """ Start coroutine. runs on_start coroutine and then runs the _step coroutine where the body of the behaviour is called. """ self.agent._alive.wait() try: await self.on_start() except Exception as e: logger....
Start coroutine. runs on_start coroutine and then runs the _step coroutine where the body of the behaviour is called.
def p_out(p): """ statement : OUT expr COMMA expr """ p[0] = make_sentence('OUT', make_typecast(TYPE.uinteger, p[2], p.lineno(3)), make_typecast(TYPE.ubyte, p[4], p.lineno(4)))
statement : OUT expr COMMA expr
def update_rho(self, k, r, s): """Automatic rho adjustment.""" if self.opt['AutoRho', 'Enabled']: tau = self.rho_tau mu = self.rho_mu xi = self.rho_xi if k != 0 and np.mod(k + 1, self.opt['AutoRho', 'Period']) == 0: if self.opt['AutoRho', ...
Automatic rho adjustment.
def database_renderer(self, name=None, site=None, role=None): """ Renders local settings for a specific database. """ name = name or self.env.default_db_name site = site or self.genv.SITE role = role or self.genv.ROLE key = (name, site, role) self.vpri...
Renders local settings for a specific database.
def create_event(component, tz=UTC): """ Create an event from its iCal representation. :param component: iCal component :param tz: timezone for start and end times :return: event """ event = Event() event.start = normalize(component.get('dtstart').dt, tz=tz) if component.get(...
Create an event from its iCal representation. :param component: iCal component :param tz: timezone for start and end times :return: event
def N_to_Ntriangles(N): """ @N: WD style gridsize Converts WD style grid size @N to the number of triangles on the surface. Returns: number of triangles. """ theta = np.array([np.pi/2*(k-0.5)/N for k in range(1, N+1)]) phi = np.array([[np.pi*(l-0.5)/Mk for l in range(1, Mk+1)] for Mk ...
@N: WD style gridsize Converts WD style grid size @N to the number of triangles on the surface. Returns: number of triangles.
def list_storages(self): '''Returns a list of existing stores. The returned names can then be used to call get_storage(). ''' # Filter out any storages used by xbmcswift2 so caller doesn't corrupt # them. return [name for name in os.listdir(self.storage_path) ...
Returns a list of existing stores. The returned names can then be used to call get_storage().
def write_matrix_to_csv(self, headers, data): """Saves .csv file with data :param headers: column names :param data: Data """ with open(self.path, "w") as out_file: # write to file data_writer = csv.writer(out_file, delimiter=",") data_writer.writerow(he...
Saves .csv file with data :param headers: column names :param data: Data
def pybel_to_json(molecule, name=None): """Converts a pybel molecule to json. Args: molecule: An instance of `pybel.Molecule` name: (Optional) If specified, will save a "name" property Returns: A Python dictionary containing atom and bond data """ # Save atom element type and...
Converts a pybel molecule to json. Args: molecule: An instance of `pybel.Molecule` name: (Optional) If specified, will save a "name" property Returns: A Python dictionary containing atom and bond data
def start(self): ''' doesn't work''' thread = threading.Thread(target=reactor.run) thread.start()
doesn't work
def solve(self): ''' Solves a one period consumption saving problem with risky income and shocks to medical need. Parameters ---------- None Returns ------- solution : ConsumerSolution The solution to the one period problem, including...
Solves a one period consumption saving problem with risky income and shocks to medical need. Parameters ---------- None Returns ------- solution : ConsumerSolution The solution to the one period problem, including a consumption function, ...
def removeStages(self, personID): """remove(string) Removes all stages of the person. If no new phases are appended, the person will be removed from the simulation in the next simulationStep(). """ # remove all stages after the current and then abort the current stage whi...
remove(string) Removes all stages of the person. If no new phases are appended, the person will be removed from the simulation in the next simulationStep().
def ReportConfiguration(self, f): """Report the boundary configuration details :param f: File (or standard out/err) :return: None """ if BoundaryCheck.chrom != -1: print >> f, BuildReportLine("CHROM", BoundaryCheck.chrom) if len(self.start_bounds) > 0: ...
Report the boundary configuration details :param f: File (or standard out/err) :return: None
def getCSD (lfps,sampr,minf=0.05,maxf=300,norm=True,vaknin=False,spacing=1.0): """ get current source density approximation using set of local field potentials with equidistant spacing first performs a lowpass filter lfps is a list or numpy array of LFPs arranged spatially by column spacing is in microns ...
get current source density approximation using set of local field potentials with equidistant spacing first performs a lowpass filter lfps is a list or numpy array of LFPs arranged spatially by column spacing is in microns
def get_ngroups(self, field=None): ''' Returns ngroups count if it was specified in the query, otherwise ValueError. If grouping on more than one field, provide the field argument to specify which count you are looking for. ''' field = field if field else self._determine_group_f...
Returns ngroups count if it was specified in the query, otherwise ValueError. If grouping on more than one field, provide the field argument to specify which count you are looking for.
def _GetComplexConjugateArray(Array): """ Calculates the complex conjugate of each element in an array and returns the resulting array. Parameters ---------- Array : ndarray Input array Returns ------- ConjArray : ndarray The complex conjugate of the input array. ""...
Calculates the complex conjugate of each element in an array and returns the resulting array. Parameters ---------- Array : ndarray Input array Returns ------- ConjArray : ndarray The complex conjugate of the input array.
def generate_random_schema(valid): """ Generate a random plain schema, and a sample generation function. :param valid: Generate valid samples? :type valid: bool :returns: schema, sample-generator :rtype: *, generator """ schema_type = choice(['literal', 'type']) if schema_type == 'lite...
Generate a random plain schema, and a sample generation function. :param valid: Generate valid samples? :type valid: bool :returns: schema, sample-generator :rtype: *, generator
def dt_day(x): """Extracts the day from a datetime sample. :returns: an expression containing the day extracted from a datetime column. Example: >>> import vaex >>> import numpy as np >>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime6...
Extracts the day from a datetime sample. :returns: an expression containing the day extracted from a datetime column. Example: >>> import vaex >>> import numpy as np >>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64) >>> df = vaex.f...
def save_file(self, path=None, filters='*.dat', force_extension=None, force_overwrite=False, header_only=False, delimiter='use current', binary=None): """ This will save all the header info and columns to an ascii file with the specified path. Parameters ---------- path=...
This will save all the header info and columns to an ascii file with the specified path. Parameters ---------- path=None Path for saving the data. If None, this will bring up a save file dialog. filters='*.dat' File filter for the fil...
def parse_expr(e): """Parse a single constraint expression. Legal expressions are defined by the regular expression `relation_re`. :param e: Expression :type e: str :return: Tuple of field, operator, and value :rtype: tuple """ m = relation_re.match(e) if m is None: raise V...
Parse a single constraint expression. Legal expressions are defined by the regular expression `relation_re`. :param e: Expression :type e: str :return: Tuple of field, operator, and value :rtype: tuple
def pool(args): """ %prog pool fastafiles > pool.fasta Pool a bunch of FASTA files, and add prefix to each record based on filenames. File names are simplified to longest unique prefix to avoid collisions after getting shortened. """ from jcvi.formats.base import longest_unique_prefix ...
%prog pool fastafiles > pool.fasta Pool a bunch of FASTA files, and add prefix to each record based on filenames. File names are simplified to longest unique prefix to avoid collisions after getting shortened.
def _set_client_pw(self, v, load=False): """ Setter method for client_pw, mapped from YANG variable /cluster/client_pw (container) If this variable is read-only (config: false) in the source YANG file, then _set_client_pw is considered as a private method. Backends looking to populate this variable ...
Setter method for client_pw, mapped from YANG variable /cluster/client_pw (container) If this variable is read-only (config: false) in the source YANG file, then _set_client_pw is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_client_pw()...
def load_requires_from_file(filepath): """Read a package list from a given file path. Args: filepath: file path of the package list. Returns: a list of package names. """ with open(filepath) as fp: return [pkg_name.strip() for pkg_name in fp.readlines()]
Read a package list from a given file path. Args: filepath: file path of the package list. Returns: a list of package names.
def insert_completions(self, e): # (M-*) u"""Insert all completions of the text before point that would have been generated by possible-completions.""" completions = self._get_completions() b = self.begidx e = self.endidx for comp in completions: rep = ...
u"""Insert all completions of the text before point that would have been generated by possible-completions.
def addStream(self, stream, interpolator="closest", t1=None, t2=None, dt=None, limit=None, i1=None, i2=None, transform=None,colname=None): """Adds the given stream to the query construction. Additionally, you can choose the interpolator to use for this stream, as well as a special name for the column in...
Adds the given stream to the query construction. Additionally, you can choose the interpolator to use for this stream, as well as a special name for the column in the returned dataset. If no column name is given, the full stream path will be used. addStream also supports Merge queries. You can insert a...
def _check_file(parameters): """Return list of errors.""" (filename, args) = parameters if filename == '-': contents = sys.stdin.read() else: with contextlib.closing( docutils.io.FileInput(source_path=filename) ) as input_file: contents = input_file.read(...
Return list of errors.
def parse_complex_fault_node(node, mfd_spacing=0.1, mesh_spacing=4.0): """ Parses a "complexFaultSource" node and returns an instance of the :class: openquake.hmtk.sources.complex_fault.mtkComplexFaultSource """ assert "complexFaultSource" in node.tag sf_taglist = get_taglist(node) # Get met...
Parses a "complexFaultSource" node and returns an instance of the :class: openquake.hmtk.sources.complex_fault.mtkComplexFaultSource
def from_dict(self, d): """ Create a Stage from a dictionary. The change is in inplace. :argument: python dictionary :return: None """ if 'uid' in d: if d['uid']: self._uid = d['uid'] if 'name' in d: if d['name']: ...
Create a Stage from a dictionary. The change is in inplace. :argument: python dictionary :return: None
def gaussian_kernel(data_shape, sigma, norm='max'): r"""Gaussian kernel This method produces a Gaussian kerenal of a specified size and dispersion Parameters ---------- data_shape : tuple Desiered shape of the kernel sigma : float Standard deviation of the kernel norm : str...
r"""Gaussian kernel This method produces a Gaussian kerenal of a specified size and dispersion Parameters ---------- data_shape : tuple Desiered shape of the kernel sigma : float Standard deviation of the kernel norm : str {'max', 'sum', 'none'}, optional Normalisation ...
def _get_switchports(profile): """Return list of (switch_ip, interface) tuples from local_link_info""" switchports = [] if profile.get('local_link_information'): for link in profile['local_link_information']: if 'switch_info' in link and 'port_id' in link: ...
Return list of (switch_ip, interface) tuples from local_link_info
def write_results(filename,config,srcfile,samples): """ Package everything nicely """ results = createResults(config,srcfile,samples=samples) results.write(filename)
Package everything nicely
def ustep(self): """The parent class ystep method is overridden to allow also performing the ystep for the additional variables introduced in the modification to the baseline algorithm. """ super(ConvCnstrMODMaskDcpl_Consensus, self).ustep() self.U1 += self.AX1 - self.Y1...
The parent class ystep method is overridden to allow also performing the ystep for the additional variables introduced in the modification to the baseline algorithm.
def enqueue_task(self, source, *args): """ Enqueue a task execution. It will run in the background as soon as the coordinator clears it to do so. """ yield from self.cell.coord.enqueue(self) route = Route(source, self.cell, self.spec, self.emit) self.cell.loop.create_task(self.c...
Enqueue a task execution. It will run in the background as soon as the coordinator clears it to do so.
def _call(self, x, out=None): """Return the constant vector or assign it to ``out``.""" if out is None: return self.range.element(copy(self.constant)) else: out.assign(self.constant)
Return the constant vector or assign it to ``out``.
def trigger_audited(self, id, rev, **kwargs): """ Triggers a build of a specific Build Configuration in a specific revision This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked wh...
Triggers a build of a specific Build Configuration in a specific revision This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(respo...
def print_head(self, parent_plate_value, plate_values, interval, n=10, print_func=logging.info): """ Print the first n values from the streams in the given time interval. The parent plate value is the value of the parent plate, and then the plate values are the values for the plate that ...
Print the first n values from the streams in the given time interval. The parent plate value is the value of the parent plate, and then the plate values are the values for the plate that are to be printed. e.g. print_head(None, ("house", "1")) :param parent_plate_value: The (fixed) pare...