Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
371,900 | def folder_get(self, token, folder_id):
parameters = dict()
parameters[] = token
parameters[] = folder_id
response = self.request(, parameters)
return response | 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 |
371,901 | def cmd(send, msg, args):
if not msg:
msg = gen_word()
send(gen_fullwidth(msg.upper())) | Converts text to fullwidth characters.
Syntax: {command} [text] |
371,902 | def transition_to_add(self):
assert self.state in [AQStateMachineStates.init, AQStateMachineStates.add]
self.state = AQStateMachineStates.add | Transition to add |
371,903 | def activate(paths, skip_local, skip_shared):
if not paths:
ctx = click.get_current_context()
if cpenv.get_active_env():
ctx.invoke(info)
return
click.echo(ctx.get_help())
examples = (
)
... | Activate an environment |
371,904 | def value(self, obj):
if self.template_name:
t = loader.select_template([self.template_name])
return t.render(Context({: obj}))
if self.eval_func:
try:
return eval(self.eval_func)
except Exception as e:
raise type(... | Computes the value of this field to update the index.
:param obj: object instance, as a dictionary or as a model instance. |
371,905 | def factorize(cls, pq):
if pq % 2 == 0:
return 2, pq // 2
y, c, m = randint(1, pq - 1), randint(1, pq - 1), randint(1, pq - 1)
g = r = q = 1
x = ys = 0
while g == 1:
x = y
for i in range(r):
y = (pow(y, 2, pq) + c) % ... | Factorizes the given large integer.
:param pq: the prime pair pq.
:return: a tuple containing the two factors p and q. |
371,906 | def delete_user(self, user_id, **kwargs):
return DeleteUser(settings=self.settings, **kwargs).call(user_id=user_id, **kwargs) | Delete user
:param user_id: User ID
:param kwargs:
:return: |
371,907 | def convert_markerstyle(inputstyle, mode, inputmode=None):
mode = mode.lower()
if mode not in (, ):
raise ValueError("`{0}` is not valid `mode`".format(mode))
if inputmode is None:
if inputstyle in markerstyles_root2mpl:
inputmode =
elif inputstyle in markerstyles_m... | 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'. |
371,908 | def _pairwise(iterable):
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. |
371,909 | def calculate_checksum_on_iterator(
itr, algorithm=d1_common.const.DEFAULT_CHECKSUM_ALGORITHM
):
checksum_calc = get_checksum_calculator_by_dataone_designator(algorithm)
for chunk in itr:
checksum_calc.update(chunk)
return checksum_calc.hexdigest() | 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. |
371,910 | def _duplicate_queries(self, output):
if QC_SETTINGS[]:
for query, count in self.queries.most_common(QC_SETTINGS[]):
lines = [.format(count)]
lines += wrap(query)
lines = "\n".join(lines) + "\n"
output += self._colorize(lines, ... | Appends the most common duplicate queries to the given output. |
371,911 | def get_forward_star(self, node):
if node not in self._node_attributes:
raise ValueError("No such node exists.")
return self._forward_star[node].copy() | 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. |
371,912 | 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)) | 检查参数长度 |
371,913 | def nearest_vertices(self, x, y, k=1, max_distance=np.inf ):
if self.tree == False or self.tree == None:
return 0, 0
xy = np.column_stack([x, y])
dxy, vertices = self._cKDtree.query(xy, k=k, distance_upper_bound=max_distance)
if k == 1:
vertices =... | 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... |
371,914 | def _footer_start_thread(self, text, time):
footerwid = urwid.AttrMap(urwid.Text(text), )
self.top.footer = footerwid
load_thread = Thread(target=self._loading_thread, args=(time,))
load_thread.daemon = True
load_thread.start() | Display given text in the footer. Clears after <time> seconds |
371,915 | def do_build_reports(directory):
for cwd, dirs, files in os.walk(directory):
for f in sorted(files):
if f in (, , , ):
job_ini = os.path.join(cwd, f)
logging.info(job_ini)
try:
reportwriter.build_report(job_ini, cwd)
... | Walk the directory and builds pre-calculation reports for all the
job.ini files found. |
371,916 | def get_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"]
return None | Returns a joke from the WebKnox one liner API.
Returns None if unable to retrieve a joke. |
371,917 | def merge(args):
from jcvi.formats.base import DictFile
p = OptionParser(merge.__doc__)
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
quartets, registry, lost = args
qq = DictFile(registry, keypos=1, valuepos=3)
lost = DictFile(lost, keypos=1... | %prog merge protein-quartets registry LOST
Merge protein quartets table with dna quartets registry. This is specific
to the napus project. |
371,918 | def add_dynamic_kb(kbname, tag, collection="", searchwith=""):
kb_id = add_kb(kb_name=kbname, kb_type=)
save_kb_dyn_config(kb_id, tag, searchwith, collection)
return kb_id | A convenience method. |
371,919 | def create(self, using=None, **kwargs):
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. |
371,920 | def _phase_kuramoto(self, teta, t, argv):
index = argv;
phase = 0.0;
neighbors = self.get_neighbors(index);
for k in neighbors:
conn_weight = 1.0;
if (self._ena_conn_weight is True):
conn_weight = self._c... | !
@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... |
371,921 | def series(self):
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). |
371,922 | def requestSchema(self, nym, name, version, sender):
operation = { TARGET_NYM: nym,
TXN_TYPE: GET_SCHEMA,
DATA: {NAME : name,
VERSION: version}
}
req = Request(sender, operation=operation)
return self.prep... | 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 |
371,923 | def is_read_only(p_command):
read_only_commands = tuple(cmd for cmd
in (, ) + READ_ONLY_COMMANDS)
return p_command.name() in read_only_commands | Returns True when the given command class is read-only. |
371,924 | def selection_error_control(self, form_info):
keys, names = self.return_selected_form_items(form_info[])
chosen_channels_number = len(keys)
if form_info[] and chosen_channels_number < 2:
return False, _(
u"You should choose at least two channel to merge oper... | 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 |
371,925 | def add_node(self, node):
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.append(ring_key)
self.sorted_keys.sort() | Adds a `node` to the hash ring (including a number of replicas). |
371,926 | def sorted_items(d, key=__identity, reverse=False):
def pairkey_key(item):
return key(item[0])
return sorted(d.items(), key=pairkey_key, reverse=reverse) | 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))
... |
371,927 | def table_path(cls, project, instance, table):
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. |
371,928 | def debug(self, *msg):
label = colors.yellow("DEBUG")
self._msg(label, *msg) | Prints a warning |
371,929 | def get_query_rows(self, job_id, offset=None, limit=None, timeout=0):
query_reply = self.get_query_results(job_id, offset=offset,
limit=limit, timeout=timeout)
if not query_reply[]:
logger.warning( % job_id)
raise Un... | 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... |
371,930 | def from_perseus(network_table, networks):
graphs = []
for guid, graph_attr in zip(network_table[], network_table.values):
network = networks[guid]
edge_table = network[]
if edge_table[[, ]].duplicated().any():
warnings.warn(.format(network[]))
G = nx.from_pandas... | 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) |
371,931 | def compute_key(cli, familly, discriminant=None):
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:
if isinstance(discriminant, list):
for i in discriminant:
... | This function is used to compute a unique key from all connection parametters. |
371,932 | def normalize_url(url):
if url.endswith():
url = url[:-5]
if url.endswith():
url = url[:-1]
return url | Return url after stripping trailing .json and trailing slashes. |
371,933 | def GetData(ID, season = None, cadence = , 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):
raise NotImplementedError() | 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`
:... |
371,934 | def _from_docstring_rst(doc):
def format_fn(line, status):
if re_from_data.match(line):
line = re_from_data.sub(r"**\1** ", line)
status["add_line"] = True
line = re_from_defaults.sub(r"*\1*", line)
if status["listing"]:
if re_... | format from docstring to ReStructured Text |
371,935 | def insert(self, row):
data = self._convert_value(row)
self._service.InsertRow(data, self._ss.id, self.id) | 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. |
371,936 | def verify_psd_options_multi_ifo(opt, parser, ifos):
for ifo in ifos:
for opt_group in ensure_one_opt_groups:
ensure_one_opt_multi_ifo(opt, parser, ifo, opt_group)
if opt.psd_estimation[ifo]:
required_opts_multi_ifo(opt, parser, ifo,
[, ],
... | 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... |
371,937 | def create_ngram_set(input_list, ngram_value=2):
return set(zip(*[input_list[i:] for i in range(ngram_value)])) | 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)] |
371,938 | def get_proficiencies_by_genus_type(self, proficiency_genus_type):
collection = JSONClientValidated(,
collection=,
runtime=self._runtime)
result = collection.find(
dict({: st... | 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... |
371,939 | 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`. |
371,940 | def current_site_id():
if hasattr(override_current_site_id.thread_local, "site_id"):
return override_current_site_id.thread_local.site_id
from yacms.utils.cache import cache_installed, cache_get, cache_set
request = current_request()
site_id = getattr(request, "site_id", None)
if requ... | 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... |
371,941 | def config_path(self, value):
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 |
371,942 | def reset_coords(self, names=None, drop=False, inplace=None):
inplace = _check_inplace(inplace)
if names is None:
names = self._coord_names - set(self.dims)
else:
if isinstance(names, str):
names = [names]
self._assert_all_in_dataset(n... | 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
... |
371,943 | def lv_load_areas(self):
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 |
371,944 | def get_least_salient_words(vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n=None):
return _words_by_salience_score(vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n, least_to_most=True) | 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" |
371,945 | def binary_regex(self):
regex = {: r,
: r,
: r,
: r,
:
r,
:
r,
}
return regex[self.platform] % {
: APPLICATIONS_TO_BINARY_NAME.get(self.app... | Return the regex for the binary. |
371,946 | def gain_offsets(Idat,Qdat,Udat,Vdat,tsamp,chan_per_coarse,feedtype=,**kwargs):
if feedtype==:
I_OFF,I_ON = foldcal(Idat,tsamp,**kwargs)
Q_OFF,Q_ON = foldcal(Qdat,tsamp,**kwargs)
XX_ON = (I_ON+Q_ON)/2
XX_OFF = (I_OFF+Q_OFF)/2
YY_ON = (I_ON-Q_ON)/2
... | 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. |
371,947 | def export_partlist_to_file(input, output, timeout=20, showgui=False):
input = norm_path(input)
output = norm_path(output)
commands = export_command(output=output, output_type=)
command_eagle(
input=input, timeout=timeout, commands=commands, showgui=showgui) | 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 |
371,948 | def _from_dict(cls, _dict):
args = {}
if in _dict:
args[] = MessageContextGlobal._from_dict(
_dict.get())
if in _dict:
args[] = MessageContextSkills._from_dict(
_dict.get())
return cls(**args) | Initialize a MessageContext object from a json dictionary. |
371,949 | def fetch(self, fetch_notes=None):
if fetch_notes is None:
fetch_notes = self.fetch_notes
values, notes_index = get_sheet_values(self.name, self.sheet_name,
spreadsheet_service=self._spreadsheet_service,
... | update remote values (called automatically at __init__) |
371,950 | def from_xy_array(cls, xy, shape):
keypoints = [Keypoint(x=coord[0], y=coord[1]) for coord in xy]
return KeypointsOnImage(keypoints, 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.
shape : tuple of int or ndarray
... |
371,951 | def with_bundler(self):
def gemfile_exists():
return os.path.exists()
if in os.environ:
print(colored(
s config system. To
set it globally, run this command anywhere:
git config --global git-up.bundler.check true
To set it ... | 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 |
371,952 | def setCol(self, x, l):
for i in xrange(0, self.__size):
self.setCell(x, i, l[i]) | set the x-th column, starting at 0 |
371,953 | def parse_cell(self, cell):
field =
if (isinstance(cell.value, (str, unicode)) and
cell.value.startswith() and
cell.value.endswith()):
field = cell.value[2:-2].strip()
value =
else:
value = cell.value
return value, f... | Process cell field, the field format just like {{field}}
:param cell:
:return: value, field |
371,954 | 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 = value
if key == :
extrema = value
list = []
count = 0
for row in table.columns.values.tolist():
if in row:
list.ap... | 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... |
371,955 | def to_molden(cartesian_list, buf=None, sort_index=True,
overwrite=True, float_format=.format):
if sort_index:
cartesian_list = [molecule.sort_index() for molecule in cartesian_list]
give_header = ("[MOLDEN FORMAT]\n"
+ "[N_GEO]\n"
+ str(len(cart... | 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... |
371,956 | def _dens(self,R,z,phi=0.,t=0.):
return 3./4./nu.pi*self._b2*(R**2.+z**2.+self._b2)**-2.5 | 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 -... |
371,957 | def _rotate(lon, lat, theta, axis=):
lon, lat = np.atleast_1d(lon, lat)
lon, lat = map(np.radians, [lon, lat])
theta = np.radians(theta)
x, y, z = sph2cart(lon, lat)
lookup = {:_rotate_x, :_rotate_y, :_rotate_z}
X, Y, Z = lookup[axis](x, y, z, theta)
lon, lat = cart2sp... | 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_). |
371,958 | def get_de_novos_in_transcript(transcript, de_novos):
in_transcript = []
for de_novo in de_novos:
in_transcript.append(de_novo)
return in_transcript | 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 |
371,959 | def less_than(self, less_than):
if hasattr(less_than, ):
less_than = datetime_as_utc(less_than).strftime()
elif isinstance(less_than, six.string_types):
raise QueryTypeError( % type(less_than))
return self._add_condition(, less_than, types=[int, str]) | 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 |
371,960 | def read_object_from_yaml(desired_type: Type[Any], file_object: TextIOBase, logger: Logger,
fix_imports: bool = True, errors: str = , *args, **kwargs) -> Any:
return yaml.load(file_object) | Parses a yaml file.
:param desired_type:
:param file_object:
:param logger:
:param fix_imports:
:param errors:
:param args:
:param kwargs:
:return: |
371,961 | def populate_dataframe(index,columns, default_dict, dtype):
new_df = pd.DataFrame(index=index,columns=columns)
for fieldname,dt in zip(columns,dtype.descr):
default = default_dict[fieldname]
new_df.loc[:,fieldname] = default
new_df.loc[:,fieldname] = new_df.loc[:,fieldname].astype(d... | 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... |
371,962 | def fn_floor(self, value):
if is_ndarray(value) or isinstance(value, (list, tuple)):
return numpy.floor(self._to_ndarray(value))
else:
return math.floor(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. |
371,963 | def zan(self, id_reply):
logger.info(.format(id_reply))
MReply2User.create_reply(self.userinfo.uid, id_reply)
cur_count = MReply2User.get_voter_count(id_reply)
if cur_count:
MReply.update_vote(id_reply, cur_count)
output = {: cur_count}
else:
... | 先在外部表中更新,然后更新内部表字段的值。
有冗余,但是查看的时候避免了联合查询 |
371,964 | 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. |
371,965 | def update_report_collector(self, timestamp):
report_enabled = in self.information and self.information[] ==
report_enabled = report_enabled and in self.information
report_enabled = report_enabled and Event.collector_queue is not None
if report_enabled:
Event.col... | Updating report collector for pipeline details. |
371,966 | def warm_spell_duration_index(tasmax, tx90, window=6, freq=):
r
if not in tx90.coords.keys():
raise AttributeError("tx90 should have dayofyear coordinates.")
doy = tasmax.indexes[].dayofyear
tx90 = utils.adjust_doy_calendar(tx90, tasmax)
thresh = xr.full_like(tasmax, np.na... | 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... |
371,967 | def fit(self, xy=False, **kwargs):
kwargs.setdefault(, self.tpr)
kwargs.setdefault(, self.ndx)
kwargs[] = self.xtc
force = kwargs.pop(, self.force)
if xy:
fitmode =
kwargs.pop(, None)
infix_default =
else:
fitmode... | 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
... |
371,968 | def usergroups_users_update(
self, *, usergroup: str, users: List[str], **kwargs
) -> SlackResponse:
self._validate_xoxp_token()
kwargs.update({"usergroup": usergroup, "users": users})
return self.api_call("usergroups.users.update", json=kwargs) | 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'] |
371,969 | def _bucket_key(self):
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 |
371,970 | def func(nargs: Optional[int] = None, nouts: Optional[int] = None, ndefs: Optional[int] = None):
return lambda f: wraps(f)(WrappedFunction(f, nargs=nargs, nouts=nouts, ndefs=ndefs)) | 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) |
371,971 | def from_backend(self, dagobah_id):
logger.debug(.format(dagobah_id))
rec = self.backend.get_dagobah_json(dagobah_id)
if not rec:
raise DagobahError(
% dagobah_id)
self._construct_from_json(rec) | Reconstruct this Dagobah instance from the backend. |
371,972 | def healthy(self):
try:
if self.is_healthy():
return "OK", 200
else:
return "FAIL", 500
except Exception as e:
self.app.logger.exception(e)
return str(e), 500 | Return 200 is healthy, else 500.
Override is_healthy() to change the health check. |
371,973 | def max_insertion(seqs, gene, domain):
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 == []:
return 100
return max(lengths) | length of largest insertion |
371,974 | def calc_svd(self, lapack_driver=):
if self._isSpectral():
msg = "svd not implemented yet for spectral data class"
raise Exception(msg)
chronos, s, topos = _comp.calc_svd(self.data, lapack_driver=lapack_driver)
return u, s, v | 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... |
371,975 | async def toggle(self):
self.logger.debug("toggle command")
if not self.state == :
return
if self.streamer is None:
return
try:
if self.streamer.is_playing():
await self.pause()
else:
await self.... | Toggles between pause and resume command |
371,976 | def __normalize_args(**keywds):
if isinstance(keywds[], Callable) and \
None is keywds[]:
keywds[] = keywds[]
keywds[] = None
return keywds | implementation details |
371,977 | def save_output_meta(self):
options = self.options
file_path = os.path.join(options.outputdir, )
with open(file_path, ) as outfile:
json.dump(self.OUTPUT_META_DICT, outfile) | Save descriptive output meta data to a JSON file. |
371,978 | def skull_strip(dset,suffix=,prefix=None,unifize=True):
if prefix==None:
prefix = nl.suffix(dset,suffix)
unifize_dset = nl.suffix(dset,)
cmd = bet2 if bet2 else
if unifize:
info = nl.dset_info(dset)
if info==None:
nl.notify( % dset,level=nl.level.error... | use bet to strip skull from given anatomy |
371,979 | def dist_calc(loc1, loc2):
R = 6371.009
dlat = np.radians(abs(loc1[0] - loc2[0]))
dlong = np.radians(abs(loc1[1] - loc2[1]))
ddepth = abs(loc1[2] - loc2[2])
mean_lat = np.radians((loc1[0] + loc2[0]) / 2)
dist = R * np.sqrt(dlat ** 2 + (np.cos(mean_lat) * dlong) ** 2)
dist = np.sqrt(di... | 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... |
371,980 | def get_user_choice(items):
q
choice = raw_input()
while choice != :
try:
item = items[int(choice)]
print
return item
except ValueError:
return None | Returns the selected item from provided items or None if 'q' was
entered for quit. |
371,981 | def shell_split(text):
assert is_text_string(text)
pattern = r.*?(?<!\\)\
out = []
for token in re.split(pattern, text):
if token.strip():
out.append(token.strip().strip("'"))
return out | 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... |
371,982 | def write(self, buf):
assert self.writable
self._check_pid(allow_reset=False)
check_call(_LIB.MXRecordIOWriterWriteRecord(self.handle,
ctypes.c_char_p(buf),
ctypes.c_size_t(len(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)... |
371,983 | def groups(self, labels, collect=None):
if not _is_non_string_iterable(labels):
return self.group(labels, collect=collect)
collect = _zero_on_type_error(collect)
columns = []
labels = self._as_labels(labels)
for label in labels:
if label... | 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... |
371,984 | def update(self, changed_state_model=None, with_expand=False):
if not self.view_is_registered:
return
if changed_state_model is None:
parent_row_iter = None
self.state_row_iter_dict_by_state_path.clear()
self.tree_store.clea... | 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 |
371,985 | def get_available_devices(self):
connected_devices = self.mbeds.list_mbeds() if self.mbeds else []
edbg_ports = self.available_edbg_ports()
for port in edbg_ports:
connected_devices.append({
"platform_name": "SAM4E",
"serial_... | Gets available devices using mbedls and self.available_edbg_ports.
:return: List of connected devices as dictionaries. |
371,986 | def make_directory(self, directory_name, *args, **kwargs):
self.dav_client().mkdir(self.join_path(self.session_path(), directory_name)) | :meth:`.WNetworkClientProto.make_directory` method implementation |
371,987 | def server(self):
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._server = server
return server | UDP server to listen for responses. |
371,988 | def get_randomness_stream(self, decision_point: str, for_initialization: bool=False) -> RandomnessStream:
if decision_point in self._decision_points:
raise RandomnessError(f"Two separate places are attempting to create "
f"the same randomness stream for {de... | 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... |
371,989 | def get_array_dimensions(data):
depths_and_dimensions = get_depths_and_dimensions(data, 0)
grouped_by_depth = {
depth: tuple(dimension for depth, dimension in group)
for depth, group in groupby(depths_and_dimensions, itemgetter(0))
}
invalid_depths_dimensions = tuple(
... | 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) |
371,990 | def prepare_socket(bind_addr, family, type, proto, nodelay, ssl_adapter):
sock = socket.socket(family, type, proto)
prevent_socket_inheritance(sock)
host, port = bind_addr[:2]
IS_EPHEMERAL_PORT = port == 0
if not (IS_WINDOWS or IS_EPHEMERAL_PORT):
... | Create and prepare the socket object. |
371,991 | def batch_fetch_labels(ids):
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 |
371,992 | def add_project(self, ):
i = self.prj_tablev.currentIndex()
item = i.internalPointer()
if item:
project = item.internal_data()
if self._atype:
self._atype.projects.add(project)
elif self._dep:
self._dep.projects.add(pro... | Add a project and store it in the self.projects
:returns: None
:rtype: None
:raises: None |
371,993 | def peek_at(iterable: Iterable[T]) -> Tuple[T, Iterator[T]]:
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 |
371,994 | def main_passpersist(self):
line = sys.stdin.readline().strip()
if not line:
raise EOFError()
if in line:
print("PONG")
elif in line:
oid = self.cut_oid(sys.stdin.readline().strip())
if oid is None:
print("NONE")
elif oid == "":
print(self.get_first())
else:
print(self.g... | Main function that handle SNMP's pass_persist protocol, called by
the start method.
Direct call is unnecessary. |
371,995 | def before_all(ctx):
ctx.client = get_client()
try:
ctx.client.inspect_image(IMAGE)
except NotFound:
ctx.client.pull(IMAGE) | Pulls down busybox:latest before anything is tested. |
371,996 | def alternative_short_name(self, name=None, entry_name=None, limit=None, as_df=False):
q = self.session.query(models.AlternativeShortName)
model_queries_config = (
(name, models.AlternativeShortName.name),
)
q = self.get_model_queries(q, model_queries_config)
... | 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:
- ... |
371,997 | def clear_cache(backend=None):
fileserver = salt.fileserver.Fileserver(__opts__)
cleared, errors = fileserver.clear_cache(back=backend)
ret = {}
if cleared:
ret[] = cleared
if errors:
ret[] = errors
if not ret:
return
return ret | .. 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
... |
371,998 | def handleNotification(self, handle, data):
_LOGGER.debug("Got notification from %s: %s", handle, codecs.encode(data, ))
if handle in self._callbacks:
self._callbacks[handle](data) | Handle Callback from a Bluetooth (GATT) request. |
371,999 | def array_addunique(path, value, create_parents=False, **kwargs):
return _gen_4spec(LCB_SDCMD_ARRAY_ADD_UNIQUE, path, value,
create_path=create_parents, **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,
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.