code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def folder_get(self, token, folder_id):
"""
Get the attributes of the specified folder.
:param token: A valid token for the user in question.
:type token: string
:param folder_id: The id of the requested folder.
:type folder_id: int | long
:returns: Dictionary of... | Get the attributes of the specified folder.
:param token: A valid token for the user in question.
:type token: string
:param folder_id: The id of the requested folder.
:type folder_id: int | long
:returns: Dictionary of the folder attributes.
:rtype: dict |
def cmd(send, msg, args):
"""Converts text to fullwidth characters.
Syntax: {command} [text]
"""
if not msg:
msg = gen_word()
send(gen_fullwidth(msg.upper())) | Converts text to fullwidth characters.
Syntax: {command} [text] |
def transition_to_add(self):
"""Transition to add"""
assert self.state in [AQStateMachineStates.init, AQStateMachineStates.add]
self.state = AQStateMachineStates.add | Transition to add |
def activate(paths, skip_local, skip_shared):
'''Activate an environment'''
if not paths:
ctx = click.get_current_context()
if cpenv.get_active_env():
ctx.invoke(info)
return
click.echo(ctx.get_help())
examples = (
'\nExamples: \n'
... | Activate an environment |
def value(self, obj):
'''
Computes the value of this field to update the index.
:param obj: object instance, as a dictionary or as a model instance.
'''
if self.template_name:
t = loader.select_template([self.template_name])
return t.render(Context({'objec... | Computes the value of this field to update the index.
:param obj: object instance, as a dictionary or as a model instance. |
def factorize(cls, pq):
"""
Factorizes the given large integer.
:param pq: the prime pair pq.
:return: a tuple containing the two factors p and q.
"""
if pq % 2 == 0:
return 2, pq // 2
y, c, m = randint(1, pq - 1), randint(1, pq - 1), randint(1, pq -... | Factorizes the given large integer.
:param pq: the prime pair pq.
:return: a tuple containing the two factors p and q. |
def delete_user(self, user_id, **kwargs):
"""
Delete user
:param user_id: User ID
:param kwargs:
:return:
"""
return DeleteUser(settings=self.settings, **kwargs).call(user_id=user_id, **kwargs) | Delete user
:param user_id: User ID
:param kwargs:
:return: |
def convert_markerstyle(inputstyle, mode, inputmode=None):
"""
Convert *inputstyle* to ROOT or matplotlib format.
Output format is determined by *mode* ('root' or 'mpl'). The *inputstyle*
may be a ROOT marker style, a matplotlib marker style, or a description
such as 'star' or 'square'.
"""
... | Convert *inputstyle* to ROOT or matplotlib format.
Output format is determined by *mode* ('root' or 'mpl'). The *inputstyle*
may be a ROOT marker style, a matplotlib marker style, or a description
such as 'star' or 'square'. |
def _pairwise(iterable):
"""
Wrapper on itertools for SVD_magnitude.
"""
a, b = itertools.tee(iterable)
next(b, None)
if sys.version_info.major == 2:
return itertools.izip(a, b)
else:
return zip(a, b) | Wrapper on itertools for SVD_magnitude. |
def calculate_checksum_on_iterator(
itr, algorithm=d1_common.const.DEFAULT_CHECKSUM_ALGORITHM
):
"""Calculate the checksum of an iterator.
Args:
itr: iterable
Object which supports the iterator protocol.
algorithm: str
Checksum algorithm, ``MD5`` or ``SHA1`` / ``SHA-1``.
R... | Calculate the checksum of an iterator.
Args:
itr: iterable
Object which supports the iterator protocol.
algorithm: str
Checksum algorithm, ``MD5`` or ``SHA1`` / ``SHA-1``.
Returns:
str : Checksum as a hexadecimal string, with length decided by the algorithm. |
def _duplicate_queries(self, output):
"""Appends the most common duplicate queries to the given output."""
if QC_SETTINGS['DISPLAY_DUPLICATES']:
for query, count in self.queries.most_common(QC_SETTINGS['DISPLAY_DUPLICATES']):
lines = ['\nRepeated {0} times.'.format(count)]
... | Appends the most common duplicate queries to the given output. |
def get_forward_star(self, node):
"""Given a node, get a copy of that node's forward star.
:param node: node to retrieve the forward-star of.
:returns: set -- set of hyperedge_ids for the hyperedges
in the node's forward star.
:raises: ValueError -- No such node ... | Given a node, get a copy of that node's forward star.
:param node: node to retrieve the forward-star of.
:returns: set -- set of hyperedge_ids for the hyperedges
in the node's forward star.
:raises: ValueError -- No such node exists. |
def args_length(min_len, max_len, *args):
"""
检查参数长度
"""
not_null(*args)
if not all(map(lambda v: min_len <= len(v) <= max_len, args)):
raise ValueError("Argument length must be between {0} and {1}!".format(min_len, max_len)) | 检查参数长度 |
def nearest_vertices(self, x, y, k=1, max_distance=np.inf ):
"""
Query the cKDtree for the nearest neighbours and Euclidean
distance from x,y points.
Returns 0, 0 if a cKDtree has not been constructed
(switch tree=True if you need this routine)
Parameters
------... | Query the cKDtree for the nearest neighbours and Euclidean
distance from x,y points.
Returns 0, 0 if a cKDtree has not been constructed
(switch tree=True if you need this routine)
Parameters
----------
x : 1D array of Cartesian x coordinates
y : 1D array of Ca... |
def _footer_start_thread(self, text, time):
"""Display given text in the footer. Clears after <time> seconds
"""
footerwid = urwid.AttrMap(urwid.Text(text), 'footer')
self.top.footer = footerwid
load_thread = Thread(target=self._loading_thread, args=(time,))
load_thread.... | Display given text in the footer. Clears after <time> seconds |
def do_build_reports(directory):
"""
Walk the directory and builds pre-calculation reports for all the
job.ini files found.
"""
for cwd, dirs, files in os.walk(directory):
for f in sorted(files):
if f in ('job.ini', 'job_h.ini', 'job_haz.ini', 'job_hazard.ini'):
j... | Walk the directory and builds pre-calculation reports for all the
job.ini files found. |
def get_joke():
"""Returns a joke from the WebKnox one liner API.
Returns None if unable to retrieve a joke.
"""
page = requests.get("https://api.chucknorris.io/jokes/random")
if page.status_code == 200:
joke = json.loads(page.content.decode("UTF-8"))
return joke["value"]
... | Returns a joke from the WebKnox one liner API.
Returns None if unable to retrieve a joke. |
def merge(args):
"""
%prog merge protein-quartets registry LOST
Merge protein quartets table with dna quartets registry. This is specific
to the napus project.
"""
from jcvi.formats.base import DictFile
p = OptionParser(merge.__doc__)
opts, args = p.parse_args(args)
if len(args) !... | %prog merge protein-quartets registry LOST
Merge protein quartets table with dna quartets registry. This is specific
to the napus project. |
def add_dynamic_kb(kbname, tag, collection="", searchwith=""):
"""A convenience method."""
kb_id = add_kb(kb_name=kbname, kb_type='dynamic')
save_kb_dyn_config(kb_id, tag, searchwith, collection)
return kb_id | A convenience method. |
def create(self, using=None, **kwargs):
"""
Creates the index in elasticsearch.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.create`` unchanged.
"""
self._get_connection(using).indices.create(index=self._name, body=self.to_dict(), **kwargs) | Creates the index in elasticsearch.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.create`` unchanged. |
def _phase_kuramoto(self, teta, t, argv):
"""!
@brief Overrided method for calculation of oscillator phase.
@param[in] teta (double): Current value of phase.
@param[in] t (double): Time (can be ignored).
@param[in] argv (uint): Index of oscillator whose phase repre... | !
@brief Overrided method for calculation of oscillator phase.
@param[in] teta (double): Current value of phase.
@param[in] t (double): Time (can be ignored).
@param[in] argv (uint): Index of oscillator whose phase represented by argument teta.
@return (d... |
def series(self):
'''Generator of single series data (no dates are included).'''
data = self.values()
if len(data):
for c in range(self.count()):
yield data[:, c]
else:
raise StopIteration | Generator of single series data (no dates are included). |
def requestSchema(self, nym, name, version, sender):
"""
Used to get a schema from Sovrin
:param nym: nym that schema is attached to
:param name: name of schema
:param version: version of schema
:return: req object
"""
operation = { TARGET_NYM: nym,
... | Used to get a schema from Sovrin
:param nym: nym that schema is attached to
:param name: name of schema
:param version: version of schema
:return: req object |
def is_read_only(p_command):
""" Returns True when the given command class is read-only. """
read_only_commands = tuple(cmd for cmd
in ('revert', ) + READ_ONLY_COMMANDS)
return p_command.name() in read_only_commands | Returns True when the given command class is read-only. |
def selection_error_control(self, form_info):
"""
It controls the selection from the form according
to the operations, and returns an error message
if it does not comply with the rules.
Args:
form_info: Channel or subscriber form from the user
Returns: True ... | It controls the selection from the form according
to the operations, and returns an error message
if it does not comply with the rules.
Args:
form_info: Channel or subscriber form from the user
Returns: True or False
error message |
def add_node(self, node):
"""Adds a `node` to the hash ring (including a number of replicas).
"""
self.nodes.append(node)
for x in xrange(self.replicas):
ring_key = self.hash_method(b("%s:%d" % (node, x)))
self.ring[ring_key] = node
self.sorted_keys.ap... | Adds a `node` to the hash ring (including a number of replicas). |
def sorted_items(d, key=__identity, reverse=False):
"""
Return the items of the dictionary sorted by the keys
>>> sample = dict(foo=20, bar=42, baz=10)
>>> tuple(sorted_items(sample))
(('bar', 42), ('baz', 10), ('foo', 20))
>>> reverse_string = lambda s: ''.join(reversed(s))
>>> tuple(sorted_items(sample, key=... | Return the items of the dictionary sorted by the keys
>>> sample = dict(foo=20, bar=42, baz=10)
>>> tuple(sorted_items(sample))
(('bar', 42), ('baz', 10), ('foo', 20))
>>> reverse_string = lambda s: ''.join(reversed(s))
>>> tuple(sorted_items(sample, key=reverse_string))
(('foo', 20), ('bar', 42), ('baz', 10))
... |
def table_path(cls, project, instance, table):
"""Return a fully-qualified table string."""
return google.api_core.path_template.expand(
"projects/{project}/instances/{instance}/tables/{table}",
project=project,
instance=instance,
table=table,
) | Return a fully-qualified table string. |
def debug(self, *msg):
"""
Prints a warning
"""
label = colors.yellow("DEBUG")
self._msg(label, *msg) | Prints a warning |
def get_query_rows(self, job_id, offset=None, limit=None, timeout=0):
"""Retrieve a list of rows from a query table by job id.
This method will append results from multiple pages together. If you
want to manually page through results, you can use `get_query_results`
method directly.
... | Retrieve a list of rows from a query table by job id.
This method will append results from multiple pages together. If you
want to manually page through results, you can use `get_query_results`
method directly.
Parameters
----------
job_id : str
The job id th... |
def from_perseus(network_table, networks):
"""
Create networkx graph from network tables
>>> from perseuspy import read_networks, nx
>>> network_table, networks = read_networks(folder)
>>> graphs = nx.from_perseus(network_table, networks)
"""
graphs = []
for guid, graph_attr in zip(... | Create networkx graph from network tables
>>> from perseuspy import read_networks, nx
>>> network_table, networks = read_networks(folder)
>>> graphs = nx.from_perseus(network_table, networks) |
def compute_key(cli, familly, discriminant=None):
"""This function is used to compute a unique key from all connection parametters."""
hash_key = hashlib.sha256()
hash_key.update(familly)
hash_key.update(cli.host)
hash_key.update(cli.user)
hash_key.update(cli.password)
if discriminant:
... | This function is used to compute a unique key from all connection parametters. |
def normalize_url(url):
"""Return url after stripping trailing .json and trailing slashes."""
if url.endswith('.json'):
url = url[:-5]
if url.endswith('/'):
url = url[:-1]
return url | Return url after stripping trailing .json and trailing slashes. |
def GetData(ID, season = None, cadence = 'lc', clobber = False, delete_raw = False,
aperture_name = None, saturated_aperture_name = None,
max_pixels = None, download_only = False, saturation_tolerance = None,
bad_bits = None, **kwargs):
'''
Returns a :py:obj:`DataContainer` ins... | Returns a :py:obj:`DataContainer` instance with the raw data for the target.
:param int ID: The target ID number
:param int season: The observing season. Default :py:obj:`None`
:param str cadence: The light curve cadence. Default `lc`
:param bool clobber: Overwrite existing files? Default :py:obj:`False`
:... |
def _from_docstring_rst(doc):
"""
format from docstring to ReStructured Text
"""
def format_fn(line, status):
""" format function """
if re_from_data.match(line):
line = re_from_data.sub(r"**\1** ", line)
status["add_line"] = True
line = re_from_defaults... | format from docstring to ReStructured Text |
def insert(self, row):
""" Insert a new row. The row will be added to the end of the
spreadsheet. Before inserting, the field names in the given
row will be normalized and values with empty field names
removed. """
data = self._convert_value(row)
self._service.InsertRow... | Insert a new row. The row will be added to the end of the
spreadsheet. Before inserting, the field names in the given
row will be normalized and values with empty field names
removed. |
def verify_psd_options_multi_ifo(opt, parser, ifos):
"""Parses the CLI options and verifies that they are consistent and
reasonable.
Parameters
----------
opt : object
Result of parsing the CLI with OptionParser, or any object with the
required attributes (psd_model, psd_file, asd_f... | Parses the CLI options and verifies that they are consistent and
reasonable.
Parameters
----------
opt : object
Result of parsing the CLI with OptionParser, or any object with the
required attributes (psd_model, psd_file, asd_file, psd_estimation,
psd_segment_length, psd_segment... |
def create_ngram_set(input_list, ngram_value=2):
"""
Extract a set of n-grams from a list of integers.
>>> create_ngram_set([1, 4, 9, 4, 1, 4], ngram_value=2)
{(4, 9), (4, 1), (1, 4), (9, 4)}
>>> create_ngram_set([1, 4, 9, 4, 1, 4], ngram_value=3)
[(1, 4, 9), (4, 9, 4), (9, 4, 1), (4, 1, 4)]
... | Extract a set of n-grams from a list of integers.
>>> create_ngram_set([1, 4, 9, 4, 1, 4], ngram_value=2)
{(4, 9), (4, 1), (1, 4), (9, 4)}
>>> create_ngram_set([1, 4, 9, 4, 1, 4], ngram_value=3)
[(1, 4, 9), (4, 9, 4), (9, 4, 1), (4, 1, 4)] |
def get_proficiencies_by_genus_type(self, proficiency_genus_type):
"""Gets a ``ProficiencyList`` corresponding to the given proficiency genus ``Type`` which does not include proficiencies of types derived from the specified ``Type``.
arg: proficiency_genus_type (osid.type.Type): a proficiency
... | Gets a ``ProficiencyList`` corresponding to the given proficiency genus ``Type`` which does not include proficiencies of types derived from the specified ``Type``.
arg: proficiency_genus_type (osid.type.Type): a proficiency
genus type
return: (osid.learning.ProficiencyList) - the ret... |
def generator(self, output, target):
"Evaluate the `output` with the critic then uses `self.loss_funcG` to combine it with `target`."
fake_pred = self.gan_model.critic(output)
return self.loss_funcG(fake_pred, target, output) | Evaluate the `output` with the critic then uses `self.loss_funcG` to combine it with `target`. |
def current_site_id():
"""
Responsible for determining the current ``Site`` instance to use
when retrieving data for any ``SiteRelated`` models. If we're inside an
override_current_site_id context manager, return the overriding site ID.
Otherwise, try to determine the site using the following method... | Responsible for determining the current ``Site`` instance to use
when retrieving data for any ``SiteRelated`` models. If we're inside an
override_current_site_id context manager, return the overriding site ID.
Otherwise, try to determine the site using the following methods in order:
- ``site_id`` in... |
def config_path(self, value):
"""Set config_path"""
self._config_path = value or ''
if not isinstance(self._config_path, str):
raise BadArgumentError("config_path must be string: {}".format(
self._config_path)) | Set config_path |
def reset_coords(self, names=None, drop=False, inplace=None):
"""Given names of coordinates, reset them to become variables
Parameters
----------
names : str or list of str, optional
Name(s) of non-index coordinates in this dataset to reset into
variables. By def... | Given names of coordinates, reset them to become variables
Parameters
----------
names : str or list of str, optional
Name(s) of non-index coordinates in this dataset to reset into
variables. By default, all non-index coordinates are reset.
drop : bool, optional
... |
def lv_load_areas(self):
"""Returns a generator for iterating over load_areas
Yields
------
int
generator for iterating over load_areas
"""
for load_area in sorted(self._lv_load_areas, key=lambda _: repr(_)):
yield load_area | Returns a generator for iterating over load_areas
Yields
------
int
generator for iterating over load_areas |
def get_least_salient_words(vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n=None):
"""
Order the words from `vocab` by "saliency score" (Chuang et al. 2012) from least to most salient. Optionally only
return the `n` least salient words.
J. Chuang, C. Manning, J. Heer 2012: "Termite: Visual... | Order the words from `vocab` by "saliency score" (Chuang et al. 2012) from least to most salient. Optionally only
return the `n` least salient words.
J. Chuang, C. Manning, J. Heer 2012: "Termite: Visualization Techniques for Assessing Textual Topic Models" |
def binary_regex(self):
"""Return the regex for the binary."""
regex = {'linux': r'^%(BINARY_NAME)s-%(VERSION)s\.%(EXT)s$',
'linux64': r'^%(BINARY_NAME)s-%(VERSION)s\.%(EXT)s$',
'mac': r'^%(BINARY_NAME)s(?:\s|-)%(VERSION)s\.%(EXT)s$',
'mac64': r'^%(BINA... | Return the regex for the binary. |
def gain_offsets(Idat,Qdat,Udat,Vdat,tsamp,chan_per_coarse,feedtype='l',**kwargs):
'''
Determines relative gain error in the X and Y feeds for an
observation given I and Q (I and V for circular basis) noise diode data.
'''
if feedtype=='l':
#Fold noise diode data and calculate ON OFF differe... | Determines relative gain error in the X and Y feeds for an
observation given I and Q (I and V for circular basis) noise diode data. |
def export_partlist_to_file(input, output, timeout=20, showgui=False):
'''
call eagle and export sch or brd to partlist text file
:param input: .sch or .brd file name
:param output: text file name
:param timeout: int
:param showgui: Bool, True -> do not hide eagle GUI
:rtype: None
'''
... | call eagle and export sch or brd to partlist text file
:param input: .sch or .brd file name
:param output: text file name
:param timeout: int
:param showgui: Bool, True -> do not hide eagle GUI
:rtype: None |
def _from_dict(cls, _dict):
"""Initialize a MessageContext object from a json dictionary."""
args = {}
if 'global' in _dict:
args['global_'] = MessageContextGlobal._from_dict(
_dict.get('global'))
if 'skills' in _dict:
args['skills'] = MessageConte... | Initialize a MessageContext object from a json dictionary. |
def fetch(self, fetch_notes=None):
""" update remote values (called automatically at __init__) """
if fetch_notes is None:
fetch_notes = self.fetch_notes
values, notes_index = get_sheet_values(self.name, self.sheet_name,
spreadsheet_serv... | update remote values (called automatically at __init__) |
def from_xy_array(cls, xy, shape):
"""
Convert an array (N,2) with a given image shape to a KeypointsOnImage object.
Parameters
----------
xy : (N, 2) ndarray
Coordinates of ``N`` keypoints on the original image, given
as ``(N,2)`` array of xy-coordinates... | Convert an array (N,2) with a given image shape to a KeypointsOnImage object.
Parameters
----------
xy : (N, 2) ndarray
Coordinates of ``N`` keypoints on the original image, given
as ``(N,2)`` array of xy-coordinates.
shape : tuple of int or ndarray
... |
def with_bundler(self):
"""
Check, if bundler check is requested.
Check, if the user wants us to check for new gems and return True in
this case.
:rtype : bool
"""
def gemfile_exists():
"""
Check, if a Gemfile exists in the cur... | Check, if bundler check is requested.
Check, if the user wants us to check for new gems and return True in
this case.
:rtype : bool |
def setCol(self, x, l):
"""set the x-th column, starting at 0"""
for i in xrange(0, self.__size):
self.setCell(x, i, l[i]) | set the x-th column, starting at 0 |
def parse_cell(self, cell):
"""
Process cell field, the field format just like {{field}}
:param cell:
:return: value, field
"""
field = ''
if (isinstance(cell.value, (str, unicode)) and
cell.value.startswith('{{') and
cell.value.endswith('}... | Process cell field, the field format just like {{field}}
:param cell:
:return: value, field |
def make_spark_lines(table,filename,sc,**kwargs):
spark_output = True
lines_out_count = False
extrema = False
for key,value in kwargs.iteritems():
if key == 'lines_out_count':
lines_out_count = value
if key == 'extrema':
extrema = value
# removing datetime references from imported postgis database
# CUR... | alignment_field = False
spark_output = True
if kwargs is not None:
for key,value in kwargs.iteritems():
if key == 'alignment_field':
alignment_field = value
if key == 'spark_output':
spark_output = value
#changing dataframe to list if dataframe
if isinstance(table,pd.DataFrame):
table=df2list(ta... |
def to_molden(cartesian_list, buf=None, sort_index=True,
overwrite=True, float_format='{:.6f}'.format):
"""Write a list of Cartesians into a molden file.
.. note:: Since it permamently writes a file, this function
is strictly speaking **not sideeffect free**.
The list to be writte... | Write a list of Cartesians into a molden file.
.. note:: Since it permamently writes a file, this function
is strictly speaking **not sideeffect free**.
The list to be written is of course not changed.
Args:
cartesian_list (list):
buf (str): StringIO-like, optional buffer to wr... |
def _dens(self,R,z,phi=0.,t=0.):
"""
NAME:
_dens
PURPOSE:
evaluate the density for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
the densi... | NAME:
_dens
PURPOSE:
evaluate the density for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
the density
HISTORY:
2015-06-15 - Written -... |
def _rotate(lon, lat, theta, axis='x'):
"""
Rotate "lon", "lat" coords (in _degrees_) about the X-axis by "theta"
degrees. This effectively simulates rotating a physical stereonet.
Returns rotated lon, lat coords in _radians_).
"""
# Convert input to numpy arrays in radians
lon, lat = np.at... | Rotate "lon", "lat" coords (in _degrees_) about the X-axis by "theta"
degrees. This effectively simulates rotating a physical stereonet.
Returns rotated lon, lat coords in _radians_). |
def get_de_novos_in_transcript(transcript, de_novos):
""" get the de novos within the coding sequence of a transcript
Args:
transcript: Transcript object, which defines the transcript coordinates
de_novos: list of chromosome sequence positions for de novo events
Returns:
li... | get the de novos within the coding sequence of a transcript
Args:
transcript: Transcript object, which defines the transcript coordinates
de_novos: list of chromosome sequence positions for de novo events
Returns:
list of de novo positions found within the transcript |
def less_than(self, less_than):
"""Adds new `<` condition
:param less_than: str or datetime compatible object (naive UTC datetime or tz-aware datetime)
:raise:
- QueryTypeError: if `less_than` is of an unexpected type
"""
if hasattr(less_than, 'strftime'):
... | Adds new `<` condition
:param less_than: str or datetime compatible object (naive UTC datetime or tz-aware datetime)
:raise:
- QueryTypeError: if `less_than` is of an unexpected type |
def read_object_from_yaml(desired_type: Type[Any], file_object: TextIOBase, logger: Logger,
fix_imports: bool = True, errors: str = 'strict', *args, **kwargs) -> Any:
"""
Parses a yaml file.
:param desired_type:
:param file_object:
:param logger:
:param fix_imports:
... | Parses a yaml file.
:param desired_type:
:param file_object:
:param logger:
:param fix_imports:
:param errors:
:param args:
:param kwargs:
:return: |
def populate_dataframe(index,columns, default_dict, dtype):
""" helper function to populate a generic Pst dataframe attribute. This
function is called as part of constructing a generic Pst instance
Parameters
----------
index : (varies)
something to use as the dataframe index
columns: ... | helper function to populate a generic Pst dataframe attribute. This
function is called as part of constructing a generic Pst instance
Parameters
----------
index : (varies)
something to use as the dataframe index
columns: (varies)
something to use as the dataframe columns
defau... |
def fn_floor(self, value):
"""
Return the floor of a number. For negative numbers, floor returns a lower value. E.g., `floor(-2.5) == -3`
:param value: The number.
:return: The floor of the number.
"""
if is_ndarray(value) or isinstance(value, (list, tuple)):
... | Return the floor of a number. For negative numbers, floor returns a lower value. E.g., `floor(-2.5) == -3`
:param value: The number.
:return: The floor of the number. |
def zan(self, id_reply):
'''
先在外部表中更新,然后更新内部表字段的值。
有冗余,但是查看的时候避免了联合查询
'''
logger.info('zan: {0}'.format(id_reply))
MReply2User.create_reply(self.userinfo.uid, id_reply)
cur_count = MReply2User.get_voter_count(id_reply)
if cur_count:
MReply.up... | 先在外部表中更新,然后更新内部表字段的值。
有冗余,但是查看的时候避免了联合查询 |
def get_template_debug(template_name, error):
'''
This structure is what Django wants when errors occur in templates.
It gives the user a nice stack trace in the error page during debug.
'''
# This is taken from mako.exceptions.html_error_template(), which has an issue
# in Py3 where files get l... | This structure is what Django wants when errors occur in templates.
It gives the user a nice stack trace in the error page during debug. |
def update_report_collector(self, timestamp):
"""Updating report collector for pipeline details."""
report_enabled = 'report' in self.information and self.information['report'] == 'html'
report_enabled = report_enabled and 'stage' in self.information
report_enabled = report_enabled and E... | Updating report collector for pipeline details. |
def warm_spell_duration_index(tasmax, tx90, window=6, freq='YS'):
r"""Warm spell duration index
Number of days with at least six consecutive days where the daily maximum temperature is above the 90th
percentile. The 90th percentile should be computed for a 5-day window centred on each calendar day in the
... | r"""Warm spell duration index
Number of days with at least six consecutive days where the daily maximum temperature is above the 90th
percentile. The 90th percentile should be computed for a 5-day window centred on each calendar day in the
1961-1990 period.
Parameters
----------
tasmax : xarra... |
def fit(self, xy=False, **kwargs):
"""Write xtc that is fitted to the tpr reference structure.
Runs :class:`gromacs.tools.trjconv` with appropriate arguments
for fitting. The most important *kwargs* are listed
here but in most cases the defaults should work.
Note that the defau... | Write xtc that is fitted to the tpr reference structure.
Runs :class:`gromacs.tools.trjconv` with appropriate arguments
for fitting. The most important *kwargs* are listed
here but in most cases the defaults should work.
Note that the default settings do *not* include centering or
... |
def usergroups_users_update(
self, *, usergroup: str, users: List[str], **kwargs
) -> SlackResponse:
"""Update the list of users for a User Group
Args:
usergroup (str): The encoded ID of the User Group to update.
e.g. 'S0604QSJC'
users (list): A list ... | Update the list of users for a User Group
Args:
usergroup (str): The encoded ID of the User Group to update.
e.g. 'S0604QSJC'
users (list): A list user IDs that represent the entire list of
users for the User Group. e.g. ['U060R4BJ4', 'U060RNRCZ'] |
def _bucket_key(self):
""" Returns hash bucket key for the redis key """
return "{}.size.{}".format(
self.prefix, (self._hashed_key//1000)
if self._hashed_key > 1000 else self._hashed_key) | Returns hash bucket key for the redis key |
def func(nargs: Optional[int] = None, nouts: Optional[int] = None, ndefs: Optional[int] = None):
"""
decorates normal function to Function with (optional) number of arguments and outputs.
: func(nargs: Optional[int] = None, nouts: Optional[int] = None, ndefs: Optional[int] = None)
"""
retur... | decorates normal function to Function with (optional) number of arguments and outputs.
: func(nargs: Optional[int] = None, nouts: Optional[int] = None, ndefs: Optional[int] = None) |
def from_backend(self, dagobah_id):
""" Reconstruct this Dagobah instance from the backend. """
logger.debug('Reconstructing Dagobah instance from backend with ID {0}'.format(dagobah_id))
rec = self.backend.get_dagobah_json(dagobah_id)
if not rec:
raise DagobahError('dagobah ... | Reconstruct this Dagobah instance from the backend. |
def healthy(self):
"""Return 200 is healthy, else 500.
Override is_healthy() to change the health check.
"""
try:
if self.is_healthy():
return "OK", 200
else:
return "FAIL", 500
except Exception as e:
self.app... | Return 200 is healthy, else 500.
Override is_healthy() to change the health check. |
def max_insertion(seqs, gene, domain):
"""
length of largest insertion
"""
seqs = [i[2] for i in list(seqs.values()) if i[2] != [] and i[0] == gene and i[1] == domain]
lengths = []
for seq in seqs:
for ins in seq:
lengths.append(int(ins[2]))
if lengths == []:
retu... | length of largest insertion |
def calc_svd(self, lapack_driver='gesdd'):
""" Return the SVD decomposition of data
The input data np.ndarray shall be of dimension 2,
with time as the first dimension, and the channels in the second
Hence data should be of shape (nt, nch)
Uses scipy.linalg.svd(), with:... | Return the SVD decomposition of data
The input data np.ndarray shall be of dimension 2,
with time as the first dimension, and the channels in the second
Hence data should be of shape (nt, nch)
Uses scipy.linalg.svd(), with:
full_matrices = True
compute_u... |
async def toggle(self):
"""Toggles between pause and resume command"""
self.logger.debug("toggle command")
if not self.state == 'ready':
return
if self.streamer is None:
return
try:
if self.streamer.is_playing():
await self.... | Toggles between pause and resume command |
def __normalize_args(**keywds):
"""implementation details"""
if isinstance(keywds['name'], Callable) and \
None is keywds['function']:
keywds['function'] = keywds['name']
keywds['name'] = None
return keywds | implementation details |
def save_output_meta(self):
"""
Save descriptive output meta data to a JSON file.
"""
options = self.options
file_path = os.path.join(options.outputdir, 'output.meta.json')
with open(file_path, 'w') as outfile:
json.dump(self.OUTPUT_META_DICT, outfile) | Save descriptive output meta data to a JSON file. |
def skull_strip(dset,suffix='_ns',prefix=None,unifize=True):
''' use bet to strip skull from given anatomy '''
# should add options to use betsurf and T1/T2 in the future
# Since BET fails on weirdly distributed datasets, I added 3dUnifize in... I realize this makes this dependent on AFNI. Sorry, :)
if ... | use bet to strip skull from given anatomy |
def dist_calc(loc1, loc2):
"""
Function to calculate the distance in km between two points.
Uses the flat Earth approximation. Better things are available for this,
like `gdal <http://www.gdal.org/>`_.
:type loc1: tuple
:param loc1: Tuple of lat, lon, depth (in decimal degrees and km)
:typ... | Function to calculate the distance in km between two points.
Uses the flat Earth approximation. Better things are available for this,
like `gdal <http://www.gdal.org/>`_.
:type loc1: tuple
:param loc1: Tuple of lat, lon, depth (in decimal degrees and km)
:type loc2: tuple
:param loc2: Tuple of... |
def get_user_choice(items):
'''Returns the selected item from provided items or None if 'q' was
entered for quit.
'''
choice = raw_input('Choose an item or "q" to quit: ')
while choice != 'q':
try:
item = items[int(choice)]
print # Blank line for readability between ... | Returns the selected item from provided items or None if 'q' was
entered for quit. |
def shell_split(text):
"""
Split the string `text` using shell-like syntax
This avoids breaking single/double-quoted strings (e.g. containing
strings with spaces). This function is almost equivalent to the shlex.split
function (see standard library `shlex`) except that it is supporting
u... | Split the string `text` using shell-like syntax
This avoids breaking single/double-quoted strings (e.g. containing
strings with spaces). This function is almost equivalent to the shlex.split
function (see standard library `shlex`) except that it is supporting
unicode strings (shlex does not suppor... |
def write(self, buf):
"""Inserts a string buffer as a record.
Examples
---------
>>> record = mx.recordio.MXRecordIO('tmp.rec', 'w')
>>> for i in range(5):
... record.write('record_%d'%i)
>>> record.close()
Parameters
----------
buf : ... | Inserts a string buffer as a record.
Examples
---------
>>> record = mx.recordio.MXRecordIO('tmp.rec', 'w')
>>> for i in range(5):
... record.write('record_%d'%i)
>>> record.close()
Parameters
----------
buf : string (python2), bytes (python3)... |
def groups(self, labels, collect=None):
"""Group rows by multiple columns, count or aggregate others.
Args:
``labels``: list of column names (or indices) to group on
``collect``: a function applied to values in other columns for each group
Returns: A Table with each ro... | Group rows by multiple columns, count or aggregate others.
Args:
``labels``: list of column names (or indices) to group on
``collect``: a function applied to values in other columns for each group
Returns: A Table with each row corresponding to a unique combination of values i... |
def update(self, changed_state_model=None, with_expand=False):
"""Checks if all states are in tree and if tree has states which were deleted
:param changed_state_model: Model that row has to be updated
:param with_expand: The expand flag for the tree
"""
if not self.view_is_regi... | Checks if all states are in tree and if tree has states which were deleted
:param changed_state_model: Model that row has to be updated
:param with_expand: The expand flag for the tree |
def get_available_devices(self):
"""
Gets available devices using mbedls and self.available_edbg_ports.
:return: List of connected devices as dictionaries.
"""
connected_devices = self.mbeds.list_mbeds() if self.mbeds else []
# Check non mbedOS supported devices.
... | Gets available devices using mbedls and self.available_edbg_ports.
:return: List of connected devices as dictionaries. |
def make_directory(self, directory_name, *args, **kwargs):
""" :meth:`.WNetworkClientProto.make_directory` method implementation
"""
self.dav_client().mkdir(self.join_path(self.session_path(), directory_name)) | :meth:`.WNetworkClientProto.make_directory` method implementation |
def server(self):
"""
UDP server to listen for responses.
"""
server = getattr(self, "_server", None)
if server is None:
log.debug("Binding datagram server to %s", self.bind)
server = DatagramServer(self.bind, self._response_received)
self._ser... | UDP server to listen for responses. |
def get_randomness_stream(self, decision_point: str, for_initialization: bool=False) -> RandomnessStream:
"""Provides a new source of random numbers for the given decision point.
Parameters
----------
decision_point :
A unique identifier for a stream of random numbers. Typi... | Provides a new source of random numbers for the given decision point.
Parameters
----------
decision_point :
A unique identifier for a stream of random numbers. Typically represents
a decision that needs to be made each time step like 'moves_left' or
'gets_d... |
def get_array_dimensions(data):
"""
Given an array type data item, check that it is an array and
return the dimensions as a tuple.
Ex: get_array_dimensions([[1, 2, 3], [4, 5, 6]]) returns (2, 3)
"""
depths_and_dimensions = get_depths_and_dimensions(data, 0)
# re-form as a dictionary with `de... | Given an array type data item, check that it is an array and
return the dimensions as a tuple.
Ex: get_array_dimensions([[1, 2, 3], [4, 5, 6]]) returns (2, 3) |
def prepare_socket(bind_addr, family, type, proto, nodelay, ssl_adapter):
"""Create and prepare the socket object."""
sock = socket.socket(family, type, proto)
prevent_socket_inheritance(sock)
host, port = bind_addr[:2]
IS_EPHEMERAL_PORT = port == 0
if not (IS_WINDOWS o... | Create and prepare the socket object. |
def batch_fetch_labels(ids):
"""
fetch all rdfs:label assertions for a set of CURIEs
"""
m = {}
for id in ids:
label = anyont_fetch_label(id)
if label is not None:
m[id] = label
return m | fetch all rdfs:label assertions for a set of CURIEs |
def add_project(self, ):
"""Add a project and store it in the self.projects
:returns: None
:rtype: None
:raises: None
"""
i = self.prj_tablev.currentIndex()
item = i.internalPointer()
if item:
project = item.internal_data()
if self... | Add a project and store it in the self.projects
:returns: None
:rtype: None
:raises: None |
def peek_at(iterable: Iterable[T]) -> Tuple[T, Iterator[T]]:
"""Returns the first value from iterable, as well as a new iterator with
the same content as the original iterable
"""
gen = iter(iterable)
peek = next(gen)
return peek, itertools.chain([peek], gen) | Returns the first value from iterable, as well as a new iterator with
the same content as the original iterable |
def main_passpersist(self):
"""
Main function that handle SNMP's pass_persist protocol, called by
the start method.
Direct call is unnecessary.
"""
line = sys.stdin.readline().strip()
if not line:
raise EOFError()
if 'PING' in line:
print("PONG")
elif 'getnext' in line:
oid = self.cut_oid(sy... | Main function that handle SNMP's pass_persist protocol, called by
the start method.
Direct call is unnecessary. |
def before_all(ctx):
"""
Pulls down busybox:latest before anything is tested.
"""
ctx.client = get_client()
try:
ctx.client.inspect_image(IMAGE)
except NotFound:
ctx.client.pull(IMAGE) | Pulls down busybox:latest before anything is tested. |
def alternative_short_name(self, name=None, entry_name=None, limit=None, as_df=False):
"""Method to query :class:`.models.AlternativeShortlName` objects in database
:param name: alternative short name(s)
:type name: str or tuple(str) or None
:param entry_name: name(s) in :class:`.model... | Method to query :class:`.models.AlternativeShortlName` objects in database
:param name: alternative short name(s)
:type name: str or tuple(str) or None
:param entry_name: name(s) in :class:`.models.Entry`
:type entry_name: str or tuple(str) or None
:param limit:
- ... |
def clear_cache(backend=None):
'''
.. versionadded:: 2015.5.0
Clear the fileserver cache from VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`). Executing this runner with no arguments will
clear the cache for all ... | .. versionadded:: 2015.5.0
Clear the fileserver cache from VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`). Executing this runner with no arguments will
clear the cache for all enabled VCS fileserver backends, but this
... |
def handleNotification(self, handle, data):
"""Handle Callback from a Bluetooth (GATT) request."""
_LOGGER.debug("Got notification from %s: %s", handle, codecs.encode(data, 'hex'))
if handle in self._callbacks:
self._callbacks[handle](data) | Handle Callback from a Bluetooth (GATT) request. |
def array_addunique(path, value, create_parents=False, **kwargs):
"""
Add a new value to an array if the value does not exist.
:param path: The path to the array
:param value: Value to add to the array if it does not exist.
Currently the value is restricted to primitives: strings, numbers,
... | Add a new value to an array if the value does not exist.
:param path: The path to the array
:param value: Value to add to the array if it does not exist.
Currently the value is restricted to primitives: strings, numbers,
booleans, and `None` values.
:param create_parents: Create the array i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.