code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def green(fn=None, consume_green_mode=True): """Make a function green. Can be used as a decorator.""" def decorator(fn): @wraps(fn) def greener(obj, *args, **kwargs): args = (obj,) + args wait = kwargs.pop('wait', None) timeout = kwargs.pop('timeout', None) ...
Make a function green. Can be used as a decorator.
def get(self, measurementId): """ Analyses the measurement with the given parameters :param measurementId: :return: """ logger.info('Loading raw data for ' + measurementId) measurement = self._measurementController.getMeasurement(measurementId, MeasurementStatus.C...
Analyses the measurement with the given parameters :param measurementId: :return:
def _handle_sub_action(self, input_dict, handler): """ Handles resolving replacements in the Sub action based on the handler that is passed as an input. :param input_dict: Dictionary to be resolved :param supported_values: One of several different objects that contain the supported valu...
Handles resolving replacements in the Sub action based on the handler that is passed as an input. :param input_dict: Dictionary to be resolved :param supported_values: One of several different objects that contain the supported values that need to be changed. See each method above for speci...
def search(self, **kwargs): """ Method to search neighbors based on extends search. :param search: Dict containing QuerySets to find neighbors. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. ...
Method to search neighbors based on extends search. :param search: Dict containing QuerySets to find neighbors. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. :param fields: Array containing fields to over...
def namedb_create(path, genesis_block): """ Create a sqlite3 db at the given path. Create all the tables and indexes we need. """ global BLOCKSTACK_DB_SCRIPT if os.path.exists( path ): raise Exception("Database '%s' already exists" % path) lines = [l + ";" for l in BLOCKSTACK_DB_S...
Create a sqlite3 db at the given path. Create all the tables and indexes we need.
def generate_id_name_map(sdk, reverse=False): """ Generate the ID-NAME map dict :param sdk: CloudGenix API constructor :param reverse: Generate reverse name-> ID map as well, return tuple with both. :return: ID Name dictionary """ global_id_name_dict = {} global_name_id_dict = {} #...
Generate the ID-NAME map dict :param sdk: CloudGenix API constructor :param reverse: Generate reverse name-> ID map as well, return tuple with both. :return: ID Name dictionary
def qs(schema): """ Decorate a function with a query string schema. """ def wrapper(func): setattr(func, QS, schema) return func return wrapper
Decorate a function with a query string schema.
def fractional(value): ''' There will be some cases where one might not want to show ugly decimal places for floats and decimals. This function returns a human readable fractional number in form of fractions and mixed fractions. Pass in a string, or a number or a float, and this function...
There will be some cases where one might not want to show ugly decimal places for floats and decimals. This function returns a human readable fractional number in form of fractions and mixed fractions. Pass in a string, or a number or a float, and this function returns a string represent...
def _GetDiscoveryDocFromFlags(args): """Get the discovery doc from flags.""" if args.discovery_url: try: return util.FetchDiscoveryDoc(args.discovery_url) except exceptions.CommunicationError: raise exceptions.GeneratedClientError( 'Could not fetch discove...
Get the discovery doc from flags.
def get_trace(self, frame, tb): """Get a dict of the traceback for wdb.js use""" import linecache frames = [] stack, _ = self.get_stack(frame, tb) current = 0 for i, (stack_frame, lno) in enumerate(stack): code = stack_frame.f_code filename = code...
Get a dict of the traceback for wdb.js use
def setref(graphtable=None, comptable=None, thermtable=None, area=None, waveset=None): """Set default graph and component tables, primary area, and wavelength set. This is similar to setting ``refdata`` in IRAF STSDAS SYNPHOT. If all parameters set to `None`, they are reverted to software de...
Set default graph and component tables, primary area, and wavelength set. This is similar to setting ``refdata`` in IRAF STSDAS SYNPHOT. If all parameters set to `None`, they are reverted to software default. If any of the parameters are not `None`, they are set to desired values while the rest (if...
def _resolve_input(variable, variable_name, config_key, config): """ Resolve input entered as option values with config values If option values are provided (passed in as `variable`), then they are returned unchanged. If `variable` is None, then we first look for a config value to use. If no ...
Resolve input entered as option values with config values If option values are provided (passed in as `variable`), then they are returned unchanged. If `variable` is None, then we first look for a config value to use. If no config value is found, then raise an error. Parameters ---------- ...
def view_packages(self, *args): """:View slackbuild packages with version and arch args[0] package color args[1] package args[2] version args[3] arch """ ver = GetFromInstalled(args[1]).version() print(" {0}{1}{2}{3} {4}{5} {6}{7}{8}{9}{10}{11:>11}{12}".f...
:View slackbuild packages with version and arch args[0] package color args[1] package args[2] version args[3] arch
def _mark_image_file_deleted(cls, mapper, connection, target): """When the session flushes, marks images as deleted. The files of this marked images will be actually deleted in the image storage when the ongoing transaction succeeds. If it fails the :attr:`_deleted_images` queue will be ...
When the session flushes, marks images as deleted. The files of this marked images will be actually deleted in the image storage when the ongoing transaction succeeds. If it fails the :attr:`_deleted_images` queue will be just empty.
def pivot(self): """ transposes rows and columns """ self.op_data = [list(i) for i in zip(*self.ip_data)]
transposes rows and columns
def fill_view(self, view): """ Fill this histogram from a view of another histogram """ other = view.hist _other_x_center = other.axis(0).GetBinCenter _other_y_center = other.axis(1).GetBinCenter _other_z_center = other.axis(2).GetBinCenter _other_get = ot...
Fill this histogram from a view of another histogram
def total_branches(self): """How many total branches are there?""" exit_counts = self.parser.exit_counts() return sum([count for count in exit_counts.values() if count > 1])
How many total branches are there?
def call_fn(fn: TransitionOperator, args: Union[Tuple[Any], Any]) -> Any: """Calls a transition operator with args, unpacking args if its a sequence. Args: fn: A `TransitionOperator`. args: Arguments to `fn` Returns: ret: Return value of `fn`. """ if isinstance(args, (list, tuple)) and not mcmc...
Calls a transition operator with args, unpacking args if its a sequence. Args: fn: A `TransitionOperator`. args: Arguments to `fn` Returns: ret: Return value of `fn`.
def identify_needed_data(curr_exe_job, link_job_instance=None): """ This function will identify the length of data that a specific executable needs to analyse and what part of that data is valid (ie. inspiral doesn't analyse the first or last 64+8s of data it reads in). In addition you can supply a sec...
This function will identify the length of data that a specific executable needs to analyse and what part of that data is valid (ie. inspiral doesn't analyse the first or last 64+8s of data it reads in). In addition you can supply a second job instance to "link" to, which will ensure that the two jobs w...
def find_out_var(self, varnames=[]): """ This function will read the standard out of the program, catch variables and return the values EG. #varname=value """ if self.wdir != '': stdout = "%s/%s"%(self.wdir, self.stdout) else: stdout = self.stdout res...
This function will read the standard out of the program, catch variables and return the values EG. #varname=value
def handle(self): """ Executes the command. """ database = self.option("database") self.resolver.set_default_connection(database) repository = DatabaseMigrationRepository(self.resolver, "migrations") migrator = Migrator(repository, self.resolver) if no...
Executes the command.
def rate_of_return(period_ret, base_period): """ Convert returns to 'one_period_len' rate of returns: that is the value the returns would have every 'one_period_len' if they had grown at a steady rate Parameters ---------- period_ret: pd.DataFrame DataFrame containing returns values...
Convert returns to 'one_period_len' rate of returns: that is the value the returns would have every 'one_period_len' if they had grown at a steady rate Parameters ---------- period_ret: pd.DataFrame DataFrame containing returns values with column headings representing the return per...
def read(self, size=-1): """! @brief Return bytes read from the connection.""" if self.connected is None: return None # Extract requested amount of data from the read buffer. data = self._get_input(size) return data
! @brief Return bytes read from the connection.
def find_or_graft(self, board): """Build a tree with each level corresponding to a fixed position on board. A path of tiles is stored for each board. If any two boards have the same path, then they are the same board. If there is any difference, a new branch will be created to store that...
Build a tree with each level corresponding to a fixed position on board. A path of tiles is stored for each board. If any two boards have the same path, then they are the same board. If there is any difference, a new branch will be created to store that path. Return: True if board alrea...
def InitUI(self): """ initialize window """ self.main_sizer = wx.BoxSizer(wx.VERTICAL) self.init_grid_headers() self.grid_builder = GridBuilder(self.er_magic, self.grid_type, self.grid_headers, self.panel, self.parent_type) ...
initialize window
def code_from_ipynb(nb, markdown=False): """ Get the code for a given notebook nb is passed in as a dictionary that's a parsed ipynb file """ code = PREAMBLE for cell in nb['cells']: if cell['cell_type'] == 'code': # transform the input to executable Python code ...
Get the code for a given notebook nb is passed in as a dictionary that's a parsed ipynb file
def animation_dialog(images, delay_s=1., loop=True, **kwargs): ''' .. versionadded:: v0.19 Parameters ---------- images : list Filepaths to images or :class:`gtk.Pixbuf` instances. delay_s : float, optional Number of seconds to display each frame. Default: ``1.0``. ...
.. versionadded:: v0.19 Parameters ---------- images : list Filepaths to images or :class:`gtk.Pixbuf` instances. delay_s : float, optional Number of seconds to display each frame. Default: ``1.0``. loop : bool, optional If ``True``, restart animation after last ima...
def write_puml(self, filename=''): """ Writes PUML from the system. If filename is given, stores result in the file. Otherwise returns result as a string. """ def get_type(o): type = 'program' if isinstance(o, AbstractSensor): type ...
Writes PUML from the system. If filename is given, stores result in the file. Otherwise returns result as a string.
def encrypt(passwd): """ Encrypts the incoming password after adding some salt to store it in the database. @param passwd: password portion of user credentials @type passwd: string @returns: encrypted/salted string """ m = sha1() salt = hexlify(os.urandom(salt_len)) m.update(un...
Encrypts the incoming password after adding some salt to store it in the database. @param passwd: password portion of user credentials @type passwd: string @returns: encrypted/salted string
def find_first_file_with_ext(base_paths, prefix, exts): """Runs through the given list of file extensions and returns the first file with the given base path and extension combination that actually exists. Args: base_paths: The base paths in which to search for files. prefix: The filename p...
Runs through the given list of file extensions and returns the first file with the given base path and extension combination that actually exists. Args: base_paths: The base paths in which to search for files. prefix: The filename prefix of the file for which to search. exts: An ordered...
def update(self, dt): """Update the shape's position by moving it forward according to its velocity. Parameters ---------- dt : float """ self.translate(dt * self.velocity) self.rotate(dt * self.angular_velocity)
Update the shape's position by moving it forward according to its velocity. Parameters ---------- dt : float
def parse_bug_activity(raw_html): """Parse a Bugzilla bug activity HTML stream. This method extracts the information about activity from the given HTML stream. The bug activity is stored into a HTML table. Each parsed activity event is returned into a dictionary. If the given H...
Parse a Bugzilla bug activity HTML stream. This method extracts the information about activity from the given HTML stream. The bug activity is stored into a HTML table. Each parsed activity event is returned into a dictionary. If the given HTML is invalid, the method will raise a Parse...
def respond(self, output): """Generates server response.""" response = {'exit_code': output.code, 'command_output': output.log} self.send_response(200) self.send_header('Content-type', 'application/json') self.end_headers() self.wfile.write(bytes(js...
Generates server response.
def V(self, brightest=False): """ http://www.aerith.net/astro/color_conversion.html """ mags = self.get_photometry(brightest=brightest, convert=False) VT, dVT = mags['VT'] BT, dBT = mags['BT'] if (-0.25 < BT - VT < 2.0): (a, b, c, d) = (0.00097, 0.1334...
http://www.aerith.net/astro/color_conversion.html
def extend(self, *args, **kwargs): """Generic import function for any type of header-like object. Adapted version of MutableMapping.update in order to insert items with self.add instead of self.__setitem__ """ if len(args) > 1: raise TypeError("extend() takes at most ...
Generic import function for any type of header-like object. Adapted version of MutableMapping.update in order to insert items with self.add instead of self.__setitem__
def isclose(a, b, rtol=4*np.finfo(float).eps, atol=0.0, equal_nan=False): """ Returns a boolean array where two arrays are element-wise equal within a tolerance. This function is essentially a copy of the `numpy.isclose` function, with different default tolerances and one minor changes necessary to...
Returns a boolean array where two arrays are element-wise equal within a tolerance. This function is essentially a copy of the `numpy.isclose` function, with different default tolerances and one minor changes necessary to deal correctly with quaternions. The tolerance values are positive, typicall...
def create(cls, second_line, name_on_card, alias=None, type_=None, pin_code_assignment=None, monetary_account_id_fallback=None, custom_headers=None): """ Create a new debit card request. :type user_id: int :param second_line: The second line of text on the ...
Create a new debit card request. :type user_id: int :param second_line: The second line of text on the card, used as name/description for it. It can contain at most 17 characters and it can be empty. :type second_line: str :param name_on_card: The user's name as it will ...
def H(self, phase, T): """ Calculate the enthalpy of a phase of the compound at a specified temperature. :param phase: A phase of the compound, e.g. 'S', 'L', 'G'. :param T: [K] temperature :returns: [J/mol] Enthalpy. """ try: return self._p...
Calculate the enthalpy of a phase of the compound at a specified temperature. :param phase: A phase of the compound, e.g. 'S', 'L', 'G'. :param T: [K] temperature :returns: [J/mol] Enthalpy.
def add_entity(self): ''' Add the entity. All the information got from the post data. ''' post_data = self.get_post_data() if 'kind' in post_data: if post_data['kind'] == '1': self.add_pic(post_data) elif post_data['kind'] == '2': ...
Add the entity. All the information got from the post data.
def __construct_claim_json(self): """ Writes the properties from self.data to a new or existing json in self.wd_json_representation :return: None """ def handle_qualifiers(old_item, new_item): if not new_item.check_qualifier_equality: old_item.set_qua...
Writes the properties from self.data to a new or existing json in self.wd_json_representation :return: None
def isNonPairTag(self, isnonpair=None): """ True if element is listed in nonpair tag table (``br`` for example) or if it ends with ``/>`` (``<hr />`` for example). You can also change state from pair to nonpair if you use this as setter. Args: isnonpair (boo...
True if element is listed in nonpair tag table (``br`` for example) or if it ends with ``/>`` (``<hr />`` for example). You can also change state from pair to nonpair if you use this as setter. Args: isnonpair (bool, default None): If set, internal nonpair state is ...
def save(self, sc, path): """ Save this model to the given path. """ java_model = sc._jvm.org.apache.spark.mllib.classification.LogisticRegressionModel( _py2java(sc, self._coeff), self.intercept, self.numFeatures, self.numClasses) java_model.save(sc._jsc.sc(), path)
Save this model to the given path.
def get_rup_array(ebruptures, srcfilter=nofilter): """ Convert a list of EBRuptures into a numpy composite array, by filtering out the ruptures far away from every site """ if not BaseRupture._code: BaseRupture.init() # initialize rupture codes rups = [] geoms = [] nbytes = 0 ...
Convert a list of EBRuptures into a numpy composite array, by filtering out the ruptures far away from every site
def fixed_poch(a, n): """Implementation of the Pochhammer symbol :math:`(a)_n` which handles negative integer arguments properly. Need conditional statement because scipy's impelementation of the Pochhammer symbol is wrong for negative integer arguments. This function uses the definition from h...
Implementation of the Pochhammer symbol :math:`(a)_n` which handles negative integer arguments properly. Need conditional statement because scipy's impelementation of the Pochhammer symbol is wrong for negative integer arguments. This function uses the definition from http://functions.wolfram.com/G...
def calculate_start_time(df): """Calculate the star_time per read. Time data is either a "time" (in seconds, derived from summary files) or a "timestamp" (in UTC, derived from fastq_rich format) and has to be converted appropriately in a datetime format time_arr For both the time_zero is the m...
Calculate the star_time per read. Time data is either a "time" (in seconds, derived from summary files) or a "timestamp" (in UTC, derived from fastq_rich format) and has to be converted appropriately in a datetime format time_arr For both the time_zero is the minimal value of the time_arr, whi...
def load_time_series(filename, delimiter=r'\s+'): r"""Import a time series from an annotation file. The file should consist of two columns of numeric values corresponding to the time and value of each sample of the time series. Parameters ---------- filename : str Path to the annotatio...
r"""Import a time series from an annotation file. The file should consist of two columns of numeric values corresponding to the time and value of each sample of the time series. Parameters ---------- filename : str Path to the annotation file delimiter : str Separator regular e...
def find_category(self, parent_alias, title): """Searches parent category children for the given title (case independent). :param str parent_alias: :param str title: :rtype: Category|None :return: None if not found; otherwise - found Category """ found = None ...
Searches parent category children for the given title (case independent). :param str parent_alias: :param str title: :rtype: Category|None :return: None if not found; otherwise - found Category
def init( dist='dist', minver=None, maxver=None, use_markdown_readme=True, use_stdeb=False, use_distribute=False, ): """Imports and returns a setup function. If use_markdown_readme is set, then README.md is added to setuptools READMES list. If use_stdeb is set on a Debian b...
Imports and returns a setup function. If use_markdown_readme is set, then README.md is added to setuptools READMES list. If use_stdeb is set on a Debian based system, then module stdeb is imported. Stdeb supports building deb packages on Debian based systems. The package should only be install...
def calc_percentile_interval(self, conf_percentage): """ Calculates percentile bootstrap confidence intervals for one's model. Parameters ---------- conf_percentage : scalar in the interval (0.0, 100.0). Denotes the confidence-level for the returned endpoints. For ...
Calculates percentile bootstrap confidence intervals for one's model. Parameters ---------- conf_percentage : scalar in the interval (0.0, 100.0). Denotes the confidence-level for the returned endpoints. For instance, to calculate a 95% confidence interval, pass `95`. ...
def monkey_patch(enabled=True): """Monkey patching PIL.Image.open method Args: enabled (bool): If the monkey patch should be activated or deactivated. """ if enabled: Image.open = imdirect_open else: Image.open = pil_open
Monkey patching PIL.Image.open method Args: enabled (bool): If the monkey patch should be activated or deactivated.
def _variants(self, case_id, gemini_query): """Return variants found in the gemini database Args: case_id (str): The case for which we want to see information gemini_query (str): What variants should be chosen filters (dict): A dictionary with filters...
Return variants found in the gemini database Args: case_id (str): The case for which we want to see information gemini_query (str): What variants should be chosen filters (dict): A dictionary with filters Yields: variant_obj (dict...
def init(self, force_deploy=False, client=None): """Reserve and deploys the nodes according to the resources section In comparison to the vagrant provider, networks must be characterized as in the networks key. Args: force_deploy (bool): True iff the environment must be red...
Reserve and deploys the nodes according to the resources section In comparison to the vagrant provider, networks must be characterized as in the networks key. Args: force_deploy (bool): True iff the environment must be redeployed Raises: MissingNetworkError: If ...
def path(self): """Returns the build root for the current workspace.""" if self._root_dir is None: # This env variable is for testing purpose. override_buildroot = os.environ.get('PANTS_BUILDROOT_OVERRIDE', None) if override_buildroot: self._root_dir = override_buildroot else: ...
Returns the build root for the current workspace.
def _check_params(self,params): """ Print a warning if params contains something that is not a Parameter of the overridden object. """ overridden_object_params = list(self._overridden.param) for item in params: if item not in overridden_object_params: ...
Print a warning if params contains something that is not a Parameter of the overridden object.
def validate_backup_window(window): """Validate PreferredBackupWindow for DBInstance""" hour = r'[01]?[0-9]|2[0-3]' minute = r'[0-5][0-9]' r = ("(?P<start_hour>%s):(?P<start_minute>%s)-" "(?P<end_hour>%s):(?P<end_minute>%s)") % (hour, minute, hour, minute) range_regex = re.compile(r) m...
Validate PreferredBackupWindow for DBInstance
def get_message_headers(self, section: Sequence[int] = None, subset: Collection[bytes] = None, inverse: bool = False) -> Writeable: """Get the headers from the message or a ``message/rfc822`` sub-part of the message.. The ``section`` argum...
Get the headers from the message or a ``message/rfc822`` sub-part of the message.. The ``section`` argument can index a nested sub-part of the message. For example, ``[2, 3]`` would get the 2nd sub-part of the message and then index it for its 3rd sub-part. Args: se...
def get_stack_refs(refs: list): # copy pasted from Senza """ Returns a list of stack references with name and version. """ refs = list(refs) refs.reverse() stack_refs = [] last_stack = None while refs: ref = refs.pop() if last_stack is not None and re.compile(r'v[0-9][a-...
Returns a list of stack references with name and version.
def getBinding(self): """Return the Binding object that is referenced by this port.""" wsdl = self.getService().getWSDL() return wsdl.bindings[self.binding]
Return the Binding object that is referenced by this port.
def ReadClientCrashInfo(self, client_id): """Reads the latest client crash record for a single client.""" history = self.crash_history.get(client_id, None) if not history: return None ts = max(history) res = rdf_client.ClientCrash.FromSerializedString(history[ts]) res.timestamp = ts r...
Reads the latest client crash record for a single client.
def _objective_decorator(func): """Decorate an objective function Converts an objective function using the typical sklearn metrics signature so that it is usable with ``xgboost.training.train`` Parameters ---------- func: callable Expects a callable with signature ``func(y_true, y_pred...
Decorate an objective function Converts an objective function using the typical sklearn metrics signature so that it is usable with ``xgboost.training.train`` Parameters ---------- func: callable Expects a callable with signature ``func(y_true, y_pred)``: y_true: array_like of sha...
def almost_unitary(gate: Gate) -> bool: """Return true if gate tensor is (almost) unitary""" res = (gate @ gate.H).asoperator() N = gate.qubit_nb return np.allclose(asarray(res), np.eye(2**N), atol=TOLERANCE)
Return true if gate tensor is (almost) unitary
def zsymDecorator(odd): """Decorator to deal with zsym=True input; set odd=True if the function is an odd function of z (like zforce)""" def wrapper(func): @wraps(func) def zsym_wrapper(*args,**kwargs): if args[0]._zsym: out= func(args[0],args[1],numpy.fabs(args[2]),*...
Decorator to deal with zsym=True input; set odd=True if the function is an odd function of z (like zforce)
def _parseSections(self, data, imageDosHeader, imageNtHeaders, parse_header_only=False): """Parses the sections in the memory and returns a list of them""" sections = [] optional_header_offset = imageDosHeader.header.e_lfanew + 4 + sizeof(IMAGE_FILE_HEADER) offset = optional_header_offs...
Parses the sections in the memory and returns a list of them
def see(obj=DEFAULT_ARG, *args, **kwargs): """ see(obj=anything) Show the features and attributes of an object. This function takes a single argument, ``obj``, which can be of any type. A summary of the object is printed immediately in the Python interpreter. For example:: >>> see([])...
see(obj=anything) Show the features and attributes of an object. This function takes a single argument, ``obj``, which can be of any type. A summary of the object is printed immediately in the Python interpreter. For example:: >>> see([]) [] in + ...
def set_evernote_spec(): """ set the spec of the notes :return: spec """ spec = NoteStore.NotesMetadataResultSpec() spec.includeTitle = True spec.includeAttributes = True return spec
set the spec of the notes :return: spec
def _firmware_update(firmwarefile='', host='', directory=''): ''' Update firmware for a single host ''' dest = os.path.join(directory, firmwarefile[7:]) __salt__['cp.get_file'](firmwarefile, dest) username = __pillar__['proxy']['admin_user'] password = __pillar__['prox...
Update firmware for a single host
def vm_detach_nic(name, kwargs=None, call=None): ''' Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt...
Detaches a disk from a virtual machine. .. versionadded:: 2016.3.0 name The name of the VM from which to detach the network interface. nic_id The ID of the nic to detach. CLI Example: .. code-block:: bash salt-cloud -a vm_detach_nic my-vm nic_id=1
def calculate_z2pt5_ngaw2(vs30): ''' Reads an array of vs30 values (in m/s) and returns the depth to the 2.5 km/s velocity horizon (in km) Ref: Campbell, K.W. & Bozorgnia, Y., 2014. 'NGA-West2 ground motion model for the average horizontal components of PGA, PGV, and 5pct damped linear accelerat...
Reads an array of vs30 values (in m/s) and returns the depth to the 2.5 km/s velocity horizon (in km) Ref: Campbell, K.W. & Bozorgnia, Y., 2014. 'NGA-West2 ground motion model for the average horizontal components of PGA, PGV, and 5pct damped linear acceleration response spectra.' Earthquake Spectra...
def crick_angles(p, reference_axis, tag=True, reference_axis_name='ref_axis'): """Returns the Crick angle for each CA atom in the `Polymer`. Notes ----- The final value is in the returned list is `None`, since the angle calculation requires pairs of points on both the primitive and reference_ax...
Returns the Crick angle for each CA atom in the `Polymer`. Notes ----- The final value is in the returned list is `None`, since the angle calculation requires pairs of points on both the primitive and reference_axis. Parameters ---------- p : ampal.Polymer Reference `Polymer`. ...
def digest(self): """Terminate the message-digest computation and return digest. Return the digest of the strings passed to the update() method so far. This is a 16-byte string which may contain non-ASCII characters, including null bytes. """ A = self.A B = self.B C = self.C D = se...
Terminate the message-digest computation and return digest. Return the digest of the strings passed to the update() method so far. This is a 16-byte string which may contain non-ASCII characters, including null bytes.
def canonicalize_id(reference_id): """\ Returns the canonicalized form of the provided reference_id. WikiLeaks provides some malformed cable identifiers. If the provided `reference_id` is not valid, this method returns the valid reference identifier equivalent. If the reference identifier is valid,...
\ Returns the canonicalized form of the provided reference_id. WikiLeaks provides some malformed cable identifiers. If the provided `reference_id` is not valid, this method returns the valid reference identifier equivalent. If the reference identifier is valid, the reference id is returned unchanged. ...
def decode_list(self, integers): """List of ints to list of str.""" integers = list(np.squeeze(integers)) return self.encoders["inputs"].decode_list(integers)
List of ints to list of str.
def encode(self, raw=False): """Convert message to on-the-wire FIX format. :param raw: If True, encode pairs exactly as provided. Unless 'raw' is set, this function will calculate and correctly set the BodyLength (9) and Checksum (10) fields, and ensure that the BeginString (8)...
Convert message to on-the-wire FIX format. :param raw: If True, encode pairs exactly as provided. Unless 'raw' is set, this function will calculate and correctly set the BodyLength (9) and Checksum (10) fields, and ensure that the BeginString (8), Body Length (9), Message Type ...
def destroyTempFiles(self): """Destroys all temp temp file hierarchy, getting rid of all files. """ os.system("rm -rf %s" % self.rootDir) logger.debug("Temp files created: %s, temp files actively destroyed: %s" % (self.tempFilesCreated, self.tempFilesDestroyed))
Destroys all temp temp file hierarchy, getting rid of all files.
def forward(self, src_seq, tgt_seq, src_valid_length=None, tgt_valid_length=None): #pylint: disable=arguments-differ """Generate the prediction given the src_seq and tgt_seq. This is used in training an NMT model. Parameters ---------- src_seq : NDArray tgt_seq : NDArr...
Generate the prediction given the src_seq and tgt_seq. This is used in training an NMT model. Parameters ---------- src_seq : NDArray tgt_seq : NDArray src_valid_length : NDArray or None tgt_valid_length : NDArray or None Returns ------- ...
def returner(ret): ''' Parse the return data and return metrics to Librato. ''' librato_conn = _get_librato(ret) q = librato_conn.new_queue() if ret['fun'] == 'state.highstate': log.debug('Found returned Highstate data.') # Calculate the runtimes and number of failed states. ...
Parse the return data and return metrics to Librato.
def extractInputForTP(self, tm): """ Extract inputs for TP from the state of temporal memory three information are extracted 1. correctly predicted cells 2. all active cells 3. bursting cells (unpredicted input) """ # bursting cells in layer 4 burstingColumns = tm.activeState["t"].s...
Extract inputs for TP from the state of temporal memory three information are extracted 1. correctly predicted cells 2. all active cells 3. bursting cells (unpredicted input)
def fromfits(infile, hdu = 0, verbose = True): """ Factory function that reads a FITS file and returns a f2nimage object. Use hdu to specify which HDU you want (primary = 0) """ pixelarray, hdr = ft.getdata(infile, hdu, header=True) pixelarray = np.asarray(pixelarray).transpose() #print...
Factory function that reads a FITS file and returns a f2nimage object. Use hdu to specify which HDU you want (primary = 0)
def rpush(self, key, value, *values): """Insert all the specified values at the tail of the list stored at key. """ return self.execute(b'RPUSH', key, value, *values)
Insert all the specified values at the tail of the list stored at key.
def connection_from_promised_list(data_promise, args=None, **kwargs): ''' A version of `connectionFromArray` that takes a promised array, and returns a promised connection. ''' return data_promise.then(lambda data: connection_from_list(data, args, **kwargs))
A version of `connectionFromArray` that takes a promised array, and returns a promised connection.
def get_endpoint_path(self, endpoint_id): '''return the first fullpath to a folder in the endpoint based on expanding the user's home from the globus config file. This function is fragile but I don't see any other way to do it. Parameters ========== endpoint_id: the endpoint ...
return the first fullpath to a folder in the endpoint based on expanding the user's home from the globus config file. This function is fragile but I don't see any other way to do it. Parameters ========== endpoint_id: the endpoint id to look up the path for
def on_disconnect(self, client, userdata, result_code): """ Callback when the MQTT client is disconnected. In this case, the server waits five seconds before trying to reconnected. :param client: the client being disconnected. :param userdata: unused. :param result_code: res...
Callback when the MQTT client is disconnected. In this case, the server waits five seconds before trying to reconnected. :param client: the client being disconnected. :param userdata: unused. :param result_code: result code.
def shutdown(): '''Shut down the SDK. :returns: An exception object if an error occurred, a falsy value otherwise. :rtype: Exception ''' global _sdk_ref_count #pylint:disable=global-statement global _sdk_instance #pylint:disable=global-statement global _should_shutdown #pylint:disable=glob...
Shut down the SDK. :returns: An exception object if an error occurred, a falsy value otherwise. :rtype: Exception
def getmembers_static(cls): """Gets members (vars) from all scopes using ONLY static information. You most likely want to use ScopeStack.getmembers instead. Returns: Set of available vars. Raises: NotImplementedError if any scope fails to implement 'getmembers'...
Gets members (vars) from all scopes using ONLY static information. You most likely want to use ScopeStack.getmembers instead. Returns: Set of available vars. Raises: NotImplementedError if any scope fails to implement 'getmembers'.
def html_to_rgb(html): """Convert the HTML color to (r, g, b). Parameters: :html: the HTML definition of the color (#RRGGBB or #RGB or a color name). Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] Throws: :ValueError: If html is neither...
Convert the HTML color to (r, g, b). Parameters: :html: the HTML definition of the color (#RRGGBB or #RGB or a color name). Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] Throws: :ValueError: If html is neither a known color name or a hex...
def _impl(lexer): """Return an Implies expression.""" p = _sumterm(lexer) tok = next(lexer) # SUMTERM '=>' IMPL if isinstance(tok, OP_rarrow): q = _impl(lexer) return ('implies', p, q) # SUMTERM '<=>' IMPL elif isinstance(tok, OP_lrarrow): q = _impl(lexer) re...
Return an Implies expression.
def tracebacks_from_lines(lines_iter): """Generator that yields tracebacks found in a lines iterator The lines iterator can be: - a file-like object - a list (or deque) of lines. - any other iterable sequence of strings """ tbgrep = TracebackGrep() for line in lines_iter: tb ...
Generator that yields tracebacks found in a lines iterator The lines iterator can be: - a file-like object - a list (or deque) of lines. - any other iterable sequence of strings
def get_command(self, ctx, name): """Retrieve the appropriate method from the Resource, decorate it as a click command, and return that method. """ # Sanity check: Does a method exist corresponding to this # command? If not, None is returned for click to raise # exception...
Retrieve the appropriate method from the Resource, decorate it as a click command, and return that method.
def isVideo(self): """ Is the stream labelled as a video stream. """ val=False if self.__dict__['codec_type']: if self.codec_type == 'video': val=True return val
Is the stream labelled as a video stream.
def geometry_from_grid(self, grid, pixel_centres, pixel_neighbors, pixel_neighbors_size, buffer=1e-8): """Determine the geometry of the Voronoi pixelization, by alligning it with the outer-most coordinates on a \ grid plus a small buffer. Parameters ----------- grid : ndarray ...
Determine the geometry of the Voronoi pixelization, by alligning it with the outer-most coordinates on a \ grid plus a small buffer. Parameters ----------- grid : ndarray The (y,x) grid of coordinates which determine the Voronoi pixelization's geometry. pixel_centres...
def set_site_energies( self, energies ): """ Set the energies for every site in the lattice according to the site labels. Args: energies (Dict(Str:Float): Dictionary of energies for each site label, e.g.:: { 'A' : 1.0, 'B', 0.0 } Returns: None ...
Set the energies for every site in the lattice according to the site labels. Args: energies (Dict(Str:Float): Dictionary of energies for each site label, e.g.:: { 'A' : 1.0, 'B', 0.0 } Returns: None
def ReadFileObject(self, file_object): """Reads artifact definitions from a file-like object. Args: file_object (file): file-like object to read from. Yields: ArtifactDefinition: an artifact definition. Raises: FormatError: if the format of the JSON artifact definition is not set ...
Reads artifact definitions from a file-like object. Args: file_object (file): file-like object to read from. Yields: ArtifactDefinition: an artifact definition. Raises: FormatError: if the format of the JSON artifact definition is not set or incorrect.
def unfreeze(self): """ Unfreeze model layers """ for idx, child in enumerate(self.model.children()): mu.unfreeze_layer(child)
Unfreeze model layers
def start(self): """Execution happening on jhubctl.""" # Get specified resource. resource_list = getattr(self, f'{self.resource_type}_list') resource_action = getattr(resource_list, self.resource_action) resource_action(self.resource_name)
Execution happening on jhubctl.
def _make_3d(field, twod): """Add a dimension to field if necessary. Args: field (numpy.array): the field that need to be 3d. twod (str): 'XZ', 'YZ' or None depending on what is relevant. Returns: numpy.array: reshaped field. """ shp = list(field.shape) if twod and 'X' i...
Add a dimension to field if necessary. Args: field (numpy.array): the field that need to be 3d. twod (str): 'XZ', 'YZ' or None depending on what is relevant. Returns: numpy.array: reshaped field.
def mlp(feature, hparams, name="mlp"): """Multi layer perceptron with dropout and relu activation.""" with tf.variable_scope(name, "mlp", values=[feature]): num_mlp_layers = hparams.num_mlp_layers mlp_dim = hparams.mlp_dim for _ in range(num_mlp_layers): feature = common_layers.dense(feature, mlp_...
Multi layer perceptron with dropout and relu activation.
def typing(self, *, channel: str): """Sends a typing indicator to the specified channel. This indicates that this app is currently writing a message to send to a channel. Args: channel (str): The channel id. e.g. 'C024BE91L' Raises: SlackClientNotConnec...
Sends a typing indicator to the specified channel. This indicates that this app is currently writing a message to send to a channel. Args: channel (str): The channel id. e.g. 'C024BE91L' Raises: SlackClientNotConnectedError: Websocket connection is closed.
def getJson(url): """Download json and return simplejson object""" site = urllib2.urlopen(url, timeout=300) return json.load(site)
Download json and return simplejson object
def create_vpn_gateway(self, type, availability_zone=None): """ Create a new Vpn Gateway :type type: str :param type: Type of VPN Connection. Only valid valid currently is 'ipsec.1' :type availability_zone: str :param availability_zone: The Availability Zone where you ...
Create a new Vpn Gateway :type type: str :param type: Type of VPN Connection. Only valid valid currently is 'ipsec.1' :type availability_zone: str :param availability_zone: The Availability Zone where you want the VPN gateway. :rtype: The newly created VpnGateway :ret...
def create_blocking_connection(host): """ Return properly created blocking connection. Args: host (str): Host as it is defined in :func:`.get_amqp_settings`. Uses :func:`edeposit.amqp.amqpdaemon.getConParams`. """ return pika.BlockingConnection( amqpdaemon.getConParams( ...
Return properly created blocking connection. Args: host (str): Host as it is defined in :func:`.get_amqp_settings`. Uses :func:`edeposit.amqp.amqpdaemon.getConParams`.