repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
psss/did | did/plugins/wiki.py | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/wiki.py#L46-L53 | def header(self):
""" Show summary header. """
# Different header for wiki: Updates on xxx: x changes of y pages
item(
"{0}: {1} change{2} of {3} page{4}".format(
self.name, self.changes, "" if self.changes == 1 else "s",
len(self.stats), "" if len(self.stats) == 1 else "s"),
level=0, options=self.options) | [
"def",
"header",
"(",
"self",
")",
":",
"# Different header for wiki: Updates on xxx: x changes of y pages",
"item",
"(",
"\"{0}: {1} change{2} of {3} page{4}\"",
".",
"format",
"(",
"self",
".",
"name",
",",
"self",
".",
"changes",
",",
"\"\"",
"if",
"self",
".",
"... | Show summary header. | [
"Show",
"summary",
"header",
"."
] | python | train |
jtmoulia/switchboard-python | switchboard/__init__.py | https://github.com/jtmoulia/switchboard-python/blob/c9b0cb74cb12a64385465091be633e78d39f08b1/switchboard/__init__.py#L154-L163 | def _get_cmds_id(*cmds):
"""
Returns an identifier for a group of partially tagged commands.
If there are no tagged commands, returns None.
"""
tags = [cmd[2] if len(cmd) == 3 else None for cmd in cmds]
if [tag for tag in tags if tag != None]:
return tuple(tags)
else:
return None | [
"def",
"_get_cmds_id",
"(",
"*",
"cmds",
")",
":",
"tags",
"=",
"[",
"cmd",
"[",
"2",
"]",
"if",
"len",
"(",
"cmd",
")",
"==",
"3",
"else",
"None",
"for",
"cmd",
"in",
"cmds",
"]",
"if",
"[",
"tag",
"for",
"tag",
"in",
"tags",
"if",
"tag",
"!... | Returns an identifier for a group of partially tagged commands.
If there are no tagged commands, returns None. | [
"Returns",
"an",
"identifier",
"for",
"a",
"group",
"of",
"partially",
"tagged",
"commands",
".",
"If",
"there",
"are",
"no",
"tagged",
"commands",
"returns",
"None",
"."
] | python | train |
pmacosta/ptrie | ptrie/ptrie.py | https://github.com/pmacosta/ptrie/blob/c176d3ee810b7b5243c7ff2bbf2f1af0b0fff2a8/ptrie/ptrie.py#L190-L213 | def _delete_subtree(self, nodes):
"""
Delete subtree private method.
No argument validation and usage of getter/setter private methods is
used for speed
"""
nodes = nodes if isinstance(nodes, list) else [nodes]
iobj = [
(self._db[node]["parent"], node)
for node in nodes
if self._node_name_in_tree(node)
]
for parent, node in iobj:
# Delete link to parent (if not root node)
del_list = self._get_subtree(node)
if parent:
self._db[parent]["children"].remove(node)
# Delete children (sub-tree)
for child in del_list:
del self._db[child]
if self._empty_tree():
self._root = None
self._root_hierarchy_length = None | [
"def",
"_delete_subtree",
"(",
"self",
",",
"nodes",
")",
":",
"nodes",
"=",
"nodes",
"if",
"isinstance",
"(",
"nodes",
",",
"list",
")",
"else",
"[",
"nodes",
"]",
"iobj",
"=",
"[",
"(",
"self",
".",
"_db",
"[",
"node",
"]",
"[",
"\"parent\"",
"]"... | Delete subtree private method.
No argument validation and usage of getter/setter private methods is
used for speed | [
"Delete",
"subtree",
"private",
"method",
"."
] | python | train |
Nekmo/amazon-dash | amazon_dash/config.py | https://github.com/Nekmo/amazon-dash/blob/0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b/amazon_dash/config.py#L159-L172 | def bitperm(s, perm, pos):
"""Returns zero if there are no permissions for a bit of the perm. of a file. Otherwise it returns a positive value
:param os.stat_result s: os.stat(file) object
:param str perm: R (Read) or W (Write) or X (eXecute)
:param str pos: USR (USeR) or GRP (GRouP) or OTH (OTHer)
:return: mask value
:rtype: int
"""
perm = perm.upper()
pos = pos.upper()
assert perm in ['R', 'W', 'X']
assert pos in ['USR', 'GRP', 'OTH']
return s.st_mode & getattr(stat, 'S_I{}{}'.format(perm, pos)) | [
"def",
"bitperm",
"(",
"s",
",",
"perm",
",",
"pos",
")",
":",
"perm",
"=",
"perm",
".",
"upper",
"(",
")",
"pos",
"=",
"pos",
".",
"upper",
"(",
")",
"assert",
"perm",
"in",
"[",
"'R'",
",",
"'W'",
",",
"'X'",
"]",
"assert",
"pos",
"in",
"["... | Returns zero if there are no permissions for a bit of the perm. of a file. Otherwise it returns a positive value
:param os.stat_result s: os.stat(file) object
:param str perm: R (Read) or W (Write) or X (eXecute)
:param str pos: USR (USeR) or GRP (GRouP) or OTH (OTHer)
:return: mask value
:rtype: int | [
"Returns",
"zero",
"if",
"there",
"are",
"no",
"permissions",
"for",
"a",
"bit",
"of",
"the",
"perm",
".",
"of",
"a",
"file",
".",
"Otherwise",
"it",
"returns",
"a",
"positive",
"value"
] | python | test |
zetaops/zengine | zengine/lib/utils.py | https://github.com/zetaops/zengine/blob/b5bc32d3b37bca799f8985be916f04528ac79e4a/zengine/lib/utils.py#L34-L43 | def to_safe_str(s):
"""
converts some (tr) non-ascii chars to ascii counterparts,
then return the result as lowercase
"""
# TODO: This is insufficient as it doesn't do anything for other non-ascii chars
return re.sub(r'[^0-9a-zA-Z]+', '_', s.strip().replace(u'ğ', 'g').replace(u'ö', 'o').replace(
u'ç', 'c').replace(u'Ç','c').replace(u'Ö', u'O').replace(u'Ş', 's').replace(
u'Ü', 'u').replace(u'ı', 'i').replace(u'İ','i').replace(u'Ğ', 'g').replace(
u'ö', 'o').replace(u'ş', 's').replace(u'ü', 'u').lower(), re.UNICODE) | [
"def",
"to_safe_str",
"(",
"s",
")",
":",
"# TODO: This is insufficient as it doesn't do anything for other non-ascii chars",
"return",
"re",
".",
"sub",
"(",
"r'[^0-9a-zA-Z]+'",
",",
"'_'",
",",
"s",
".",
"strip",
"(",
")",
".",
"replace",
"(",
"u'ğ',",
" ",
"g')... | converts some (tr) non-ascii chars to ascii counterparts,
then return the result as lowercase | [
"converts",
"some",
"(",
"tr",
")",
"non",
"-",
"ascii",
"chars",
"to",
"ascii",
"counterparts",
"then",
"return",
"the",
"result",
"as",
"lowercase"
] | python | train |
pkgw/pwkit | pwkit/io.py | https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/io.py#L125-L131 | def make_path_func (*baseparts):
"""Return a function that joins paths onto some base directory."""
from os.path import join
base = join (*baseparts)
def path_func (*args):
return join (base, *args)
return path_func | [
"def",
"make_path_func",
"(",
"*",
"baseparts",
")",
":",
"from",
"os",
".",
"path",
"import",
"join",
"base",
"=",
"join",
"(",
"*",
"baseparts",
")",
"def",
"path_func",
"(",
"*",
"args",
")",
":",
"return",
"join",
"(",
"base",
",",
"*",
"args",
... | Return a function that joins paths onto some base directory. | [
"Return",
"a",
"function",
"that",
"joins",
"paths",
"onto",
"some",
"base",
"directory",
"."
] | python | train |
joke2k/django-environ | environ/environ.py | https://github.com/joke2k/django-environ/blob/c2620021614557abe197578f99deeef42af3e082/environ/environ.py#L157-L161 | def int(self, var, default=NOTSET):
"""
:rtype: int
"""
return self.get_value(var, cast=int, default=default) | [
"def",
"int",
"(",
"self",
",",
"var",
",",
"default",
"=",
"NOTSET",
")",
":",
"return",
"self",
".",
"get_value",
"(",
"var",
",",
"cast",
"=",
"int",
",",
"default",
"=",
"default",
")"
] | :rtype: int | [
":",
"rtype",
":",
"int"
] | python | train |
Azure/azure-cosmos-python | azure/cosmos/routing/collection_routing_map.py | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/routing/collection_routing_map.py#L74-L94 | def get_range_by_effective_partition_key(self, effective_partition_key_value):
"""Gets the range containing the given partition key
:param str effective_partition_key_value:
The partition key value.
:return:
The partition key range.
:rtype: dict
"""
if _CollectionRoutingMap.MinimumInclusiveEffectivePartitionKey == effective_partition_key_value:
return self._orderedPartitionKeyRanges[0]
if _CollectionRoutingMap.MaximumExclusiveEffectivePartitionKey == effective_partition_key_value:
return None
sortedLow = [(r.min, not r.isMinInclusive) for r in self._orderedRanges]
index = bisect.bisect_right(sortedLow, (effective_partition_key_value, True))
if (index > 0):
index = index -1
return self._orderedPartitionKeyRanges[index] | [
"def",
"get_range_by_effective_partition_key",
"(",
"self",
",",
"effective_partition_key_value",
")",
":",
"if",
"_CollectionRoutingMap",
".",
"MinimumInclusiveEffectivePartitionKey",
"==",
"effective_partition_key_value",
":",
"return",
"self",
".",
"_orderedPartitionKeyRanges"... | Gets the range containing the given partition key
:param str effective_partition_key_value:
The partition key value.
:return:
The partition key range.
:rtype: dict | [
"Gets",
"the",
"range",
"containing",
"the",
"given",
"partition",
"key"
] | python | train |
waqasbhatti/astrobase | astrobase/lcproc/checkplotgen.py | https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/checkplotgen.py#L1239-L1483 | def parallel_cp_pfdir(pfpickledir,
outdir,
lcbasedir,
pfpickleglob='periodfinding-*.pkl*',
lclistpkl=None,
cprenorm=False,
nbrradiusarcsec=60.0,
maxnumneighbors=5,
makeneighborlcs=True,
fast_mode=False,
gaia_max_timeout=60.0,
gaia_mirror=None,
xmatchinfo=None,
xmatchradiusarcsec=3.0,
minobservations=99,
sigclip=10.0,
lcformat='hat-sql',
lcformatdir=None,
timecols=None,
magcols=None,
errcols=None,
skipdone=False,
done_callback=None,
done_callback_args=None,
done_callback_kwargs=None,
maxobjects=None,
nworkers=32):
'''This drives the parallel execution of `runcp` for a directory of
periodfinding pickles.
Parameters
----------
pfpickledir : str
This is the directory containing all of the period-finding pickles to
process.
outdir : str
The directory the checkplot pickles will be written to.
lcbasedir : str
The base directory that this function will look in to find the light
curves pointed to by the period-finding result files. If you're using
`lcfnamelist` to provide a list of light curve filenames directly, this
arg is ignored.
pkpickleglob : str
This is a UNIX file glob to select period-finding result pickles in the
specified `pfpickledir`.
lclistpkl : str or dict
This is either the filename of a pickle or the actual dict produced by
lcproc.make_lclist. This is used to gather neighbor information.
cprenorm : bool
Set this to True if the light curves should be renormalized by
`checkplot.checkplot_pickle`. This is set to False by default because we
do our own normalization in this function using the light curve's
registered normalization function and pass the normalized times, mags,
errs to the `checkplot.checkplot_pickle` function.
nbrradiusarcsec : float
The radius in arcseconds to use for a search conducted around the
coordinates of this object to look for any potential confusion and
blending of variability amplitude caused by their proximity.
maxnumneighbors : int
The maximum number of neighbors that will have their light curves and
magnitudes noted in this checkplot as potential blends with the target
object.
makeneighborlcs : bool
If True, will make light curve and phased light curve plots for all
neighbors found in the object collection for each input object.
fast_mode : bool or float
This runs the external catalog operations in a "fast" mode, with short
timeouts and not trying to hit external catalogs that take a long time
to respond.
If this is set to True, the default settings for the external requests
will then become::
skyview_lookup = False
skyview_timeout = 10.0
skyview_retry_failed = False
dust_timeout = 10.0
gaia_submit_timeout = 7.0
gaia_max_timeout = 10.0
gaia_submit_tries = 2
complete_query_later = False
search_simbad = False
If this is a float, will run in "fast" mode with the provided timeout
value in seconds and the following settings::
skyview_lookup = True
skyview_timeout = fast_mode
skyview_retry_failed = False
dust_timeout = fast_mode
gaia_submit_timeout = 0.66*fast_mode
gaia_max_timeout = fast_mode
gaia_submit_tries = 2
complete_query_later = False
search_simbad = False
gaia_max_timeout : float
Sets the timeout in seconds to use when waiting for the GAIA service to
respond to our request for the object's information. Note that if
`fast_mode` is set, this is ignored.
gaia_mirror : str or None
This sets the GAIA mirror to use. This is a key in the
`services.gaia.GAIA_URLS` dict which defines the URLs to hit for each
mirror.
xmatchinfo : str or dict
This is either the xmatch dict produced by the function
`load_xmatch_external_catalogs` above, or the path to the xmatch info
pickle file produced by that function.
xmatchradiusarcsec : float
This is the cross-matching radius to use in arcseconds.
minobservations : int
The minimum of observations the input object's mag/flux time-series must
have for this function to plot its light curve and phased light
curve. If the object has less than this number, no light curves will be
plotted, but the checkplotdict will still contain all of the other
information.
sigclip : float or int or sequence of two floats/ints or None
If a single float or int, a symmetric sigma-clip will be performed using
the number provided as the sigma-multiplier to cut out from the input
time-series.
If a list of two ints/floats is provided, the function will perform an
'asymmetric' sigma-clip. The first element in this list is the sigma
value to use for fainter flux/mag values; the second element in this
list is the sigma value to use for brighter flux/mag values. For
example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma
dimmings and greater than 3-sigma brightenings. Here the meaning of
"dimming" and "brightening" is set by *physics* (not the magnitude
system), which is why the `magsarefluxes` kwarg must be correctly set.
If `sigclip` is None, no sigma-clipping will be performed, and the
time-series (with non-finite elems removed) will be passed through to
the output.
lcformat : str
This is the `formatkey` associated with your light curve format, which
you previously passed in to the `lcproc.register_lcformat`
function. This will be used to look up how to find and read the light
curves specified in `basedir` or `use_list_of_filenames`.
lcformatdir : str or None
If this is provided, gives the path to a directory when you've stored
your lcformat description JSONs, other than the usual directories lcproc
knows to search for them in. Use this along with `lcformat` to specify
an LC format JSON file that's not currently registered with lcproc.
timecols : list of str or None
The timecol keys to use from the lcdict in generating this checkplot.
magcols : list of str or None
The magcol keys to use from the lcdict in generating this checkplot.
errcols : list of str or None
The errcol keys to use from the lcdict in generating this checkplot.
skipdone : bool
This indicates if this function will skip creating checkplots that
already exist corresponding to the current `objectid` and `magcol`. If
`skipdone` is set to True, this will be done.
done_callback : Python function or None
This is used to provide a function to execute after the checkplot
pickles are generated. This is useful if you want to stream the results
of checkplot making to some other process, e.g. directly running an
ingestion into an LCC-Server collection. The function will always get
the list of the generated checkplot pickles as its first arg, and all of
the kwargs for runcp in the kwargs dict. Additional args and kwargs can
be provided by giving a list in the `done_callbacks_args` kwarg and a
dict in the `done_callbacks_kwargs` kwarg.
NOTE: the function you pass in here should be pickleable by normal
Python if you want to use it with the parallel_cp and parallel_cp_lcdir
functions below.
done_callback_args : tuple or None
If not None, contains any args to pass into the `done_callback`
function.
done_callback_kwargs : dict or None
If not None, contains any kwargs to pass into the `done_callback`
function.
maxobjects : int
The maximum number of objects to process in this run.
nworkers : int
The number of parallel workers that will work on the checkplot
generation process.
Returns
-------
dict
This returns a dict with keys = input period-finding pickles and vals =
list of the corresponding checkplot pickles produced.
'''
pfpicklelist = sorted(glob.glob(os.path.join(pfpickledir, pfpickleglob)))
LOGINFO('found %s period-finding pickles, running cp...' %
len(pfpicklelist))
return parallel_cp(pfpicklelist,
outdir,
lcbasedir,
fast_mode=fast_mode,
lclistpkl=lclistpkl,
nbrradiusarcsec=nbrradiusarcsec,
gaia_max_timeout=gaia_max_timeout,
gaia_mirror=gaia_mirror,
maxnumneighbors=maxnumneighbors,
makeneighborlcs=makeneighborlcs,
xmatchinfo=xmatchinfo,
xmatchradiusarcsec=xmatchradiusarcsec,
sigclip=sigclip,
minobservations=minobservations,
cprenorm=cprenorm,
maxobjects=maxobjects,
lcformat=lcformat,
lcformatdir=lcformatdir,
timecols=timecols,
magcols=magcols,
errcols=errcols,
skipdone=skipdone,
nworkers=nworkers,
done_callback=done_callback,
done_callback_args=done_callback_args,
done_callback_kwargs=done_callback_kwargs) | [
"def",
"parallel_cp_pfdir",
"(",
"pfpickledir",
",",
"outdir",
",",
"lcbasedir",
",",
"pfpickleglob",
"=",
"'periodfinding-*.pkl*'",
",",
"lclistpkl",
"=",
"None",
",",
"cprenorm",
"=",
"False",
",",
"nbrradiusarcsec",
"=",
"60.0",
",",
"maxnumneighbors",
"=",
"... | This drives the parallel execution of `runcp` for a directory of
periodfinding pickles.
Parameters
----------
pfpickledir : str
This is the directory containing all of the period-finding pickles to
process.
outdir : str
The directory the checkplot pickles will be written to.
lcbasedir : str
The base directory that this function will look in to find the light
curves pointed to by the period-finding result files. If you're using
`lcfnamelist` to provide a list of light curve filenames directly, this
arg is ignored.
pkpickleglob : str
This is a UNIX file glob to select period-finding result pickles in the
specified `pfpickledir`.
lclistpkl : str or dict
This is either the filename of a pickle or the actual dict produced by
lcproc.make_lclist. This is used to gather neighbor information.
cprenorm : bool
Set this to True if the light curves should be renormalized by
`checkplot.checkplot_pickle`. This is set to False by default because we
do our own normalization in this function using the light curve's
registered normalization function and pass the normalized times, mags,
errs to the `checkplot.checkplot_pickle` function.
nbrradiusarcsec : float
The radius in arcseconds to use for a search conducted around the
coordinates of this object to look for any potential confusion and
blending of variability amplitude caused by their proximity.
maxnumneighbors : int
The maximum number of neighbors that will have their light curves and
magnitudes noted in this checkplot as potential blends with the target
object.
makeneighborlcs : bool
If True, will make light curve and phased light curve plots for all
neighbors found in the object collection for each input object.
fast_mode : bool or float
This runs the external catalog operations in a "fast" mode, with short
timeouts and not trying to hit external catalogs that take a long time
to respond.
If this is set to True, the default settings for the external requests
will then become::
skyview_lookup = False
skyview_timeout = 10.0
skyview_retry_failed = False
dust_timeout = 10.0
gaia_submit_timeout = 7.0
gaia_max_timeout = 10.0
gaia_submit_tries = 2
complete_query_later = False
search_simbad = False
If this is a float, will run in "fast" mode with the provided timeout
value in seconds and the following settings::
skyview_lookup = True
skyview_timeout = fast_mode
skyview_retry_failed = False
dust_timeout = fast_mode
gaia_submit_timeout = 0.66*fast_mode
gaia_max_timeout = fast_mode
gaia_submit_tries = 2
complete_query_later = False
search_simbad = False
gaia_max_timeout : float
Sets the timeout in seconds to use when waiting for the GAIA service to
respond to our request for the object's information. Note that if
`fast_mode` is set, this is ignored.
gaia_mirror : str or None
This sets the GAIA mirror to use. This is a key in the
`services.gaia.GAIA_URLS` dict which defines the URLs to hit for each
mirror.
xmatchinfo : str or dict
This is either the xmatch dict produced by the function
`load_xmatch_external_catalogs` above, or the path to the xmatch info
pickle file produced by that function.
xmatchradiusarcsec : float
This is the cross-matching radius to use in arcseconds.
minobservations : int
The minimum of observations the input object's mag/flux time-series must
have for this function to plot its light curve and phased light
curve. If the object has less than this number, no light curves will be
plotted, but the checkplotdict will still contain all of the other
information.
sigclip : float or int or sequence of two floats/ints or None
If a single float or int, a symmetric sigma-clip will be performed using
the number provided as the sigma-multiplier to cut out from the input
time-series.
If a list of two ints/floats is provided, the function will perform an
'asymmetric' sigma-clip. The first element in this list is the sigma
value to use for fainter flux/mag values; the second element in this
list is the sigma value to use for brighter flux/mag values. For
example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma
dimmings and greater than 3-sigma brightenings. Here the meaning of
"dimming" and "brightening" is set by *physics* (not the magnitude
system), which is why the `magsarefluxes` kwarg must be correctly set.
If `sigclip` is None, no sigma-clipping will be performed, and the
time-series (with non-finite elems removed) will be passed through to
the output.
lcformat : str
This is the `formatkey` associated with your light curve format, which
you previously passed in to the `lcproc.register_lcformat`
function. This will be used to look up how to find and read the light
curves specified in `basedir` or `use_list_of_filenames`.
lcformatdir : str or None
If this is provided, gives the path to a directory when you've stored
your lcformat description JSONs, other than the usual directories lcproc
knows to search for them in. Use this along with `lcformat` to specify
an LC format JSON file that's not currently registered with lcproc.
timecols : list of str or None
The timecol keys to use from the lcdict in generating this checkplot.
magcols : list of str or None
The magcol keys to use from the lcdict in generating this checkplot.
errcols : list of str or None
The errcol keys to use from the lcdict in generating this checkplot.
skipdone : bool
This indicates if this function will skip creating checkplots that
already exist corresponding to the current `objectid` and `magcol`. If
`skipdone` is set to True, this will be done.
done_callback : Python function or None
This is used to provide a function to execute after the checkplot
pickles are generated. This is useful if you want to stream the results
of checkplot making to some other process, e.g. directly running an
ingestion into an LCC-Server collection. The function will always get
the list of the generated checkplot pickles as its first arg, and all of
the kwargs for runcp in the kwargs dict. Additional args and kwargs can
be provided by giving a list in the `done_callbacks_args` kwarg and a
dict in the `done_callbacks_kwargs` kwarg.
NOTE: the function you pass in here should be pickleable by normal
Python if you want to use it with the parallel_cp and parallel_cp_lcdir
functions below.
done_callback_args : tuple or None
If not None, contains any args to pass into the `done_callback`
function.
done_callback_kwargs : dict or None
If not None, contains any kwargs to pass into the `done_callback`
function.
maxobjects : int
The maximum number of objects to process in this run.
nworkers : int
The number of parallel workers that will work on the checkplot
generation process.
Returns
-------
dict
This returns a dict with keys = input period-finding pickles and vals =
list of the corresponding checkplot pickles produced. | [
"This",
"drives",
"the",
"parallel",
"execution",
"of",
"runcp",
"for",
"a",
"directory",
"of",
"periodfinding",
"pickles",
"."
] | python | valid |
CiscoDevNet/webexteamssdk | webexteamssdk/utils.py | https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/utils.py#L100-L110 | def is_web_url(string):
"""Check to see if string is an validly-formatted web url."""
assert isinstance(string, basestring)
parsed_url = urllib.parse.urlparse(string)
return (
(
parsed_url.scheme.lower() == 'http'
or parsed_url.scheme.lower() == 'https'
)
and parsed_url.netloc
) | [
"def",
"is_web_url",
"(",
"string",
")",
":",
"assert",
"isinstance",
"(",
"string",
",",
"basestring",
")",
"parsed_url",
"=",
"urllib",
".",
"parse",
".",
"urlparse",
"(",
"string",
")",
"return",
"(",
"(",
"parsed_url",
".",
"scheme",
".",
"lower",
"(... | Check to see if string is an validly-formatted web url. | [
"Check",
"to",
"see",
"if",
"string",
"is",
"an",
"validly",
"-",
"formatted",
"web",
"url",
"."
] | python | test |
matrix-org/matrix-python-sdk | matrix_client/room.py | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L614-L622 | def set_guest_access(self, allow_guests):
"""Set whether guests can join the room and return True if successful."""
guest_access = "can_join" if allow_guests else "forbidden"
try:
self.client.api.set_guest_access(self.room_id, guest_access)
self.guest_access = allow_guests
return True
except MatrixRequestError:
return False | [
"def",
"set_guest_access",
"(",
"self",
",",
"allow_guests",
")",
":",
"guest_access",
"=",
"\"can_join\"",
"if",
"allow_guests",
"else",
"\"forbidden\"",
"try",
":",
"self",
".",
"client",
".",
"api",
".",
"set_guest_access",
"(",
"self",
".",
"room_id",
",",... | Set whether guests can join the room and return True if successful. | [
"Set",
"whether",
"guests",
"can",
"join",
"the",
"room",
"and",
"return",
"True",
"if",
"successful",
"."
] | python | train |
tarbell-project/tarbell | tarbell/app.py | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/app.py#L487-L511 | def get_context_from_csv(self):
"""
Open CONTEXT_SOURCE_FILE, parse and return a context
"""
if re.search('^(http|https)://', self.project.CONTEXT_SOURCE_FILE):
data = requests.get(self.project.CONTEXT_SOURCE_FILE)
reader = csv.reader(
data.iter_lines(), delimiter=',', quotechar='"')
ret = {rows[0]: rows[1] for rows in reader}
else:
try:
with open(self.project.CONTEXT_SOURCE_FILE) as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
ret = {rows[0]: rows[1] for rows in reader}
except IOError:
file = "%s/%s" % (
os.path.abspath(self.path),
self.project.CONTEXT_SOURCE_FILE)
with open(file) as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
ret = {rows[0]: rows[1] for rows in reader}
ret.update({
"CONTEXT_SOURCE_FILE": self.project.CONTEXT_SOURCE_FILE,
})
return ret | [
"def",
"get_context_from_csv",
"(",
"self",
")",
":",
"if",
"re",
".",
"search",
"(",
"'^(http|https)://'",
",",
"self",
".",
"project",
".",
"CONTEXT_SOURCE_FILE",
")",
":",
"data",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"project",
".",
"CONTEXT_S... | Open CONTEXT_SOURCE_FILE, parse and return a context | [
"Open",
"CONTEXT_SOURCE_FILE",
"parse",
"and",
"return",
"a",
"context"
] | python | train |
kipe/enocean | enocean/protocol/eep.py | https://github.com/kipe/enocean/blob/99fa03f47004eef74c7987545c33ecd01af0de07/enocean/protocol/eep.py#L70-L89 | def _get_value(self, source, bitarray):
''' Get value, based on the data in XML '''
raw_value = self._get_raw(source, bitarray)
rng = source.find('range')
rng_min = float(rng.find('min').text)
rng_max = float(rng.find('max').text)
scl = source.find('scale')
scl_min = float(scl.find('min').text)
scl_max = float(scl.find('max').text)
return {
source['shortcut']: {
'description': source.get('description'),
'unit': source['unit'],
'value': (scl_max - scl_min) / (rng_max - rng_min) * (raw_value - rng_min) + scl_min,
'raw_value': raw_value,
}
} | [
"def",
"_get_value",
"(",
"self",
",",
"source",
",",
"bitarray",
")",
":",
"raw_value",
"=",
"self",
".",
"_get_raw",
"(",
"source",
",",
"bitarray",
")",
"rng",
"=",
"source",
".",
"find",
"(",
"'range'",
")",
"rng_min",
"=",
"float",
"(",
"rng",
"... | Get value, based on the data in XML | [
"Get",
"value",
"based",
"on",
"the",
"data",
"in",
"XML"
] | python | train |
SheffieldML/GPy | GPy/models/state_space_main.py | https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/models/state_space_main.py#L244-L275 | def R_isrk(self, k):
"""
Function returns the inverse square root of R matrix on step k.
"""
ind = int(self.index[self.R_time_var_index, k])
R = self.R[:, :, ind]
if (R.shape[0] == 1): # 1-D case handle simplier. No storage
# of the result, just compute it each time.
inv_square_root = np.sqrt(1.0/R)
else:
if self.svd_each_time:
(U, S, Vh) = sp.linalg.svd(R, full_matrices=False,
compute_uv=True, overwrite_a=False,
check_finite=True)
inv_square_root = U * 1.0/np.sqrt(S)
else:
if ind in self.R_square_root:
inv_square_root = self.R_square_root[ind]
else:
(U, S, Vh) = sp.linalg.svd(R, full_matrices=False,
compute_uv=True,
overwrite_a=False,
check_finite=True)
inv_square_root = U * 1.0/np.sqrt(S)
self.R_square_root[ind] = inv_square_root
return inv_square_root | [
"def",
"R_isrk",
"(",
"self",
",",
"k",
")",
":",
"ind",
"=",
"int",
"(",
"self",
".",
"index",
"[",
"self",
".",
"R_time_var_index",
",",
"k",
"]",
")",
"R",
"=",
"self",
".",
"R",
"[",
":",
",",
":",
",",
"ind",
"]",
"if",
"(",
"R",
".",
... | Function returns the inverse square root of R matrix on step k. | [
"Function",
"returns",
"the",
"inverse",
"square",
"root",
"of",
"R",
"matrix",
"on",
"step",
"k",
"."
] | python | train |
seyriz/taiga-contrib-google-auth | back/taiga_contrib_google_auth/services.py | https://github.com/seyriz/taiga-contrib-google-auth/blob/e9fb5d062027a055e09f7614aa2e48eab7a8604b/back/taiga_contrib_google_auth/services.py#L36-L72 | def google_register(username:str, email:str, full_name:str, google_id:int, bio:str, token:str=None):
"""
Register a new user from google.
This can raise `exc.IntegrityError` exceptions in
case of conflics found.
:returns: User
"""
auth_data_model = apps.get_model("users", "AuthData")
user_model = apps.get_model("users", "User")
try:
# Google user association exist?
auth_data = auth_data_model.objects.get(key="google", value=google_id)
user = auth_data.user
except auth_data_model.DoesNotExist:
try:
# Is a user with the same email as the google user?
user = user_model.objects.get(email=email)
auth_data_model.objects.create(user=user, key="google", value=google_id, extra={})
except user_model.DoesNotExist:
# Create a new user
username_unique = slugify_uniquely(username, user_model, slugfield="username")
user = user_model.objects.create(email=email,
username=username_unique,
full_name=full_name,
bio=bio)
auth_data_model.objects.create(user=user, key="google", value=google_id, extra={})
send_register_email(user)
user_registered_signal.send(sender=user.__class__, user=user)
if token:
membership = get_membership_by_token(token)
membership.user = user
membership.save(update_fields=["user"])
return user | [
"def",
"google_register",
"(",
"username",
":",
"str",
",",
"email",
":",
"str",
",",
"full_name",
":",
"str",
",",
"google_id",
":",
"int",
",",
"bio",
":",
"str",
",",
"token",
":",
"str",
"=",
"None",
")",
":",
"auth_data_model",
"=",
"apps",
".",... | Register a new user from google.
This can raise `exc.IntegrityError` exceptions in
case of conflics found.
:returns: User | [
"Register",
"a",
"new",
"user",
"from",
"google",
".",
"This",
"can",
"raise",
"exc",
".",
"IntegrityError",
"exceptions",
"in",
"case",
"of",
"conflics",
"found",
".",
":",
"returns",
":",
"User"
] | python | train |
bcbio/bcbio-nextgen | bcbio/broad/metrics.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/broad/metrics.py#L50-L72 | def extract_metrics(self, metrics_files):
"""Return summary information for a lane of metrics files.
"""
extension_maps = dict(
align_metrics=(self._parse_align_metrics, "AL"),
dup_metrics=(self._parse_dup_metrics, "DUP"),
hs_metrics=(self._parse_hybrid_metrics, "HS"),
insert_metrics=(self._parse_insert_metrics, "INS"),
rnaseq_metrics=(self._parse_rnaseq_metrics, "RNA"))
all_metrics = dict()
for fname in metrics_files:
ext = os.path.splitext(fname)[-1][1:]
try:
parse_fn, prefix = extension_maps[ext]
except KeyError:
parse_fn = None
if parse_fn:
with open(fname) as in_handle:
for key, val in parse_fn(in_handle).items():
if not key.startswith(prefix):
key = "%s_%s" % (prefix, key)
all_metrics[key] = val
return all_metrics | [
"def",
"extract_metrics",
"(",
"self",
",",
"metrics_files",
")",
":",
"extension_maps",
"=",
"dict",
"(",
"align_metrics",
"=",
"(",
"self",
".",
"_parse_align_metrics",
",",
"\"AL\"",
")",
",",
"dup_metrics",
"=",
"(",
"self",
".",
"_parse_dup_metrics",
",",... | Return summary information for a lane of metrics files. | [
"Return",
"summary",
"information",
"for",
"a",
"lane",
"of",
"metrics",
"files",
"."
] | python | train |
ciena/afkak | afkak/producer.py | https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/producer.py#L451-L481 | def _cancel_send_messages(self, d):
"""Cancel a `send_messages` request
First check if the request is in a waiting batch, of so, great, remove
it from the batch. If it's not found, we errback() the deferred and
the downstream processing steps take care of aborting further
processing.
We check if there's a current _batch_send_d to determine where in the
chain we were (getting partitions, or already sent request to Kafka)
and errback differently.
"""
# Is the request in question in an unsent batch?
for req in self._batch_reqs:
if req.deferred == d:
# Found the request, remove it and return.
msgs = req.messages
self._waitingMsgCount -= len(msgs)
for m in (_m for _m in msgs if _m is not None):
self._waitingByteCount -= len(m)
# This _should_ be safe as we abort the iteration upon removal
self._batch_reqs.remove(req)
d.errback(CancelledError(request_sent=False))
return
# If it wasn't found in the unsent batch. We just rely on the
# downstream processing of the request to check if the deferred
# has been called and skip further processing for this request
# Errback the deferred with whether or not we sent the request
# to Kafka already
d.errback(
CancelledError(request_sent=(self._batch_send_d is not None)))
return | [
"def",
"_cancel_send_messages",
"(",
"self",
",",
"d",
")",
":",
"# Is the request in question in an unsent batch?",
"for",
"req",
"in",
"self",
".",
"_batch_reqs",
":",
"if",
"req",
".",
"deferred",
"==",
"d",
":",
"# Found the request, remove it and return.",
"msgs"... | Cancel a `send_messages` request
First check if the request is in a waiting batch, of so, great, remove
it from the batch. If it's not found, we errback() the deferred and
the downstream processing steps take care of aborting further
processing.
We check if there's a current _batch_send_d to determine where in the
chain we were (getting partitions, or already sent request to Kafka)
and errback differently. | [
"Cancel",
"a",
"send_messages",
"request",
"First",
"check",
"if",
"the",
"request",
"is",
"in",
"a",
"waiting",
"batch",
"of",
"so",
"great",
"remove",
"it",
"from",
"the",
"batch",
".",
"If",
"it",
"s",
"not",
"found",
"we",
"errback",
"()",
"the",
"... | python | train |
ForensicArtifacts/artifacts | tools/stats.py | https://github.com/ForensicArtifacts/artifacts/blob/044a63bfb4448af33d085c69066c80f9505ae7ca/tools/stats.py#L114-L120 | def PrintStats(self):
"""Build stats and print in MarkDown format."""
self.BuildStats()
self.PrintSummaryTable()
self.PrintSourceTypeTable()
self.PrintOSTable()
self.PrintLabelTable() | [
"def",
"PrintStats",
"(",
"self",
")",
":",
"self",
".",
"BuildStats",
"(",
")",
"self",
".",
"PrintSummaryTable",
"(",
")",
"self",
".",
"PrintSourceTypeTable",
"(",
")",
"self",
".",
"PrintOSTable",
"(",
")",
"self",
".",
"PrintLabelTable",
"(",
")"
] | Build stats and print in MarkDown format. | [
"Build",
"stats",
"and",
"print",
"in",
"MarkDown",
"format",
"."
] | python | train |
spacetelescope/stsci.tools | lib/stsci/tools/wcsutil.py | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/wcsutil.py#L824-L864 | def archive(self,prepend=None,overwrite=no,quiet=yes):
""" Create backup copies of the WCS keywords with the given prepended
string.
If backup keywords are already present, only update them if
'overwrite' is set to 'yes', otherwise, do warn the user and do nothing.
Set the WCSDATE at this time as well.
"""
# Verify that existing backup values are not overwritten accidentally.
if len(list(self.backup.keys())) > 0 and overwrite == no:
if not quiet:
print('WARNING: Backup WCS keywords already exist! No backup made.')
print(' The values can only be overridden if overwrite=yes.')
return
# Establish what prepend string to use...
if prepend is None:
if self.prepend is not None:
_prefix = self.prepend
else:
_prefix = DEFAULT_PREFIX
else:
_prefix = prepend
# Update backup and orig_wcs dictionaries
# We have archive keywords and a defined prefix
# Go through and append them to self.backup
self.prepend = _prefix
for key in self.wcstrans.keys():
if key != 'pixel scale':
_archive_key = self._buildNewKeyname(key,_prefix)
else:
_archive_key = self.prepend.lower()+'pscale'
# if key != 'pixel scale':
self.orig_wcs[_archive_key] = self.__dict__[self.wcstrans[key]]
self.backup[key] = _archive_key
self.revert[_archive_key] = key
# Setup keyword to record when these keywords were backed up.
self.orig_wcs['WCSCDATE']= fileutil.getLTime()
self.backup['WCSCDATE'] = 'WCSCDATE'
self.revert['WCSCDATE'] = 'WCSCDATE' | [
"def",
"archive",
"(",
"self",
",",
"prepend",
"=",
"None",
",",
"overwrite",
"=",
"no",
",",
"quiet",
"=",
"yes",
")",
":",
"# Verify that existing backup values are not overwritten accidentally.",
"if",
"len",
"(",
"list",
"(",
"self",
".",
"backup",
".",
"k... | Create backup copies of the WCS keywords with the given prepended
string.
If backup keywords are already present, only update them if
'overwrite' is set to 'yes', otherwise, do warn the user and do nothing.
Set the WCSDATE at this time as well. | [
"Create",
"backup",
"copies",
"of",
"the",
"WCS",
"keywords",
"with",
"the",
"given",
"prepended",
"string",
".",
"If",
"backup",
"keywords",
"are",
"already",
"present",
"only",
"update",
"them",
"if",
"overwrite",
"is",
"set",
"to",
"yes",
"otherwise",
"do... | python | train |
theislab/scanpy | scanpy/readwrite.py | https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/readwrite.py#L93-L135 | def read_10x_h5(filename, genome=None, gex_only=True) -> AnnData:
"""Read 10x-Genomics-formatted hdf5 file.
Parameters
----------
filename : `str` | :class:`~pathlib.Path`
Filename.
genome : `str`, optional (default: ``None``)
Filter expression to this genes within this genome. For legacy 10x h5
files, this must be provided if the data contains more than one genome.
gex_only : `bool`, optional (default: `True`)
Only keep 'Gene Expression' data and ignore other feature types,
e.g. 'Antibody Capture', 'CRISPR Guide Capture', or 'Custom'
Returns
-------
Annotated data matrix, where obsevations/cells are named by their
barcode and variables/genes by gene name. The data matrix is stored in
`adata.X`, cell names in `adata.obs_names` and gene names in
`adata.var_names`. The gene IDs are stored in `adata.var['gene_ids']`.
The feature types are stored in `adata.var['feature_types']`
"""
logg.info('reading', filename, r=True, end=' ')
with tables.open_file(str(filename), 'r') as f:
v3 = '/matrix' in f
if v3:
adata = _read_v3_10x_h5(filename)
if genome:
if genome not in adata.var['genome'].values:
raise ValueError(
"Could not find data corresponding to genome '{genome}' in '{filename}'. "
"Available genomes are: {avail}."
.format(
genome=genome, filename=filename,
avail=list(adata.var["genome"].unique()),
)
)
adata = adata[:, list(map(lambda x: x == str(genome), adata.var['genome']))]
if gex_only:
adata = adata[:, list(map(lambda x: x == 'Gene Expression', adata.var['feature_types']))]
return adata
else:
return _read_legacy_10x_h5(filename, genome=genome) | [
"def",
"read_10x_h5",
"(",
"filename",
",",
"genome",
"=",
"None",
",",
"gex_only",
"=",
"True",
")",
"->",
"AnnData",
":",
"logg",
".",
"info",
"(",
"'reading'",
",",
"filename",
",",
"r",
"=",
"True",
",",
"end",
"=",
"' '",
")",
"with",
"tables",
... | Read 10x-Genomics-formatted hdf5 file.
Parameters
----------
filename : `str` | :class:`~pathlib.Path`
Filename.
genome : `str`, optional (default: ``None``)
Filter expression to this genes within this genome. For legacy 10x h5
files, this must be provided if the data contains more than one genome.
gex_only : `bool`, optional (default: `True`)
Only keep 'Gene Expression' data and ignore other feature types,
e.g. 'Antibody Capture', 'CRISPR Guide Capture', or 'Custom'
Returns
-------
Annotated data matrix, where obsevations/cells are named by their
barcode and variables/genes by gene name. The data matrix is stored in
`adata.X`, cell names in `adata.obs_names` and gene names in
`adata.var_names`. The gene IDs are stored in `adata.var['gene_ids']`.
The feature types are stored in `adata.var['feature_types']` | [
"Read",
"10x",
"-",
"Genomics",
"-",
"formatted",
"hdf5",
"file",
"."
] | python | train |
GetmeUK/MongoFrames | mongoframes/frames.py | https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L95-L103 | def _path_to_keys(cls, path):
"""Return a list of keys for a given path"""
# Paths are cached for performance
keys = _BaseFrame._path_to_keys_cache.get(path)
if keys is None:
keys = _BaseFrame._path_to_keys_cache[path] = path.split('.')
return keys | [
"def",
"_path_to_keys",
"(",
"cls",
",",
"path",
")",
":",
"# Paths are cached for performance",
"keys",
"=",
"_BaseFrame",
".",
"_path_to_keys_cache",
".",
"get",
"(",
"path",
")",
"if",
"keys",
"is",
"None",
":",
"keys",
"=",
"_BaseFrame",
".",
"_path_to_key... | Return a list of keys for a given path | [
"Return",
"a",
"list",
"of",
"keys",
"for",
"a",
"given",
"path"
] | python | train |
awesto/djangoshop-paypal | shop_paypal/payment.py | https://github.com/awesto/djangoshop-paypal/blob/d1db892304869fc9b182404db1d6ef214fafe2a7/shop_paypal/payment.py#L48-L95 | def get_payment_request(self, cart, request):
"""
From the given request, redirect onto the checkout view, hosted by PayPal.
"""
shop_ns = resolve(request.path).namespace
return_url = reverse('{}:{}:return'.format(shop_ns, self.namespace))
cancel_url = reverse('{}:{}:cancel'.format(shop_ns, self.namespace))
cart = CartModel.objects.get_from_request(request)
cart.update(request) # to calculate the total
auth_token_hash = self.get_auth_token()
payload = {
'url': '{API_ENDPOINT}/v1/payments/payment'.format(**settings.SHOP_PAYPAL),
'method': 'POST',
'headers': {
'Content-Type': 'application/json',
'Authorization': '{token_type} {access_token}'.format(**auth_token_hash),
},
'data': {
'intent': 'sale',
'redirect_urls': {
'return_url': request.build_absolute_uri(return_url),
'cancel_url': request.build_absolute_uri(cancel_url),
},
'payer': {
'payment_method': 'paypal',
},
'transactions': [{
'amount': {
'total': cart.total.as_decimal(),
'currency': cart.total.currency,
}
}]
}
}
config = json.dumps(payload, cls=DjangoJSONEncoder)
success_handler = """
function successCallback(r) {
console.log(r);
$window.location.href=r.data.links.filter(function(e){
return e.rel==='approval_url';
})[0].href;
}""".replace(' ', '').replace('\n', '')
error_handler = """
function errorCallback(r) {
console.error(r);
}""".replace(' ', '').replace('\n', '')
js_expression = '$http({0}).then({1},{2})'.format(config, success_handler, error_handler)
return js_expression | [
"def",
"get_payment_request",
"(",
"self",
",",
"cart",
",",
"request",
")",
":",
"shop_ns",
"=",
"resolve",
"(",
"request",
".",
"path",
")",
".",
"namespace",
"return_url",
"=",
"reverse",
"(",
"'{}:{}:return'",
".",
"format",
"(",
"shop_ns",
",",
"self"... | From the given request, redirect onto the checkout view, hosted by PayPal. | [
"From",
"the",
"given",
"request",
"redirect",
"onto",
"the",
"checkout",
"view",
"hosted",
"by",
"PayPal",
"."
] | python | train |
kylef/maintain | maintain/release/aggregate.py | https://github.com/kylef/maintain/blob/4b60e6c52accb4a7faf0d7255a7079087d3ecee0/maintain/release/aggregate.py#L20-L35 | def releasers(cls):
"""
Returns all of the supported releasers.
"""
return [
HookReleaser,
VersionFileReleaser,
PythonReleaser,
CocoaPodsReleaser,
NPMReleaser,
CReleaser,
ChangelogReleaser,
GitHubReleaser,
GitReleaser,
] | [
"def",
"releasers",
"(",
"cls",
")",
":",
"return",
"[",
"HookReleaser",
",",
"VersionFileReleaser",
",",
"PythonReleaser",
",",
"CocoaPodsReleaser",
",",
"NPMReleaser",
",",
"CReleaser",
",",
"ChangelogReleaser",
",",
"GitHubReleaser",
",",
"GitReleaser",
",",
"]... | Returns all of the supported releasers. | [
"Returns",
"all",
"of",
"the",
"supported",
"releasers",
"."
] | python | train |
EpistasisLab/scikit-rebate | skrebate/scoring_utils.py | https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/scoring_utils.py#L352-L358 | def ReliefF_compute_scores(inst, attr, nan_entries, num_attributes, mcmap, NN, headers, class_type, X, y, labels_std, data_type):
""" Unique scoring procedure for ReliefF algorithm. Scoring based on k nearest hits and misses of current target instance. """
scores = np.zeros(num_attributes)
for feature_num in range(num_attributes):
scores[feature_num] += compute_score(attr, mcmap, NN, feature_num, inst,
nan_entries, headers, class_type, X, y, labels_std, data_type)
return scores | [
"def",
"ReliefF_compute_scores",
"(",
"inst",
",",
"attr",
",",
"nan_entries",
",",
"num_attributes",
",",
"mcmap",
",",
"NN",
",",
"headers",
",",
"class_type",
",",
"X",
",",
"y",
",",
"labels_std",
",",
"data_type",
")",
":",
"scores",
"=",
"np",
".",... | Unique scoring procedure for ReliefF algorithm. Scoring based on k nearest hits and misses of current target instance. | [
"Unique",
"scoring",
"procedure",
"for",
"ReliefF",
"algorithm",
".",
"Scoring",
"based",
"on",
"k",
"nearest",
"hits",
"and",
"misses",
"of",
"current",
"target",
"instance",
"."
] | python | train |
ViiSiX/FlaskRedislite | flask_redislite.py | https://github.com/ViiSiX/FlaskRedislite/blob/01bc9fbbeb415aac621c7a9cc091a666e728e651/flask_redislite.py#L150-L158 | def collection(self):
"""Return the redis-collection instance."""
if not self.include_collections:
return None
ctx = stack.top
if ctx is not None:
if not hasattr(ctx, 'redislite_collection'):
ctx.redislite_collection = Collection(redis=self.connection)
return ctx.redislite_collection | [
"def",
"collection",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"include_collections",
":",
"return",
"None",
"ctx",
"=",
"stack",
".",
"top",
"if",
"ctx",
"is",
"not",
"None",
":",
"if",
"not",
"hasattr",
"(",
"ctx",
",",
"'redislite_collection'",... | Return the redis-collection instance. | [
"Return",
"the",
"redis",
"-",
"collection",
"instance",
"."
] | python | train |
rameshg87/pyremotevbox | pyremotevbox/ZSI/writer.py | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/writer.py#L154-L161 | def Known(self, obj):
'''Seen this object (known by its id()? Return 1 if so,
otherwise add it to our memory and return 0.
'''
obj = _get_idstr(obj)
if obj in self.memo: return 1
self.memo.append(obj)
return 0 | [
"def",
"Known",
"(",
"self",
",",
"obj",
")",
":",
"obj",
"=",
"_get_idstr",
"(",
"obj",
")",
"if",
"obj",
"in",
"self",
".",
"memo",
":",
"return",
"1",
"self",
".",
"memo",
".",
"append",
"(",
"obj",
")",
"return",
"0"
] | Seen this object (known by its id()? Return 1 if so,
otherwise add it to our memory and return 0. | [
"Seen",
"this",
"object",
"(",
"known",
"by",
"its",
"id",
"()",
"?",
"Return",
"1",
"if",
"so",
"otherwise",
"add",
"it",
"to",
"our",
"memory",
"and",
"return",
"0",
"."
] | python | train |
HttpRunner/har2case | har2case/cli.py | https://github.com/HttpRunner/har2case/blob/369e576b24b3521832c35344b104828e30742170/har2case/cli.py#L20-L61 | def main():
""" HAR converter: parse command line options and run commands.
"""
parser = argparse.ArgumentParser(description=__description__)
parser.add_argument(
'-V', '--version', dest='version', action='store_true',
help="show version")
parser.add_argument(
'--log-level', default='INFO',
help="Specify logging level, default is INFO.")
parser.add_argument('har_source_file', nargs='?',
help="Specify HAR source file")
parser.add_argument(
'-2y', '--to-yml', '--to-yaml',
dest='to_yaml', action='store_true',
help="Convert to YAML format, if not specified, convert to JSON format by default.")
parser.add_argument(
'--filter', help="Specify filter keyword, only url include filter string will be converted.")
parser.add_argument(
'--exclude',
help="Specify exclude keyword, url that includes exclude string will be ignored, multiple keywords can be joined with '|'")
args = parser.parse_args()
if args.version:
print("{}".format(__version__))
exit(0)
log_level = getattr(logging, args.log_level.upper())
logging.basicConfig(level=log_level)
har_source_file = args.har_source_file
if not har_source_file or not har_source_file.endswith(".har"):
logging.error("HAR file not specified.")
sys.exit(1)
output_file_type = "YML" if args.to_yaml else "JSON"
HarParser(
har_source_file, args.filter, args.exclude
).gen_testcase(output_file_type)
return 0 | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"__description__",
")",
"parser",
".",
"add_argument",
"(",
"'-V'",
",",
"'--version'",
",",
"dest",
"=",
"'version'",
",",
"action",
"=",
"'store_true'"... | HAR converter: parse command line options and run commands. | [
"HAR",
"converter",
":",
"parse",
"command",
"line",
"options",
"and",
"run",
"commands",
"."
] | python | train |
AltSchool/dynamic-rest | dynamic_rest/routers.py | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/routers.py#L249-L276 | def get_canonical_serializer(
resource_key,
model=None,
instance=None,
resource_name=None
):
"""
Return canonical serializer for a given resource name.
Arguments:
resource_key - Resource key, usually DB table for model-based
resources, otherwise the plural name.
model - (Optional) Model class to look up by.
instance - (Optional) Model object instance.
Returns: serializer class
"""
if model:
resource_key = get_model_table(model)
elif instance:
resource_key = instance._meta.db_table
elif resource_name:
resource_key = resource_name_map[resource_name]
if resource_key not in resource_map:
return None
return resource_map[resource_key]['viewset'].serializer_class | [
"def",
"get_canonical_serializer",
"(",
"resource_key",
",",
"model",
"=",
"None",
",",
"instance",
"=",
"None",
",",
"resource_name",
"=",
"None",
")",
":",
"if",
"model",
":",
"resource_key",
"=",
"get_model_table",
"(",
"model",
")",
"elif",
"instance",
"... | Return canonical serializer for a given resource name.
Arguments:
resource_key - Resource key, usually DB table for model-based
resources, otherwise the plural name.
model - (Optional) Model class to look up by.
instance - (Optional) Model object instance.
Returns: serializer class | [
"Return",
"canonical",
"serializer",
"for",
"a",
"given",
"resource",
"name",
"."
] | python | train |
edeposit/edeposit.amqp.ltp | src/edeposit/amqp/ltp/ltp.py | https://github.com/edeposit/edeposit.amqp.ltp/blob/df9ac7ec6cbdbeaaeed438ca66df75ea967b6d8e/src/edeposit/amqp/ltp/ltp.py#L22-L37 | def _get_package_name(prefix=settings.TEMP_DIR, book_id=None):
"""
Return package path. Use uuid to generate package's directory name.
Args:
book_id (str, default None): UUID of the book.
prefix (str, default settings.TEMP_DIR): Where the package will be
stored. Default :attr:`settings.TEMP_DIR`.
Returns:
str: Path to the root directory.
"""
if book_id is None:
book_id = str(uuid.uuid4())
return os.path.join(prefix, book_id) | [
"def",
"_get_package_name",
"(",
"prefix",
"=",
"settings",
".",
"TEMP_DIR",
",",
"book_id",
"=",
"None",
")",
":",
"if",
"book_id",
"is",
"None",
":",
"book_id",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"return",
"os",
".",
"path",
".",... | Return package path. Use uuid to generate package's directory name.
Args:
book_id (str, default None): UUID of the book.
prefix (str, default settings.TEMP_DIR): Where the package will be
stored. Default :attr:`settings.TEMP_DIR`.
Returns:
str: Path to the root directory. | [
"Return",
"package",
"path",
".",
"Use",
"uuid",
"to",
"generate",
"package",
"s",
"directory",
"name",
"."
] | python | train |
edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/scrappers/ben_cz.py | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/ben_cz.py#L111-L140 | def _parse_authors(details):
"""
Parse authors of the book.
Args:
details (obj): HTMLElement containing slice of the page with details.
Returns:
list: List of :class:`structures.Author` objects. Blank if no author \
found.
"""
authors = details.find(
"tr",
{"id": "ctl00_ContentPlaceHolder1_tblRowAutor"}
)
if not authors:
return [] # book with unspecified authors
# parse authors from HTML and convert them to Author objects
author_list = []
for author in authors[0].find("a"):
author_obj = Author(author.getContent())
if "href" in author.params:
author_obj.URL = author.params["href"]
author_list.append(author_obj)
return author_list | [
"def",
"_parse_authors",
"(",
"details",
")",
":",
"authors",
"=",
"details",
".",
"find",
"(",
"\"tr\"",
",",
"{",
"\"id\"",
":",
"\"ctl00_ContentPlaceHolder1_tblRowAutor\"",
"}",
")",
"if",
"not",
"authors",
":",
"return",
"[",
"]",
"# book with unspecified au... | Parse authors of the book.
Args:
details (obj): HTMLElement containing slice of the page with details.
Returns:
list: List of :class:`structures.Author` objects. Blank if no author \
found. | [
"Parse",
"authors",
"of",
"the",
"book",
"."
] | python | train |
adamrothman/ftl | ftl/utils.py | https://github.com/adamrothman/ftl/blob/a88f3df1ecbdfba45035b65f833b8ffffc49b399/ftl/utils.py#L6-L39 | def default_ssl_context() -> ssl.SSLContext:
"""Creates an SSL context suitable for use with HTTP/2. See
https://tools.ietf.org/html/rfc7540#section-9.2 for what this entails.
Specifically, we are interested in these points:
§ 9.2: Implementations of HTTP/2 MUST use TLS version 1.2 or higher.
§ 9.2.1: A deployment of HTTP/2 over TLS 1.2 MUST disable compression.
The h2 project has its own ideas about how this context should be
constructed but the resulting context doesn't work for us in the standard
Python Docker images (though it does work under macOS). See
https://python-hyper.org/projects/h2/en/stable/negotiating-http2.html#client-setup-example
for more.
"""
ctx = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH)
# OP_NO_SSLv2, OP_NO_SSLv3, and OP_NO_COMPRESSION are already set by default
# so we just need to disable the old versions of TLS.
ctx.options |= (ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1)
# ALPN and NPN allow upgrades from HTTP/1.1, but these extensions are only
# supported by recent versions of OpenSSL. Try to set them up, but don't cry
# if they fail.
try:
ctx.set_alpn_protocols(["h2", "http/1.1"])
except NotImplementedError:
pass
try:
ctx.set_npn_protocols(["h2", "http/1.1"])
except NotImplementedError:
pass
return ctx | [
"def",
"default_ssl_context",
"(",
")",
"->",
"ssl",
".",
"SSLContext",
":",
"ctx",
"=",
"ssl",
".",
"create_default_context",
"(",
"purpose",
"=",
"ssl",
".",
"Purpose",
".",
"SERVER_AUTH",
")",
"# OP_NO_SSLv2, OP_NO_SSLv3, and OP_NO_COMPRESSION are already set by defa... | Creates an SSL context suitable for use with HTTP/2. See
https://tools.ietf.org/html/rfc7540#section-9.2 for what this entails.
Specifically, we are interested in these points:
§ 9.2: Implementations of HTTP/2 MUST use TLS version 1.2 or higher.
§ 9.2.1: A deployment of HTTP/2 over TLS 1.2 MUST disable compression.
The h2 project has its own ideas about how this context should be
constructed but the resulting context doesn't work for us in the standard
Python Docker images (though it does work under macOS). See
https://python-hyper.org/projects/h2/en/stable/negotiating-http2.html#client-setup-example
for more. | [
"Creates",
"an",
"SSL",
"context",
"suitable",
"for",
"use",
"with",
"HTTP",
"/",
"2",
".",
"See",
"https",
":",
"//",
"tools",
".",
"ietf",
".",
"org",
"/",
"html",
"/",
"rfc7540#section",
"-",
"9",
".",
"2",
"for",
"what",
"this",
"entails",
".",
... | python | train |
sanger-pathogens/ariba | ariba/assembly_compare.py | https://github.com/sanger-pathogens/ariba/blob/16a0b1916ce0e886bd22550ba2d648542977001b/ariba/assembly_compare.py#L181-L214 | def _get_assembled_reference_sequences(nucmer_hits, ref_sequence, assembly):
'''nucmer_hits = hits made by self._parse_nucmer_coords_file.
ref_gene = reference sequence (pyfastaq.sequences.Fasta object)
assembly = dictionary of contig name -> contig.
Makes a set of Fasta objects of each piece of assembly that
corresponds to the reference sequeunce.'''
sequences = {}
for contig in sorted(nucmer_hits):
for hit in nucmer_hits[contig]:
qry_coords = hit.qry_coords()
fa = assembly[hit.qry_name].subseq(qry_coords.start, qry_coords.end + 1)
if hit.on_same_strand():
strand = '+'
else:
fa.revcomp()
strand = '-'
ref_coords = hit.ref_coords()
fa.id = '.'.join([
ref_sequence.id,
str(ref_coords.start + 1),
str(ref_coords.end + 1),
contig,
str(qry_coords.start + 1),
str(qry_coords.end + 1),
strand
])
if hit.hit_length_ref == hit.ref_length:
fa.id += '.complete'
sequences[fa.id] = fa
return sequences | [
"def",
"_get_assembled_reference_sequences",
"(",
"nucmer_hits",
",",
"ref_sequence",
",",
"assembly",
")",
":",
"sequences",
"=",
"{",
"}",
"for",
"contig",
"in",
"sorted",
"(",
"nucmer_hits",
")",
":",
"for",
"hit",
"in",
"nucmer_hits",
"[",
"contig",
"]",
... | nucmer_hits = hits made by self._parse_nucmer_coords_file.
ref_gene = reference sequence (pyfastaq.sequences.Fasta object)
assembly = dictionary of contig name -> contig.
Makes a set of Fasta objects of each piece of assembly that
corresponds to the reference sequeunce. | [
"nucmer_hits",
"=",
"hits",
"made",
"by",
"self",
".",
"_parse_nucmer_coords_file",
".",
"ref_gene",
"=",
"reference",
"sequence",
"(",
"pyfastaq",
".",
"sequences",
".",
"Fasta",
"object",
")",
"assembly",
"=",
"dictionary",
"of",
"contig",
"name",
"-",
">",
... | python | train |
ihmeuw/vivarium | src/vivarium/framework/values.py | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/values.py#L54-L79 | def joint_value_post_processor(a, _):
"""The final step in calculating joint values like disability weights.
If the combiner is list_combiner then the effective formula is:
.. math::
value(args) = 1 - \prod_{i=1}^{mutator count} 1-mutator_{i}(args)
Parameters
----------
a : List[pd.Series]
a is a list of series, indexed on the population. Each series
corresponds to a different value in the pipeline and each row
in a series contains a value that applies to a specific simulant.
"""
# if there is only one value, return the value
if len(a) == 1:
return a[0]
# if there are multiple values, calculate the joint value
product = 1
for v in a:
new_value = (1-v)
product = product * new_value
joint_value = 1 - product
return joint_value | [
"def",
"joint_value_post_processor",
"(",
"a",
",",
"_",
")",
":",
"# if there is only one value, return the value",
"if",
"len",
"(",
"a",
")",
"==",
"1",
":",
"return",
"a",
"[",
"0",
"]",
"# if there are multiple values, calculate the joint value",
"product",
"=",
... | The final step in calculating joint values like disability weights.
If the combiner is list_combiner then the effective formula is:
.. math::
value(args) = 1 - \prod_{i=1}^{mutator count} 1-mutator_{i}(args)
Parameters
----------
a : List[pd.Series]
a is a list of series, indexed on the population. Each series
corresponds to a different value in the pipeline and each row
in a series contains a value that applies to a specific simulant. | [
"The",
"final",
"step",
"in",
"calculating",
"joint",
"values",
"like",
"disability",
"weights",
".",
"If",
"the",
"combiner",
"is",
"list_combiner",
"then",
"the",
"effective",
"formula",
"is",
":"
] | python | train |
PyCQA/pylint | pylint/lint.py | https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/lint.py#L1284-L1290 | def report_total_messages_stats(sect, stats, previous_stats):
"""make total errors / warnings report"""
lines = ["type", "number", "previous", "difference"]
lines += checkers.table_lines_from_stats(
stats, previous_stats, ("convention", "refactor", "warning", "error")
)
sect.append(report_nodes.Table(children=lines, cols=4, rheaders=1)) | [
"def",
"report_total_messages_stats",
"(",
"sect",
",",
"stats",
",",
"previous_stats",
")",
":",
"lines",
"=",
"[",
"\"type\"",
",",
"\"number\"",
",",
"\"previous\"",
",",
"\"difference\"",
"]",
"lines",
"+=",
"checkers",
".",
"table_lines_from_stats",
"(",
"s... | make total errors / warnings report | [
"make",
"total",
"errors",
"/",
"warnings",
"report"
] | python | test |
tensorflow/tensor2tensor | tensor2tensor/models/slicenet.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/slicenet.py#L33-L81 | def attention(targets_shifted, inputs_encoded, norm_fn, hparams, bias=None):
"""Complete attention layer with preprocessing."""
separabilities = [hparams.separability, hparams.separability]
if hparams.separability < 0:
separabilities = [hparams.separability - 1, hparams.separability]
targets_timed = common_layers.subseparable_conv_block(
common_layers.add_timing_signal(targets_shifted),
hparams.hidden_size, [((1, 1), (5, 1)), ((4, 1), (5, 1))],
normalizer_fn=norm_fn,
padding="LEFT",
separabilities=separabilities,
name="targets_time")
if hparams.attention_type == "transformer":
targets_timed = tf.squeeze(targets_timed, 2)
target_shape = tf.shape(targets_timed)
targets_segment = tf.zeros([target_shape[0], target_shape[1]])
target_attention_bias = common_attention.attention_bias(
targets_segment, targets_segment, lower_triangular=True)
inputs_attention_bias = tf.zeros([
tf.shape(inputs_encoded)[0], hparams.num_heads,
tf.shape(targets_segment)[1],
tf.shape(inputs_encoded)[1]
])
qv = common_attention.multihead_attention(
targets_timed,
None,
target_attention_bias,
hparams.hidden_size,
hparams.hidden_size,
hparams.hidden_size,
hparams.num_heads,
hparams.attention_dropout,
name="self_attention")
qv = common_attention.multihead_attention(
qv,
inputs_encoded,
inputs_attention_bias,
hparams.hidden_size,
hparams.hidden_size,
hparams.hidden_size,
hparams.num_heads,
hparams.attention_dropout,
name="encdec_attention")
return tf.expand_dims(qv, 2)
elif hparams.attention_type == "simple":
targets_with_attention = common_layers.simple_attention(
targets_timed, inputs_encoded, bias=bias)
return norm_fn(targets_shifted + targets_with_attention, name="attn_norm") | [
"def",
"attention",
"(",
"targets_shifted",
",",
"inputs_encoded",
",",
"norm_fn",
",",
"hparams",
",",
"bias",
"=",
"None",
")",
":",
"separabilities",
"=",
"[",
"hparams",
".",
"separability",
",",
"hparams",
".",
"separability",
"]",
"if",
"hparams",
".",... | Complete attention layer with preprocessing. | [
"Complete",
"attention",
"layer",
"with",
"preprocessing",
"."
] | python | train |
BD2KGenomics/protect | src/protect/common.py | https://github.com/BD2KGenomics/protect/blob/06310682c50dcf8917b912c8e551299ff7ee41ce/src/protect/common.py#L451-L464 | def delete_fastqs(job, patient_dict):
"""
Delete the fastqs from the job Store once their purpose has been achieved (i.e. after all
mapping steps)
:param dict patient_dict: Dict of list of input fastqs
"""
for key in patient_dict.keys():
if 'fastq' not in key:
continue
job.fileStore.logToMaster('Deleting "%s:%s" ' % (patient_dict['patient_id'], key) +
'from the filestore.')
job.fileStore.deleteGlobalFile(patient_dict[key])
return None | [
"def",
"delete_fastqs",
"(",
"job",
",",
"patient_dict",
")",
":",
"for",
"key",
"in",
"patient_dict",
".",
"keys",
"(",
")",
":",
"if",
"'fastq'",
"not",
"in",
"key",
":",
"continue",
"job",
".",
"fileStore",
".",
"logToMaster",
"(",
"'Deleting \"%s:%s\" ... | Delete the fastqs from the job Store once their purpose has been achieved (i.e. after all
mapping steps)
:param dict patient_dict: Dict of list of input fastqs | [
"Delete",
"the",
"fastqs",
"from",
"the",
"job",
"Store",
"once",
"their",
"purpose",
"has",
"been",
"achieved",
"(",
"i",
".",
"e",
".",
"after",
"all",
"mapping",
"steps",
")"
] | python | train |
fedora-infra/fmn.rules | fmn/rules/utils.py | https://github.com/fedora-infra/fmn.rules/blob/f9ec790619fcc8b41803077c4dec094e5127fc24/fmn/rules/utils.py#L40-L66 | def get_fas(config):
""" Return a fedora.client.fas2.AccountSystem object if the provided
configuration contains a FAS username and password.
"""
global _FAS
if _FAS is not None:
return _FAS
# In some development environments, having fas_credentials around is a
# pain.. so, let things proceed here, but emit a warning.
try:
creds = config['fas_credentials']
except KeyError:
log.warn("No fas_credentials available. Unable to query FAS.")
return None
default_url = 'https://admin.fedoraproject.org/accounts/'
_FAS = AccountSystem(
creds.get('base_url', default_url),
username=creds['username'],
password=creds['password'],
cache_session=False,
insecure=creds.get('insecure', False)
)
return _FAS | [
"def",
"get_fas",
"(",
"config",
")",
":",
"global",
"_FAS",
"if",
"_FAS",
"is",
"not",
"None",
":",
"return",
"_FAS",
"# In some development environments, having fas_credentials around is a",
"# pain.. so, let things proceed here, but emit a warning.",
"try",
":",
"creds",
... | Return a fedora.client.fas2.AccountSystem object if the provided
configuration contains a FAS username and password. | [
"Return",
"a",
"fedora",
".",
"client",
".",
"fas2",
".",
"AccountSystem",
"object",
"if",
"the",
"provided",
"configuration",
"contains",
"a",
"FAS",
"username",
"and",
"password",
"."
] | python | train |
bitesofcode/projexui | projexui/widgets/xviewwidget/xviewpanel.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewpanel.py#L407-L418 | def clear(self):
"""
Clears out all the items from this tab bar.
"""
self.blockSignals(True)
items = list(self.items())
for item in items:
item.close()
self.blockSignals(False)
self._currentIndex = -1
self.currentIndexChanged.emit(self._currentIndex) | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"blockSignals",
"(",
"True",
")",
"items",
"=",
"list",
"(",
"self",
".",
"items",
"(",
")",
")",
"for",
"item",
"in",
"items",
":",
"item",
".",
"close",
"(",
")",
"self",
".",
"blockSignals",
... | Clears out all the items from this tab bar. | [
"Clears",
"out",
"all",
"the",
"items",
"from",
"this",
"tab",
"bar",
"."
] | python | train |
Yelp/threat_intel | threat_intel/util/http.py | https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/util/http.py#L79-L91 | def make_calls(self, num_calls=1):
"""Adds appropriate sleep to avoid making too many calls.
Args:
num_calls: int the number of calls which will be made
"""
self._cull()
while self._outstanding_calls + num_calls > self._max_calls_per_second:
time.sleep(0) # yield
self._cull()
self._call_times.append(self.CallRecord(time=time.time(), num_calls=num_calls))
self._outstanding_calls += num_calls | [
"def",
"make_calls",
"(",
"self",
",",
"num_calls",
"=",
"1",
")",
":",
"self",
".",
"_cull",
"(",
")",
"while",
"self",
".",
"_outstanding_calls",
"+",
"num_calls",
">",
"self",
".",
"_max_calls_per_second",
":",
"time",
".",
"sleep",
"(",
"0",
")",
"... | Adds appropriate sleep to avoid making too many calls.
Args:
num_calls: int the number of calls which will be made | [
"Adds",
"appropriate",
"sleep",
"to",
"avoid",
"making",
"too",
"many",
"calls",
"."
] | python | train |
Azure/azure-uamqp-python | uamqp/address.py | https://github.com/Azure/azure-uamqp-python/blob/b67e4fcaf2e8a337636947523570239c10a58ae2/uamqp/address.py#L189-L212 | def set_filter(self, value, name=constants.STRING_FILTER, descriptor=constants.STRING_FILTER):
"""Set a filter on the endpoint. Only one filter
can be applied to an endpoint.
:param value: The filter to apply to the endpoint. Set to None for a NULL filter.
:type value: bytes or str or None
:param name: The name of the filter. This will be encoded as
an AMQP Symbol. By default this is set to b'apache.org:selector-filter:string'.
:type name: bytes
:param descriptor: The descriptor used if the filter is to be encoded as a described value.
This will be encoded as an AMQP Symbol. By default this is set to b'apache.org:selector-filter:string'.
Set to None if the filter should not be encoded as a described value.
:type descriptor: bytes or None
"""
value = value.encode(self._encoding) if isinstance(value, six.text_type) else value
filter_set = c_uamqp.dict_value()
filter_key = c_uamqp.symbol_value(name)
filter_value = utils.data_factory(value, encoding=self._encoding)
if value is not None and descriptor is not None:
descriptor = c_uamqp.symbol_value(descriptor)
filter_value = c_uamqp.described_value(descriptor, filter_value)
filter_set[filter_key] = filter_value
self._address.filter_set = filter_set | [
"def",
"set_filter",
"(",
"self",
",",
"value",
",",
"name",
"=",
"constants",
".",
"STRING_FILTER",
",",
"descriptor",
"=",
"constants",
".",
"STRING_FILTER",
")",
":",
"value",
"=",
"value",
".",
"encode",
"(",
"self",
".",
"_encoding",
")",
"if",
"isi... | Set a filter on the endpoint. Only one filter
can be applied to an endpoint.
:param value: The filter to apply to the endpoint. Set to None for a NULL filter.
:type value: bytes or str or None
:param name: The name of the filter. This will be encoded as
an AMQP Symbol. By default this is set to b'apache.org:selector-filter:string'.
:type name: bytes
:param descriptor: The descriptor used if the filter is to be encoded as a described value.
This will be encoded as an AMQP Symbol. By default this is set to b'apache.org:selector-filter:string'.
Set to None if the filter should not be encoded as a described value.
:type descriptor: bytes or None | [
"Set",
"a",
"filter",
"on",
"the",
"endpoint",
".",
"Only",
"one",
"filter",
"can",
"be",
"applied",
"to",
"an",
"endpoint",
"."
] | python | train |
sorgerlab/indra | indra/tools/assemble_corpus.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L566-L581 | def _remove_bound_conditions(agent, keep_criterion):
"""Removes bound conditions of agent such that keep_criterion is False.
Parameters
----------
agent: Agent
The agent whose bound conditions we evaluate
keep_criterion: function
Evaluates removal_criterion(a) for each agent a in a bound condition
and if it evaluates to False, removes a from agent's bound_conditions
"""
new_bc = []
for ind in range(len(agent.bound_conditions)):
if keep_criterion(agent.bound_conditions[ind].agent):
new_bc.append(agent.bound_conditions[ind])
agent.bound_conditions = new_bc | [
"def",
"_remove_bound_conditions",
"(",
"agent",
",",
"keep_criterion",
")",
":",
"new_bc",
"=",
"[",
"]",
"for",
"ind",
"in",
"range",
"(",
"len",
"(",
"agent",
".",
"bound_conditions",
")",
")",
":",
"if",
"keep_criterion",
"(",
"agent",
".",
"bound_cond... | Removes bound conditions of agent such that keep_criterion is False.
Parameters
----------
agent: Agent
The agent whose bound conditions we evaluate
keep_criterion: function
Evaluates removal_criterion(a) for each agent a in a bound condition
and if it evaluates to False, removes a from agent's bound_conditions | [
"Removes",
"bound",
"conditions",
"of",
"agent",
"such",
"that",
"keep_criterion",
"is",
"False",
"."
] | python | train |
equinor/segyviewer | src/segyviewlib/sliceview.py | https://github.com/equinor/segyviewer/blob/994d402a8326f30608d98103f8831dee9e3c5850/src/segyviewlib/sliceview.py#L39-L70 | def create_slice(self, context):
""" :type context: dict """
model = self._model
axes = self._image.axes
""" :type: matplotlib.axes.Axes """
axes.set_title(model.title, fontsize=12)
axes.tick_params(axis='both')
axes.set_ylabel(model.y_axis_name, fontsize=9)
axes.set_xlabel(model.x_axis_name, fontsize=9)
axes.get_xaxis().set_major_formatter(FuncFormatter(model.x_axis_formatter))
axes.get_xaxis().set_major_locator(AutoLocator())
axes.get_yaxis().set_major_formatter(FuncFormatter(model.y_axis_formatter))
axes.get_yaxis().set_major_locator(AutoLocator())
for label in (axes.get_xticklabels() + axes.get_yticklabels()):
label.set_fontsize(9)
self._reset_zoom()
axes.add_patch(self._vertical_indicator)
axes.add_patch(self._horizontal_indicator)
self._update_indicators(context)
self._image.set_cmap(cmap=context['colormap'])
self._view_limits = context["view_limits"][self._model.index_direction['name']]
if model.data is not None:
self._image.set_data(model.data) | [
"def",
"create_slice",
"(",
"self",
",",
"context",
")",
":",
"model",
"=",
"self",
".",
"_model",
"axes",
"=",
"self",
".",
"_image",
".",
"axes",
"\"\"\" :type: matplotlib.axes.Axes \"\"\"",
"axes",
".",
"set_title",
"(",
"model",
".",
"title",
",",
"fonts... | :type context: dict | [
":",
"type",
"context",
":",
"dict"
] | python | train |
uw-it-aca/django-saferecipient-email-backend | saferecipient/__init__.py | https://github.com/uw-it-aca/django-saferecipient-email-backend/blob/8af20dece5a668d6bcad5dea75cc60871a4bd9fa/saferecipient/__init__.py#L44-L54 | def _only_safe_emails(self, emails):
""""Given a list of emails, checks whether they are all in the white
list."""
email_modified = False
if any(not self._is_whitelisted(email) for email in emails):
email_modified = True
emails = [email for email in emails if self._is_whitelisted(email)]
if settings.SAFE_EMAIL_RECIPIENT not in emails:
emails.append(settings.SAFE_EMAIL_RECIPIENT)
return emails, email_modified | [
"def",
"_only_safe_emails",
"(",
"self",
",",
"emails",
")",
":",
"email_modified",
"=",
"False",
"if",
"any",
"(",
"not",
"self",
".",
"_is_whitelisted",
"(",
"email",
")",
"for",
"email",
"in",
"emails",
")",
":",
"email_modified",
"=",
"True",
"emails",... | Given a list of emails, checks whether they are all in the white
list. | [
"Given",
"a",
"list",
"of",
"emails",
"checks",
"whether",
"they",
"are",
"all",
"in",
"the",
"white",
"list",
"."
] | python | train |
Esri/ArcREST | src/arcrest/common/symbology.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/common/symbology.py#L136-L140 | def outlineWidth(self, value):
"""gets/sets the outlineWidth"""
if isinstance(value, (int, float, long)) and \
not self._outline is None:
self._outline['width'] = value | [
"def",
"outlineWidth",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"int",
",",
"float",
",",
"long",
")",
")",
"and",
"not",
"self",
".",
"_outline",
"is",
"None",
":",
"self",
".",
"_outline",
"[",
"'width'",
"... | gets/sets the outlineWidth | [
"gets",
"/",
"sets",
"the",
"outlineWidth"
] | python | train |
vtemian/buffpy | buffpy/response.py | https://github.com/vtemian/buffpy/blob/6c9236fd3b6a8f9e2d70dbf1bc01529242b73075/buffpy/response.py#L20-L29 | def _check_for_inception(self, root_dict):
'''
Used to check if there is a dict in a dict
'''
for key in root_dict:
if isinstance(root_dict[key], dict):
root_dict[key] = ResponseObject(root_dict[key])
return root_dict | [
"def",
"_check_for_inception",
"(",
"self",
",",
"root_dict",
")",
":",
"for",
"key",
"in",
"root_dict",
":",
"if",
"isinstance",
"(",
"root_dict",
"[",
"key",
"]",
",",
"dict",
")",
":",
"root_dict",
"[",
"key",
"]",
"=",
"ResponseObject",
"(",
"root_di... | Used to check if there is a dict in a dict | [
"Used",
"to",
"check",
"if",
"there",
"is",
"a",
"dict",
"in",
"a",
"dict"
] | python | valid |
iotile/coretools | iotilesensorgraph/iotile/sg/sim/simulator.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sim/simulator.py#L95-L109 | def step(self, input_stream, value):
"""Step the sensor graph through one since input.
The internal tick count is not advanced so this function may
be called as many times as desired to input specific conditions
without simulation time passing.
Args:
input_stream (DataStream): The input stream to push the
value into
value (int): The reading value to push as an integer
"""
reading = IOTileReading(input_stream.encode(), self.tick_count, value)
self.sensor_graph.process_input(input_stream, reading, self.rpc_executor) | [
"def",
"step",
"(",
"self",
",",
"input_stream",
",",
"value",
")",
":",
"reading",
"=",
"IOTileReading",
"(",
"input_stream",
".",
"encode",
"(",
")",
",",
"self",
".",
"tick_count",
",",
"value",
")",
"self",
".",
"sensor_graph",
".",
"process_input",
... | Step the sensor graph through one since input.
The internal tick count is not advanced so this function may
be called as many times as desired to input specific conditions
without simulation time passing.
Args:
input_stream (DataStream): The input stream to push the
value into
value (int): The reading value to push as an integer | [
"Step",
"the",
"sensor",
"graph",
"through",
"one",
"since",
"input",
"."
] | python | train |
DataDog/integrations-core | datadog_checks_base/datadog_checks/base/log.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/datadog_checks_base/datadog_checks/base/log.py#L62-L77 | def init_logging():
"""
Initialize logging (set up forwarding to Go backend and sane defaults)
"""
# Forward to Go backend
logging.addLevelName(TRACE_LEVEL, 'TRACE')
logging.setLoggerClass(AgentLogger)
rootLogger = logging.getLogger()
rootLogger.addHandler(AgentLogHandler())
rootLogger.setLevel(_get_py_loglevel(datadog_agent.get_config('log_level')))
# `requests` (used in a lot of checks) imports `urllib3`, which logs a bunch of stuff at the info level
# Therefore, pre emptively increase the default level of that logger to `WARN`
urllib_logger = logging.getLogger("requests.packages.urllib3")
urllib_logger.setLevel(logging.WARN)
urllib_logger.propagate = True | [
"def",
"init_logging",
"(",
")",
":",
"# Forward to Go backend",
"logging",
".",
"addLevelName",
"(",
"TRACE_LEVEL",
",",
"'TRACE'",
")",
"logging",
".",
"setLoggerClass",
"(",
"AgentLogger",
")",
"rootLogger",
"=",
"logging",
".",
"getLogger",
"(",
")",
"rootLo... | Initialize logging (set up forwarding to Go backend and sane defaults) | [
"Initialize",
"logging",
"(",
"set",
"up",
"forwarding",
"to",
"Go",
"backend",
"and",
"sane",
"defaults",
")"
] | python | train |
saltstack/salt | salt/modules/apache.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/apache.py#L403-L449 | def _parse_config(conf, slot=None):
'''
Recursively goes through config structure and builds final Apache configuration
:param conf: defined config structure
:param slot: name of section container if needed
'''
ret = cStringIO()
if isinstance(conf, six.string_types):
if slot:
print('{0} {1}'.format(slot, conf), file=ret, end='')
else:
print('{0}'.format(conf), file=ret, end='')
elif isinstance(conf, list):
is_section = False
for item in conf:
if 'this' in item:
is_section = True
slot_this = six.text_type(item['this'])
if is_section:
print('<{0} {1}>'.format(slot, slot_this), file=ret)
for item in conf:
for key, val in item.items():
if key != 'this':
print(_parse_config(val, six.text_type(key)), file=ret)
print('</{0}>'.format(slot), file=ret)
else:
for value in conf:
print(_parse_config(value, six.text_type(slot)), file=ret)
elif isinstance(conf, dict):
try:
print('<{0} {1}>'.format(slot, conf['this']), file=ret)
except KeyError:
raise SaltException('Apache section container "<{0}>" expects attribute. '
'Specify it using key "this".'.format(slot))
for key, value in six.iteritems(conf):
if key != 'this':
if isinstance(value, six.string_types):
print('{0} {1}'.format(key, value), file=ret)
elif isinstance(value, list):
print(_parse_config(value, key), file=ret)
elif isinstance(value, dict):
print(_parse_config(value, key), file=ret)
print('</{0}>'.format(slot), file=ret)
ret.seek(0)
return ret.read() | [
"def",
"_parse_config",
"(",
"conf",
",",
"slot",
"=",
"None",
")",
":",
"ret",
"=",
"cStringIO",
"(",
")",
"if",
"isinstance",
"(",
"conf",
",",
"six",
".",
"string_types",
")",
":",
"if",
"slot",
":",
"print",
"(",
"'{0} {1}'",
".",
"format",
"(",
... | Recursively goes through config structure and builds final Apache configuration
:param conf: defined config structure
:param slot: name of section container if needed | [
"Recursively",
"goes",
"through",
"config",
"structure",
"and",
"builds",
"final",
"Apache",
"configuration"
] | python | train |
icometrix/dicom2nifti | dicom2nifti/convert_ge.py | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_ge.py#L139-L165 | def _get_full_block(grouped_dicoms):
"""
Generate a full datablock containing all timepoints
"""
# For each slice / mosaic create a data volume block
data_blocks = []
for index in range(0, len(grouped_dicoms)):
logger.info('Creating block %s of %s' % (index + 1, len(grouped_dicoms)))
data_blocks.append(_timepoint_to_block(grouped_dicoms[index]))
# Add the data_blocks together to one 4d block
size_x = numpy.shape(data_blocks[0])[0]
size_y = numpy.shape(data_blocks[0])[1]
size_z = numpy.shape(data_blocks[0])[2]
size_t = len(data_blocks)
full_block = numpy.zeros((size_x, size_y, size_z, size_t), dtype=data_blocks[0].dtype)
for index in range(0, size_t):
if full_block[:, :, :, index].shape != data_blocks[index].shape:
logger.warning('Missing slices (slice count mismatch between timepoint %s and %s)' % (index - 1, index))
logger.warning('---------------------------------------------------------')
logger.warning(full_block[:, :, :, index].shape)
logger.warning(data_blocks[index].shape)
logger.warning('---------------------------------------------------------')
raise ConversionError("MISSING_DICOM_FILES")
full_block[:, :, :, index] = data_blocks[index]
return full_block | [
"def",
"_get_full_block",
"(",
"grouped_dicoms",
")",
":",
"# For each slice / mosaic create a data volume block",
"data_blocks",
"=",
"[",
"]",
"for",
"index",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"grouped_dicoms",
")",
")",
":",
"logger",
".",
"info",
"("... | Generate a full datablock containing all timepoints | [
"Generate",
"a",
"full",
"datablock",
"containing",
"all",
"timepoints"
] | python | train |
saltstack/salt | salt/utils/gitfs.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/gitfs.py#L2988-L3006 | def symlink_list(self, load):
'''
Return a dict of all symlinks based on a given path in the repo
'''
if 'env' in load:
# "env" is not supported; Use "saltenv".
load.pop('env')
if not salt.utils.stringutils.is_hex(load['saltenv']) \
and load['saltenv'] not in self.envs():
return {}
if 'prefix' in load:
prefix = load['prefix'].strip('/')
else:
prefix = ''
symlinks = self._file_lists(load, 'symlinks')
return dict([(key, val)
for key, val in six.iteritems(symlinks)
if key.startswith(prefix)]) | [
"def",
"symlink_list",
"(",
"self",
",",
"load",
")",
":",
"if",
"'env'",
"in",
"load",
":",
"# \"env\" is not supported; Use \"saltenv\".",
"load",
".",
"pop",
"(",
"'env'",
")",
"if",
"not",
"salt",
".",
"utils",
".",
"stringutils",
".",
"is_hex",
"(",
"... | Return a dict of all symlinks based on a given path in the repo | [
"Return",
"a",
"dict",
"of",
"all",
"symlinks",
"based",
"on",
"a",
"given",
"path",
"in",
"the",
"repo"
] | python | train |
jmbhughes/suvi-trainer | suvitrainer/fileio.py | https://github.com/jmbhughes/suvi-trainer/blob/3d89894a4a037286221974c7eb5634d229b4f5d4/suvitrainer/fileio.py#L414-L560 | def align_solar_fov(header, data, cdelt_min, naxis_min,
translate_origin=True, rotate=True, scale=True):
"""
taken from suvi code by vhsu
Apply field of view image corrections
:param header: FITS header
:param data: Image data
:param cdelt_min: Minimum plate scale for images (static run config param)
:param naxis_min: Minimum axis dimension for images (static run config param)
:param translate_origin: Translate image to specified origin (dtype=bool)
:param rotate: Rotate image about origin (dtype=bool)
:param scale: Scale image (dtype=bool)
:rtype: numpy.ndarray
:return: data_corr (corrected/aligned image)
:rtype: astropy.io.fits.header Header instance
:return: upd_meta (updated metadata after image corrections)
NOTES: (1) The associative property of matrix multiplication makes it possible to multiply
transformation matrices together to produce a single transformation. However, the order
of each transformation matters. In this algorithm, the order is:
1. Translate image center to origin (required)
2. Translate image solar disk center to origin
3. Rotate image about the solar disk center to align with solar spin axis
4. Scale the image so that each pixel is square
5. Translate the image to the image center (required)
(2) In python, the image transformations are about the axis origin (0, 0). Therefore, the image point
to rotate about should be shifted to (0, 0) before the rotation.
(3) Axis 1 refers to the physical x-axis and axis 2 refers to the physical y-axis, e.g. CRPIX1 is
the center pixel value wrt the x-axis and CRPIX2 is wrt the y-axis.
"""
from skimage.transform import ProjectiveTransform
# Start with 3x3 identity matrix and original header metadata (no corrections)
t_matrix = np.identity(3)
upd_meta = header
# (1) Translate the image center to the origin (required transformation)
# Read in required keywords from header
try:
img_dim = (header["NAXIS1"], header["NAXIS2"])
except KeyError:
return None, None
else:
# Transformation matrix
t_matrix = np.matmul(np.array([[1., 0., -(img_dim[0] + 1) / 2.],
[0., 1., -(img_dim[1] + 1) / 2.],
[0., 0., 1.]]), t_matrix)
# (2) Translate image solar disk center to origin
if translate_origin:
# Read in required keywords from header
try:
sun_origin = (header["CRPIX1"], header["CRPIX2"])
except KeyError:
return None, None
else:
# Transformation matrix
t_matrix = np.matmul(np.array([[1., 0., -sun_origin[0] + (img_dim[0] + 1) / 2.],
[0., 1., -sun_origin[1] + (img_dim[1] + 1) / 2.],
[0., 0., 1.]]), t_matrix)
# Update metadata: CRPIX1 and CRPIX2 are at the center of the image
upd_meta["CRPIX1"] = (img_dim[0] + 1) / 2.
upd_meta["CRPIX2"] = (img_dim[1] + 1) / 2.
# (3) Rotate image to align with solar spin axis
if rotate:
# Read in required keywords from header
try:
PC1_1 = header['PC1_1']
PC1_2 = header['PC1_2']
PC2_1 = header['PC2_1']
PC2_2 = header['PC2_2']
except KeyError:
try:
CROTA = header['CROTA'] * (np.pi / 180.) # [rad]
plt_scale = (header["CDELT1"], header["CDELT2"])
except KeyError:
return None, None
else:
t_matrix = np.matmul(np.array([[np.cos(CROTA), -np.sin(CROTA) * (plt_scale[1] / plt_scale[0]), 0.],
[np.sin(CROTA) * (plt_scale[0] / plt_scale[1]), np.cos(CROTA), 0.],
[0., 0., 1.]]), t_matrix)
# Update metadata: CROTA is zero and PCi_j matrix is the identity matrix
upd_meta["CROTA"] = 0.
upd_meta["PC1_1"] = 1.
upd_meta["PC1_2"] = 0.
upd_meta["PC2_1"] = 0.
upd_meta["PC2_2"] = 1.
else:
t_matrix = np.matmul(np.array([[PC1_1, PC1_2, 0.],
[PC2_1, PC2_2, 0.],
[0., 0., 1.]]), t_matrix)
# Update metadata: CROTA is zero and PCi_j matrix is the identity matrix
upd_meta["CROTA"] = 0.
upd_meta["PC1_1"] = 1.
upd_meta["PC1_2"] = 0.
upd_meta["PC2_1"] = 0.
upd_meta["PC2_2"] = 1.
# (4) Scale the image so that each pixel is square
if scale:
# Read in required keywords from header
try:
plt_scale = (header["CDELT1"], header["CDELT2"])
except KeyError:
return None, None
else:
# Product of minimum plate scale and axis dimension
min_scl = cdelt_min * naxis_min
# Determine smallest axis
naxis_ref = min(img_dim)
# Transformation matrix
t_matrix = np.matmul(np.array([[(plt_scale[0] * naxis_ref) / min_scl, 0., 0.],
[0., (plt_scale[1] * naxis_ref) / min_scl, 0.],
[0., 0., 1.]]), t_matrix)
# Update the metadata: CDELT1 and CDELT2 are scaled by factor to make each pixel square
upd_meta["CDELT1"] = plt_scale[0] / ((plt_scale[0] * naxis_ref) / min_scl)
upd_meta["CDELT2"] = plt_scale[1] / ((plt_scale[1] * naxis_ref) / min_scl)
# (5) Translate the image to the image center (required transformation)
t_matrix = np.matmul(np.array([[1., 0., (img_dim[0] + 1) / 2.],
[0., 1., (img_dim[1] + 1) / 2.],
[0., 0., 1.]]), t_matrix)
# Transform the image with all specified operations
# NOTE: The inverse transformation needs to be applied because the transformation matrix
# describes operations on the pixel coordinate frame instead of the image itself. The inverse
# transformation will perform the intended operations on the image. Also, any values outside of
# the image boundaries are set to zero.
data_corr = warp(data, ProjectiveTransform(matrix=t_matrix).inverse, cval=0., preserve_range=True)
# Check if NaNs are generated from transformation
try:
assert not np.any(np.isnan(data_corr))
except AssertionError:
pass
return data_corr, upd_meta | [
"def",
"align_solar_fov",
"(",
"header",
",",
"data",
",",
"cdelt_min",
",",
"naxis_min",
",",
"translate_origin",
"=",
"True",
",",
"rotate",
"=",
"True",
",",
"scale",
"=",
"True",
")",
":",
"from",
"skimage",
".",
"transform",
"import",
"ProjectiveTransfo... | taken from suvi code by vhsu
Apply field of view image corrections
:param header: FITS header
:param data: Image data
:param cdelt_min: Minimum plate scale for images (static run config param)
:param naxis_min: Minimum axis dimension for images (static run config param)
:param translate_origin: Translate image to specified origin (dtype=bool)
:param rotate: Rotate image about origin (dtype=bool)
:param scale: Scale image (dtype=bool)
:rtype: numpy.ndarray
:return: data_corr (corrected/aligned image)
:rtype: astropy.io.fits.header Header instance
:return: upd_meta (updated metadata after image corrections)
NOTES: (1) The associative property of matrix multiplication makes it possible to multiply
transformation matrices together to produce a single transformation. However, the order
of each transformation matters. In this algorithm, the order is:
1. Translate image center to origin (required)
2. Translate image solar disk center to origin
3. Rotate image about the solar disk center to align with solar spin axis
4. Scale the image so that each pixel is square
5. Translate the image to the image center (required)
(2) In python, the image transformations are about the axis origin (0, 0). Therefore, the image point
to rotate about should be shifted to (0, 0) before the rotation.
(3) Axis 1 refers to the physical x-axis and axis 2 refers to the physical y-axis, e.g. CRPIX1 is
the center pixel value wrt the x-axis and CRPIX2 is wrt the y-axis. | [
"taken",
"from",
"suvi",
"code",
"by",
"vhsu",
"Apply",
"field",
"of",
"view",
"image",
"corrections"
] | python | train |
sparklingpandas/sparklingpandas | sparklingpandas/groupby.py | https://github.com/sparklingpandas/sparklingpandas/blob/7d549df4348c979042b683c355aa778fc6d3a768/sparklingpandas/groupby.py#L366-L375 | def nth(self, n, *args, **kwargs):
"""Take the nth element of each grouby."""
# TODO: Stop collecting the entire frame for each key.
self._prep_pandas_groupby()
myargs = self._myargs
mykwargs = self._mykwargs
nthRDD = self._regroup_mergedRDD().mapValues(
lambda r: r.nth(
n, *args, **kwargs)).values()
return DataFrame.fromDataFrameRDD(nthRDD, self.sql_ctx) | [
"def",
"nth",
"(",
"self",
",",
"n",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO: Stop collecting the entire frame for each key.",
"self",
".",
"_prep_pandas_groupby",
"(",
")",
"myargs",
"=",
"self",
".",
"_myargs",
"mykwargs",
"=",
"self",
... | Take the nth element of each grouby. | [
"Take",
"the",
"nth",
"element",
"of",
"each",
"grouby",
"."
] | python | train |
Esri/ArcREST | src/arcrest/manageags/_services.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageags/_services.py#L87-L106 | def folderName(self, folder):
"""gets/set the current folder"""
if folder == "" or\
folder == "/":
self._currentURL = self._url
self._services = None
self._description = None
self._folderName = None
self._webEncrypted = None
self.__init()
self._folderName = folder
elif folder in self.folders:
self._currentURL = self._url + "/%s" % folder
self._services = None
self._description = None
self._folderName = None
self._webEncrypted = None
self.__init()
self._folderName = folder | [
"def",
"folderName",
"(",
"self",
",",
"folder",
")",
":",
"if",
"folder",
"==",
"\"\"",
"or",
"folder",
"==",
"\"/\"",
":",
"self",
".",
"_currentURL",
"=",
"self",
".",
"_url",
"self",
".",
"_services",
"=",
"None",
"self",
".",
"_description",
"=",
... | gets/set the current folder | [
"gets",
"/",
"set",
"the",
"current",
"folder"
] | python | train |
thespacedoctor/rockAtlas | rockAtlas/positions/orbfitPositions.py | https://github.com/thespacedoctor/rockAtlas/blob/062ecaa95ab547efda535aa33165944f13c621de/rockAtlas/positions/orbfitPositions.py#L84-L119 | def get(self,
singleExposure=False):
"""
*get the orbfitPositions object*
**Key Arguments:**
- ``singleExposure`` -- only execute fot a single exposure (useful for debugging)
**Return:**
- None
**Usage:**
See class docstring
"""
self.log.info('starting the ``get`` method')
if singleExposure:
batchSize = 1
else:
batchSize = int(self.settings["orbfit"]["batch size"])
exposureCount = 1
while exposureCount > 0:
expsoureObjects, astorbString, exposureCount = self._get_exposures_requiring_orbfit_positions(
batchSize=batchSize)
if exposureCount:
orbfitPositions = self._get_orbfit_positions(
expsoureObjects, astorbString)
self._add_orbfit_eph_to_database(
orbfitPositions, expsoureObjects)
if singleExposure:
exposureCount = 0
self.log.info('completed the ``get`` method')
return None | [
"def",
"get",
"(",
"self",
",",
"singleExposure",
"=",
"False",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``get`` method'",
")",
"if",
"singleExposure",
":",
"batchSize",
"=",
"1",
"else",
":",
"batchSize",
"=",
"int",
"(",
"self",
"... | *get the orbfitPositions object*
**Key Arguments:**
- ``singleExposure`` -- only execute fot a single exposure (useful for debugging)
**Return:**
- None
**Usage:**
See class docstring | [
"*",
"get",
"the",
"orbfitPositions",
"object",
"*"
] | python | train |
czielinski/portfolioopt | portfolioopt/portfolioopt.py | https://github.com/czielinski/portfolioopt/blob/96ac25daab0c0dbc8933330a92ff31fb898112f2/portfolioopt/portfolioopt.py#L45-L122 | def markowitz_portfolio(cov_mat, exp_rets, target_ret,
allow_short=False, market_neutral=False):
"""
Computes a Markowitz portfolio.
Parameters
----------
cov_mat: pandas.DataFrame
Covariance matrix of asset returns.
exp_rets: pandas.Series
Expected asset returns (often historical returns).
target_ret: float
Target return of portfolio.
allow_short: bool, optional
If 'False' construct a long-only portfolio.
If 'True' allow shorting, i.e. negative weights.
market_neutral: bool, optional
If 'False' sum of weights equals one.
If 'True' sum of weights equal zero, i.e. create a
market neutral portfolio (implies allow_short=True).
Returns
-------
weights: pandas.Series
Optimal asset weights.
"""
if not isinstance(cov_mat, pd.DataFrame):
raise ValueError("Covariance matrix is not a DataFrame")
if not isinstance(exp_rets, pd.Series):
raise ValueError("Expected returns is not a Series")
if not isinstance(target_ret, float):
raise ValueError("Target return is not a float")
if not cov_mat.index.equals(exp_rets.index):
raise ValueError("Indices do not match")
if market_neutral and not allow_short:
warnings.warn("A market neutral portfolio implies shorting")
allow_short=True
n = len(cov_mat)
P = opt.matrix(cov_mat.values)
q = opt.matrix(0.0, (n, 1))
# Constraints Gx <= h
if not allow_short:
# exp_rets*x >= target_ret and x >= 0
G = opt.matrix(np.vstack((-exp_rets.values,
-np.identity(n))))
h = opt.matrix(np.vstack((-target_ret,
+np.zeros((n, 1)))))
else:
# exp_rets*x >= target_ret
G = opt.matrix(-exp_rets.values).T
h = opt.matrix(-target_ret)
# Constraints Ax = b
# sum(x) = 1
A = opt.matrix(1.0, (1, n))
if not market_neutral:
b = opt.matrix(1.0)
else:
b = opt.matrix(0.0)
# Solve
optsolvers.options['show_progress'] = False
sol = optsolvers.qp(P, q, G, h, A, b)
if sol['status'] != 'optimal':
warnings.warn("Convergence problem")
# Put weights into a labeled series
weights = pd.Series(sol['x'], index=cov_mat.index)
return weights | [
"def",
"markowitz_portfolio",
"(",
"cov_mat",
",",
"exp_rets",
",",
"target_ret",
",",
"allow_short",
"=",
"False",
",",
"market_neutral",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"cov_mat",
",",
"pd",
".",
"DataFrame",
")",
":",
"raise",
"V... | Computes a Markowitz portfolio.
Parameters
----------
cov_mat: pandas.DataFrame
Covariance matrix of asset returns.
exp_rets: pandas.Series
Expected asset returns (often historical returns).
target_ret: float
Target return of portfolio.
allow_short: bool, optional
If 'False' construct a long-only portfolio.
If 'True' allow shorting, i.e. negative weights.
market_neutral: bool, optional
If 'False' sum of weights equals one.
If 'True' sum of weights equal zero, i.e. create a
market neutral portfolio (implies allow_short=True).
Returns
-------
weights: pandas.Series
Optimal asset weights. | [
"Computes",
"a",
"Markowitz",
"portfolio",
"."
] | python | train |
danilobellini/audiolazy | math/lowpass_highpass_digital.py | https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/math/lowpass_highpass_digital.py#L46-L125 | def design_z_filter_single_pole(filt_str, max_gain_freq):
"""
Finds the coefficients for a simple lowpass/highpass filter.
This function just prints the coefficient values, besides the given
filter equation and its power gain. There's 3 constraints used to find the
coefficients:
1. The G value is defined by the max gain of 1 (0 dB) imposed at a
specific frequency
2. The R value is defined by the 50% power cutoff frequency given in
rad/sample.
3. Filter should be stable (-1 < R < 1)
Parameters
----------
filt_str :
Filter equation as a string using the G, R, w and z values.
max_gain_freq :
A value of zero (DC) or pi (Nyquist) to ensure the max gain as 1 (0 dB).
Note
----
The R value is evaluated only at pi/4 rad/sample to find whether -1 < R < 1,
and the max gain is assumed to be either 0 or pi, using other values might
fail.
"""
print("H(z) = " + filt_str) # Avoids printing as "1/z"
filt = sympify(filt_str, dict(G=G, R=R, w=w, z=z))
print()
# Finds the power magnitude equation for the filter
freq_resp = filt.subs(z, exp(I * w))
frr, fri = freq_resp.as_real_imag()
power_resp = fcompose(expand_complex, cancel, trigsimp)(frr ** 2 + fri ** 2)
pprint(Eq(Symbol("Power"), power_resp))
print()
# Finds the G value given the max gain value of 1 at the DC or Nyquist
# frequency. As exp(I*pi) is -1 and exp(I*0) is 1, we can use freq_resp
# (without "abs") instead of power_resp.
Gsolutions = factor(solve(Eq(freq_resp.subs(w, max_gain_freq), 1), G))
assert len(Gsolutions) == 1
pprint(Eq(G, Gsolutions[0]))
print()
# Finds the unconstrained R values for a given cutoff frequency
power_resp_no_G = power_resp.subs(G, Gsolutions[0])
half_power_eq = Eq(power_resp_no_G, S.Half)
Rsolutions = solve(half_power_eq, R)
# Constraining -1 < R < 1 when w = pi/4 (although the constraint is general)
Rsolutions_stable = [el for el in Rsolutions if -1 < el.subs(w, pi/4) < 1]
assert len(Rsolutions_stable) == 1
# Constraining w to the [0;pi] range, so |sin(w)| = sin(w)
Rsolution = Rsolutions_stable[0].subs(abs(sin(w)), sin(w))
pprint(Eq(R, Rsolution))
# More information about the pole (or -pole)
print("\n ** Alternative way to write R **\n")
if has_sqrt(Rsolution):
x = Symbol("x") # A helper symbol
xval = sum(el for el in Rsolution.args if not has_sqrt(el))
pprint(Eq(x, xval))
print()
pprint(Eq(R, expand(Rsolution.subs(xval, x))))
else:
# That's also what would be found in a bilinear transform with prewarping
pprint(Eq(R, Rsolution.rewrite(tan).cancel())) # Not so nice numerically
# See whether the R denominator can be zeroed
for root in solve(fraction(Rsolution)[1], w):
if 0 <= root <= pi:
power_resp_r = fcompose(expand, cancel)(power_resp_no_G.subs(w, root))
Rsolutions_r = solve(Eq(power_resp_r, S.Half), R)
assert len(Rsolutions_r) == 1
print("\nDenominator is zero for this value of " + pretty(w))
pprint(Eq(w, root))
pprint(Eq(R, Rsolutions_r[0])) | [
"def",
"design_z_filter_single_pole",
"(",
"filt_str",
",",
"max_gain_freq",
")",
":",
"print",
"(",
"\"H(z) = \"",
"+",
"filt_str",
")",
"# Avoids printing as \"1/z\"",
"filt",
"=",
"sympify",
"(",
"filt_str",
",",
"dict",
"(",
"G",
"=",
"G",
",",
"R",
"=",
... | Finds the coefficients for a simple lowpass/highpass filter.
This function just prints the coefficient values, besides the given
filter equation and its power gain. There's 3 constraints used to find the
coefficients:
1. The G value is defined by the max gain of 1 (0 dB) imposed at a
specific frequency
2. The R value is defined by the 50% power cutoff frequency given in
rad/sample.
3. Filter should be stable (-1 < R < 1)
Parameters
----------
filt_str :
Filter equation as a string using the G, R, w and z values.
max_gain_freq :
A value of zero (DC) or pi (Nyquist) to ensure the max gain as 1 (0 dB).
Note
----
The R value is evaluated only at pi/4 rad/sample to find whether -1 < R < 1,
and the max gain is assumed to be either 0 or pi, using other values might
fail. | [
"Finds",
"the",
"coefficients",
"for",
"a",
"simple",
"lowpass",
"/",
"highpass",
"filter",
"."
] | python | train |
serge-sans-paille/pythran | pythran/backend.py | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/backend.py#L1275-L1289 | def visit_Module(self, node):
""" Build a compilation unit. """
# build all types
deps = sorted(self.dependencies)
headers = [Include(os.path.join("pythonic", "include", *t) + ".hpp")
for t in deps]
headers += [Include(os.path.join("pythonic", *t) + ".hpp")
for t in deps]
decls_n_defns = [self.visit(stmt) for stmt in node.body]
decls, defns = zip(*[s for s in decls_n_defns if s])
nsbody = [s for ls in decls + defns for s in ls]
ns = Namespace(pythran_ward + self.passmanager.module_name, nsbody)
self.result = CompilationUnit(headers + [ns]) | [
"def",
"visit_Module",
"(",
"self",
",",
"node",
")",
":",
"# build all types",
"deps",
"=",
"sorted",
"(",
"self",
".",
"dependencies",
")",
"headers",
"=",
"[",
"Include",
"(",
"os",
".",
"path",
".",
"join",
"(",
"\"pythonic\"",
",",
"\"include\"",
",... | Build a compilation unit. | [
"Build",
"a",
"compilation",
"unit",
"."
] | python | train |
bitcraft/pyscroll | pyscroll/isometric.py | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/isometric.py#L86-L127 | def center(self, coords):
""" center the map on a "map pixel"
"""
x, y = [round(i, 0) for i in coords]
self.view_rect.center = x, y
tw, th = self.data.tile_size
left, ox = divmod(x, tw)
top, oy = divmod(y, th)
vec = int(ox / 2), int(oy)
iso = vector2_to_iso(vec)
self._x_offset = iso[0]
self._y_offset = iso[1]
print(self._tile_view.size)
print(self._buffer.get_size())
# center the buffer on the screen
self._x_offset += (self._buffer.get_width() - self.view_rect.width) // 2
self._y_offset += (self._buffer.get_height() - self.view_rect.height) // 4
# adjust the view if the view has changed without a redraw
dx = int(left - self._tile_view.left)
dy = int(top - self._tile_view.top)
view_change = max(abs(dx), abs(dy))
# force redraw every time: edge queuing not supported yet
self._redraw_cutoff = 0
if view_change and (view_change <= self._redraw_cutoff):
self._buffer.scroll(-dx * tw, -dy * th)
self._tile_view.move_ip(dx, dy)
self._queue_edge_tiles(dx, dy)
self._flush_tile_queue()
elif view_change > self._redraw_cutoff:
# logger.info('scrolling too quickly. redraw forced')
self._tile_view.move_ip(dx, dy)
self.redraw_tiles() | [
"def",
"center",
"(",
"self",
",",
"coords",
")",
":",
"x",
",",
"y",
"=",
"[",
"round",
"(",
"i",
",",
"0",
")",
"for",
"i",
"in",
"coords",
"]",
"self",
".",
"view_rect",
".",
"center",
"=",
"x",
",",
"y",
"tw",
",",
"th",
"=",
"self",
".... | center the map on a "map pixel" | [
"center",
"the",
"map",
"on",
"a",
"map",
"pixel"
] | python | train |
FulcrumTechnologies/pyconfluence | pyconfluence/api.py | https://github.com/FulcrumTechnologies/pyconfluence/blob/a999726dbc1cbdd3d9062234698eeae799ce84ce/pyconfluence/api.py#L67-L84 | def _api_action(url, req, data=None):
"""Take action based on what kind of request is needed."""
requisite_headers = {'Accept': 'application/json',
'Content-Type': 'application/json'}
auth = (user, token)
if req == "GET":
response = requests.get(url, headers=requisite_headers, auth=auth)
elif req == "PUT":
response = requests.put(url, headers=requisite_headers, auth=auth,
data=data)
elif req == "POST":
response = requests.post(url, headers=requisite_headers, auth=auth,
data=data)
elif req == "DELETE":
response = requests.delete(url, headers=requisite_headers, auth=auth)
return response.status_code, response.text | [
"def",
"_api_action",
"(",
"url",
",",
"req",
",",
"data",
"=",
"None",
")",
":",
"requisite_headers",
"=",
"{",
"'Accept'",
":",
"'application/json'",
",",
"'Content-Type'",
":",
"'application/json'",
"}",
"auth",
"=",
"(",
"user",
",",
"token",
")",
"if"... | Take action based on what kind of request is needed. | [
"Take",
"action",
"based",
"on",
"what",
"kind",
"of",
"request",
"is",
"needed",
"."
] | python | train |
bear/ninka | ninka/micropub.py | https://github.com/bear/ninka/blob/4d13a48d2b8857496f7fc470b0c379486351c89b/ninka/micropub.py#L91-L104 | def discoverMicropubEndpoints(domain, content=None, look_in={'name': 'link'}, test_urls=True, validateCerts=True):
"""Find the micropub for the given domain.
Only scan html element matching all criteria in look_in.
optionally the content to be scanned can be given as an argument.
:param domain: the URL of the domain to handle
:param content: the content to be scanned for the endpoint
:param look_in: dictionary with name, id and class_. only element matching all of these will be scanned
:param test_urls: optional flag to test URLs for validation
:param validateCerts: optional flag to enforce HTTPS certificates if present
:rtype: list of endpoints
"""
return discoverEndpoint(domain, ('micropub',), content, look_in, test_urls, validateCerts) | [
"def",
"discoverMicropubEndpoints",
"(",
"domain",
",",
"content",
"=",
"None",
",",
"look_in",
"=",
"{",
"'name'",
":",
"'link'",
"}",
",",
"test_urls",
"=",
"True",
",",
"validateCerts",
"=",
"True",
")",
":",
"return",
"discoverEndpoint",
"(",
"domain",
... | Find the micropub for the given domain.
Only scan html element matching all criteria in look_in.
optionally the content to be scanned can be given as an argument.
:param domain: the URL of the domain to handle
:param content: the content to be scanned for the endpoint
:param look_in: dictionary with name, id and class_. only element matching all of these will be scanned
:param test_urls: optional flag to test URLs for validation
:param validateCerts: optional flag to enforce HTTPS certificates if present
:rtype: list of endpoints | [
"Find",
"the",
"micropub",
"for",
"the",
"given",
"domain",
".",
"Only",
"scan",
"html",
"element",
"matching",
"all",
"criteria",
"in",
"look_in",
"."
] | python | train |
pysathq/pysat | pysat/solvers.py | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/solvers.py#L2742-L2748 | def prop_budget(self, budget):
"""
Set limit on the number of propagations.
"""
if self.minicard:
pysolvers.minicard_pbudget(self.minicard, budget) | [
"def",
"prop_budget",
"(",
"self",
",",
"budget",
")",
":",
"if",
"self",
".",
"minicard",
":",
"pysolvers",
".",
"minicard_pbudget",
"(",
"self",
".",
"minicard",
",",
"budget",
")"
] | Set limit on the number of propagations. | [
"Set",
"limit",
"on",
"the",
"number",
"of",
"propagations",
"."
] | python | train |
Knio/dominate | dominate/util.py | https://github.com/Knio/dominate/blob/1eb88f9fd797658eef83568a548e2ef9b546807d/dominate/util.py#L54-L68 | def escape(data, quote=True): # stoled from std lib cgi
'''
Escapes special characters into their html entities
Replace special characters "&", "<" and ">" to HTML-safe sequences.
If the optional flag quote is true, the quotation mark character (")
is also translated.
This is used to escape content that appears in the body of an HTML cocument
'''
data = data.replace("&", "&") # Must be done first!
data = data.replace("<", "<")
data = data.replace(">", ">")
if quote:
data = data.replace('"', """)
return data | [
"def",
"escape",
"(",
"data",
",",
"quote",
"=",
"True",
")",
":",
"# stoled from std lib cgi",
"data",
"=",
"data",
".",
"replace",
"(",
"\"&\"",
",",
"\"&\"",
")",
"# Must be done first!",
"data",
"=",
"data",
".",
"replace",
"(",
"\"<\"",
",",
"\"&l... | Escapes special characters into their html entities
Replace special characters "&", "<" and ">" to HTML-safe sequences.
If the optional flag quote is true, the quotation mark character (")
is also translated.
This is used to escape content that appears in the body of an HTML cocument | [
"Escapes",
"special",
"characters",
"into",
"their",
"html",
"entities",
"Replace",
"special",
"characters",
"&",
"<",
"and",
">",
"to",
"HTML",
"-",
"safe",
"sequences",
".",
"If",
"the",
"optional",
"flag",
"quote",
"is",
"true",
"the",
"quotation",
"mark"... | python | valid |
konture/CloeePy | cloeepy/logger.py | https://github.com/konture/CloeePy/blob/dcb21284d2df405d92ac6868ea7215792c9323b9/cloeepy/logger.py#L49-L57 | def _set_formatter(self):
"""
Inspects config and sets the name of the formatter to either "json" or "text"
as instance attr. If not present in config, default is "text"
"""
if hasattr(self._config, "formatter") and self._config.formatter == "json":
self._formatter = "json"
else:
self._formatter = "text" | [
"def",
"_set_formatter",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"_config",
",",
"\"formatter\"",
")",
"and",
"self",
".",
"_config",
".",
"formatter",
"==",
"\"json\"",
":",
"self",
".",
"_formatter",
"=",
"\"json\"",
"else",
":",
"sel... | Inspects config and sets the name of the formatter to either "json" or "text"
as instance attr. If not present in config, default is "text" | [
"Inspects",
"config",
"and",
"sets",
"the",
"name",
"of",
"the",
"formatter",
"to",
"either",
"json",
"or",
"text",
"as",
"instance",
"attr",
".",
"If",
"not",
"present",
"in",
"config",
"default",
"is",
"text"
] | python | train |
nitipit/appkit | appkit/app.py | https://github.com/nitipit/appkit/blob/08eeaf45a9ca884bf5fe105d47a81269d44b1412/appkit/app.py#L40-L68 | def do_startup(self):
"""Gtk.Application.run() will call this function()"""
Gtk.Application.do_startup(self)
gtk_window = Gtk.ApplicationWindow(application=self)
gtk_window.set_title('AppKit')
webkit_web_view = WebKit.WebView()
webkit_web_view.load_uri('http://localhost:' + str(self.port))
screen = Gdk.Screen.get_default()
monitor_geometry = screen.get_primary_monitor()
monitor_geometry = screen.get_monitor_geometry(monitor_geometry)
settings = webkit_web_view.get_settings()
settings.set_property('enable-universal-access-from-file-uris', True)
settings.set_property('enable-file-access-from-file-uris', True)
settings.set_property('default-encoding', 'utf-8')
gtk_window.set_default_size(
monitor_geometry.width * 1.0 / 2.0,
monitor_geometry.height * 3.0 / 5.0,
)
scrollWindow = Gtk.ScrolledWindow()
scrollWindow.add(webkit_web_view)
gtk_window.add(scrollWindow)
gtk_window.connect('delete-event', self._on_gtk_window_destroy)
webkit_web_view.connect('notify::title', self._on_notify_title)
self.gtk_window = gtk_window
self.webkit_web_view = webkit_web_view
gtk_window.show_all() | [
"def",
"do_startup",
"(",
"self",
")",
":",
"Gtk",
".",
"Application",
".",
"do_startup",
"(",
"self",
")",
"gtk_window",
"=",
"Gtk",
".",
"ApplicationWindow",
"(",
"application",
"=",
"self",
")",
"gtk_window",
".",
"set_title",
"(",
"'AppKit'",
")",
"web... | Gtk.Application.run() will call this function() | [
"Gtk",
".",
"Application",
".",
"run",
"()",
"will",
"call",
"this",
"function",
"()"
] | python | train |
wandb/client | wandb/vendor/prompt_toolkit/contrib/telnet/protocol.py | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/contrib/telnet/protocol.py#L175-L181 | def feed(self, data):
"""
Feed data to the parser.
"""
assert isinstance(data, binary_type)
for b in iterbytes(data):
self._parser.send(int2byte(b)) | [
"def",
"feed",
"(",
"self",
",",
"data",
")",
":",
"assert",
"isinstance",
"(",
"data",
",",
"binary_type",
")",
"for",
"b",
"in",
"iterbytes",
"(",
"data",
")",
":",
"self",
".",
"_parser",
".",
"send",
"(",
"int2byte",
"(",
"b",
")",
")"
] | Feed data to the parser. | [
"Feed",
"data",
"to",
"the",
"parser",
"."
] | python | train |
droope/droopescan | dscan/common/functions.py | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/common/functions.py#L246-L275 | def tail(f, window=20):
"""
Returns the last `window` lines of file `f` as a list.
@param window: the number of lines.
"""
if window == 0:
return []
BUFSIZ = 1024
f.seek(0, 2)
bytes = f.tell()
size = window + 1
block = -1
data = []
while size > 0 and bytes > 0:
if bytes - BUFSIZ > 0:
# Seek back one whole BUFSIZ
f.seek(block * BUFSIZ, 2)
# read BUFFER
data.insert(0, f.read(BUFSIZ).decode('utf-8', errors='ignore'))
else:
# file too small, start from begining
f.seek(0,0)
# only read what was not read
data.insert(0, f.read(bytes).decode('utf-8', errors='ignore'))
linesFound = data[0].count('\n')
size -= linesFound
bytes -= BUFSIZ
block -= 1
return ''.join(data).splitlines()[-window:] | [
"def",
"tail",
"(",
"f",
",",
"window",
"=",
"20",
")",
":",
"if",
"window",
"==",
"0",
":",
"return",
"[",
"]",
"BUFSIZ",
"=",
"1024",
"f",
".",
"seek",
"(",
"0",
",",
"2",
")",
"bytes",
"=",
"f",
".",
"tell",
"(",
")",
"size",
"=",
"windo... | Returns the last `window` lines of file `f` as a list.
@param window: the number of lines. | [
"Returns",
"the",
"last",
"window",
"lines",
"of",
"file",
"f",
"as",
"a",
"list",
"."
] | python | train |
ardydedase/pycouchbase | pycouchbase/viewsync.py | https://github.com/ardydedase/pycouchbase/blob/6f010b4d2ef41aead2366878d0cf0b1284c0db0e/pycouchbase/viewsync.py#L117-L176 | def upload(cls):
"""Uploads all the local views from :attr:`VIEW_PATHS` directory
to CouchBase server
This method **over-writes** all the server-side views with the same
named ones coming from :attr:`VIEW_PATHS` folder.
"""
cls._check_folder()
os.chdir(cls.VIEWS_PATH)
buckets = dict()
# iterate local folders
for bucket_name in os.listdir(cls.VIEWS_PATH):
if not os.path.isdir(bucket_name):
continue
# get bucket object
if bucket_name not in buckets:
try:
bucket = Connection.bucket(bucket_name)
except BucketNotFoundError as why:
print("[WARNING] %s" % str(why))
continue
else:
buckets[bucket_name] = bucket
else:
bucket = buckets[bucket_name]
# go through design docs
for ddoc_name in os.listdir(bucket_name):
views_path = '%s/%s/views' % (bucket_name, ddoc_name)
spatial_path = '%s/%s/spatial' % (bucket_name, ddoc_name)
if not (os.path.exists(views_path) and os.path.isdir(views_path)) and \
not (os.path.exists(spatial_path) and os.path.isdir(spatial_path)):
continue
# initialize design doc
new_ddoc = {
'views': {},
'spatial': {},
}
# map and reduces
if os.path.exists(views_path) and os.path.isdir(views_path):
for filename in os.listdir(views_path):
if not os.path.isfile('%s/%s' % (views_path, filename)) or \
not filename.endswith(('.map.js', '.reduce.js')):
continue
view_name, view_type, js = filename.rsplit('.', 2)
if view_name not in new_ddoc['views']:
new_ddoc['views'][view_name] = {}
with open('%s/%s' % (views_path, filename), 'r') as f:
new_ddoc['views'][view_name][view_type] = f.read()
# spatial views
if os.path.exists(spatial_path) and os.path.isdir(spatial_path):
for filename in os.listdir(spatial_path):
if not os.path.isfile('%s/%s' % (spatial_path, filename)) or \
not filename.endswith('.spatial.js'):
continue
view_name = filename.rsplit('.', 2)[0]
with open('%s/%s' % (spatial_path, filename), 'r') as f:
new_ddoc['spatial'][view_name] = f.read()
bucket['_design/%s' % ddoc_name] = new_ddoc
print('Uploaded design document: %s' % ddoc_name)
pass | [
"def",
"upload",
"(",
"cls",
")",
":",
"cls",
".",
"_check_folder",
"(",
")",
"os",
".",
"chdir",
"(",
"cls",
".",
"VIEWS_PATH",
")",
"buckets",
"=",
"dict",
"(",
")",
"# iterate local folders",
"for",
"bucket_name",
"in",
"os",
".",
"listdir",
"(",
"c... | Uploads all the local views from :attr:`VIEW_PATHS` directory
to CouchBase server
This method **over-writes** all the server-side views with the same
named ones coming from :attr:`VIEW_PATHS` folder. | [
"Uploads",
"all",
"the",
"local",
"views",
"from",
":",
"attr",
":",
"VIEW_PATHS",
"directory",
"to",
"CouchBase",
"server"
] | python | train |
ergoithz/browsepy | browsepy/compat.py | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/compat.py#L236-L259 | def pathconf(path,
os_name=os.name,
isdir_fnc=os.path.isdir,
pathconf_fnc=getattr(os, 'pathconf', None),
pathconf_names=getattr(os, 'pathconf_names', ())):
'''
Get all pathconf variables for given path.
:param path: absolute fs path
:type path: str
:returns: dictionary containing pathconf keys and their values (both str)
:rtype: dict
'''
if pathconf_fnc and pathconf_names:
return {key: pathconf_fnc(path, key) for key in pathconf_names}
if os_name == 'nt':
maxpath = 246 if isdir_fnc(path) else 259 # 260 minus <END>
else:
maxpath = 255 # conservative sane default
return {
'PC_PATH_MAX': maxpath,
'PC_NAME_MAX': maxpath - len(path),
} | [
"def",
"pathconf",
"(",
"path",
",",
"os_name",
"=",
"os",
".",
"name",
",",
"isdir_fnc",
"=",
"os",
".",
"path",
".",
"isdir",
",",
"pathconf_fnc",
"=",
"getattr",
"(",
"os",
",",
"'pathconf'",
",",
"None",
")",
",",
"pathconf_names",
"=",
"getattr",
... | Get all pathconf variables for given path.
:param path: absolute fs path
:type path: str
:returns: dictionary containing pathconf keys and their values (both str)
:rtype: dict | [
"Get",
"all",
"pathconf",
"variables",
"for",
"given",
"path",
"."
] | python | train |
unixsurfer/anycast_healthchecker | anycast_healthchecker/utils.py | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L125-L145 | def get_ip_prefixes_from_config(config, services, ip_version):
"""Build a set of IP prefixes found in service configuration files.
Arguments:
config (obg): A configparser object which holds our configuration.
services (list): A list of section names which are the name of the
service checks.
ip_version (int): IP protocol version
Returns:
A set of IP prefixes.
"""
ip_prefixes = set()
for service in services:
ip_prefix = ipaddress.ip_network(config.get(service, 'ip_prefix'))
if ip_prefix.version == ip_version:
ip_prefixes.add(ip_prefix.with_prefixlen)
return ip_prefixes | [
"def",
"get_ip_prefixes_from_config",
"(",
"config",
",",
"services",
",",
"ip_version",
")",
":",
"ip_prefixes",
"=",
"set",
"(",
")",
"for",
"service",
"in",
"services",
":",
"ip_prefix",
"=",
"ipaddress",
".",
"ip_network",
"(",
"config",
".",
"get",
"(",... | Build a set of IP prefixes found in service configuration files.
Arguments:
config (obg): A configparser object which holds our configuration.
services (list): A list of section names which are the name of the
service checks.
ip_version (int): IP protocol version
Returns:
A set of IP prefixes. | [
"Build",
"a",
"set",
"of",
"IP",
"prefixes",
"found",
"in",
"service",
"configuration",
"files",
"."
] | python | train |
kontron/python-aardvark | pyaardvark/aardvark.py | https://github.com/kontron/python-aardvark/blob/9827f669fbdc5bceb98e7d08a294b4e4e455d0d5/pyaardvark/aardvark.py#L326-L336 | def i2c_bitrate(self):
"""I2C bitrate in kHz. Not every bitrate is supported by the host
adapter. Therefore, the actual bitrate may be less than the value which
is set.
The power-on default value is 100 kHz.
"""
ret = api.py_aa_i2c_bitrate(self.handle, 0)
_raise_error_if_negative(ret)
return ret | [
"def",
"i2c_bitrate",
"(",
"self",
")",
":",
"ret",
"=",
"api",
".",
"py_aa_i2c_bitrate",
"(",
"self",
".",
"handle",
",",
"0",
")",
"_raise_error_if_negative",
"(",
"ret",
")",
"return",
"ret"
] | I2C bitrate in kHz. Not every bitrate is supported by the host
adapter. Therefore, the actual bitrate may be less than the value which
is set.
The power-on default value is 100 kHz. | [
"I2C",
"bitrate",
"in",
"kHz",
".",
"Not",
"every",
"bitrate",
"is",
"supported",
"by",
"the",
"host",
"adapter",
".",
"Therefore",
"the",
"actual",
"bitrate",
"may",
"be",
"less",
"than",
"the",
"value",
"which",
"is",
"set",
"."
] | python | train |
aaugustin/django-sequences | sequences/__init__.py | https://github.com/aaugustin/django-sequences/blob/0228ae003540ccb63be4a456fb8f63a2f4038de6/sequences/__init__.py#L13-L59 | def get_next_value(
sequence_name='default', initial_value=1, reset_value=None,
*, nowait=False, using=None):
"""
Return the next value for a given sequence.
"""
# Inner import because models cannot be imported before their application.
from .models import Sequence
if reset_value is not None:
assert initial_value < reset_value
if using is None:
using = router.db_for_write(Sequence)
connection = connections[using]
if (getattr(connection, 'pg_version', 0) >= 90500
and reset_value is None and not nowait):
# PostgreSQL ≥ 9.5 supports "upsert".
with connection.cursor() as cursor:
cursor.execute(UPSERT_QUERY, [sequence_name, initial_value])
last, = cursor.fetchone()
return last
else:
# Other databases require making more database queries.
with transaction.atomic(using=using, savepoint=False):
sequence, created = (
Sequence.objects
.select_for_update(nowait=nowait)
.get_or_create(name=sequence_name,
defaults={'last': initial_value})
)
if not created:
sequence.last += 1
if reset_value is not None and sequence.last >= reset_value:
sequence.last = initial_value
sequence.save()
return sequence.last | [
"def",
"get_next_value",
"(",
"sequence_name",
"=",
"'default'",
",",
"initial_value",
"=",
"1",
",",
"reset_value",
"=",
"None",
",",
"*",
",",
"nowait",
"=",
"False",
",",
"using",
"=",
"None",
")",
":",
"# Inner import because models cannot be imported before t... | Return the next value for a given sequence. | [
"Return",
"the",
"next",
"value",
"for",
"a",
"given",
"sequence",
"."
] | python | train |
google/grr | grr/core/grr_response_core/lib/parsers/linux_pam_parser.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/parsers/linux_pam_parser.py#L47-L84 | def EnumerateAllConfigs(self, stats, file_objects):
"""Generate RDFs for the fully expanded configs.
Args:
stats: A list of RDF StatEntries corresponding to the file_objects.
file_objects: A list of file handles.
Returns:
A tuple of a list of RDFValue PamConfigEntries found & a list of strings
which are the external config references found.
"""
# Convert the stats & file_objects into a cache of a
# simple path keyed dict of file contents.
cache = {}
for stat_obj, file_obj in zip(stats, file_objects):
cache[stat_obj.pathspec.path] = utils.ReadFileBytesAsUnicode(file_obj)
result = []
external = []
# Check to see if we have the old pam config file laying around.
if self.OLD_PAMCONF_FILENAME in cache:
# The PAM documentation says if it contains config data, then
# it takes precedence over the rest of the config.
# If it doesn't, the rest of the PAMDIR config counts.
result, external = self.EnumerateConfig(None, self.OLD_PAMCONF_FILENAME,
cache)
if result:
return result, external
# If we made it here, there isn't a old-style pam.conf file worth
# speaking of, so process everything!
for path in cache:
# PAM uses the basename as the 'service' id.
service = os.path.basename(path)
r, e = self.EnumerateConfig(service, path, cache)
result.extend(r)
external.extend(e)
return result, external | [
"def",
"EnumerateAllConfigs",
"(",
"self",
",",
"stats",
",",
"file_objects",
")",
":",
"# Convert the stats & file_objects into a cache of a",
"# simple path keyed dict of file contents.",
"cache",
"=",
"{",
"}",
"for",
"stat_obj",
",",
"file_obj",
"in",
"zip",
"(",
"s... | Generate RDFs for the fully expanded configs.
Args:
stats: A list of RDF StatEntries corresponding to the file_objects.
file_objects: A list of file handles.
Returns:
A tuple of a list of RDFValue PamConfigEntries found & a list of strings
which are the external config references found. | [
"Generate",
"RDFs",
"for",
"the",
"fully",
"expanded",
"configs",
"."
] | python | train |
fp12/achallonge | challonge/user.py | https://github.com/fp12/achallonge/blob/25780b3c48b66400a50ff9f884e4287afd4c89e4/challonge/user.py#L58-L95 | async def get_tournament(self, t_id: int = None, url: str = None, subdomain: str = None, force_update=False) -> Tournament:
""" gets a tournament with its id or url or url+subdomain
Note: from the API, it can't be known if the retrieved tournament was made from this user.
Thus, any tournament is added to the local list of tournaments, but some functions (updates/destroy...) cannot be used for tournaments not owned by this user.
|methcoro|
Args:
t_id: tournament id
url: last part of the tournament url (http://challonge.com/XXX)
subdomain: first part of the tournament url, if any (http://XXX.challonge.com/...)
force_update: *optional* set to True to force the data update from Challonge
Returns:
Tournament
Raises:
APIException
ValueError: if neither of the arguments are provided
"""
assert_or_raise((t_id is None) ^ (url is None),
ValueError,
'One of t_id or url must not be None')
found_t = self._find_tournament_by_id(t_id) if t_id is not None else self._find_tournament_by_url(url, subdomain)
if force_update or found_t is None:
param = t_id
if param is None:
if subdomain is not None:
param = '{}-{}'.format(subdomain, url)
else:
param = url
res = await self.connection('GET', 'tournaments/{}'.format(param))
self._refresh_tournament_from_json(res)
found_t = self._find_tournament_by_id(res['tournament']['id'])
return found_t | [
"async",
"def",
"get_tournament",
"(",
"self",
",",
"t_id",
":",
"int",
"=",
"None",
",",
"url",
":",
"str",
"=",
"None",
",",
"subdomain",
":",
"str",
"=",
"None",
",",
"force_update",
"=",
"False",
")",
"->",
"Tournament",
":",
"assert_or_raise",
"("... | gets a tournament with its id or url or url+subdomain
Note: from the API, it can't be known if the retrieved tournament was made from this user.
Thus, any tournament is added to the local list of tournaments, but some functions (updates/destroy...) cannot be used for tournaments not owned by this user.
|methcoro|
Args:
t_id: tournament id
url: last part of the tournament url (http://challonge.com/XXX)
subdomain: first part of the tournament url, if any (http://XXX.challonge.com/...)
force_update: *optional* set to True to force the data update from Challonge
Returns:
Tournament
Raises:
APIException
ValueError: if neither of the arguments are provided | [
"gets",
"a",
"tournament",
"with",
"its",
"id",
"or",
"url",
"or",
"url",
"+",
"subdomain",
"Note",
":",
"from",
"the",
"API",
"it",
"can",
"t",
"be",
"known",
"if",
"the",
"retrieved",
"tournament",
"was",
"made",
"from",
"this",
"user",
".",
"Thus",
... | python | train |
dj-stripe/dj-stripe | djstripe/management/commands/djstripe_sync_customers.py | https://github.com/dj-stripe/dj-stripe/blob/a5308a3808cd6e2baba49482f7a699f3a8992518/djstripe/management/commands/djstripe_sync_customers.py#L15-L28 | def handle(self, *args, **options):
"""Call sync_subscriber on Subscribers without customers associated to them."""
qs = get_subscriber_model().objects.filter(djstripe_customers__isnull=True)
count = 0
total = qs.count()
for subscriber in qs:
count += 1
perc = int(round(100 * (float(count) / float(total))))
print(
"[{0}/{1} {2}%] Syncing {3} [{4}]".format(
count, total, perc, subscriber.email, subscriber.pk
)
)
sync_subscriber(subscriber) | [
"def",
"handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"qs",
"=",
"get_subscriber_model",
"(",
")",
".",
"objects",
".",
"filter",
"(",
"djstripe_customers__isnull",
"=",
"True",
")",
"count",
"=",
"0",
"total",
"=",
"qs",
... | Call sync_subscriber on Subscribers without customers associated to them. | [
"Call",
"sync_subscriber",
"on",
"Subscribers",
"without",
"customers",
"associated",
"to",
"them",
"."
] | python | train |
CalebBell/ht | ht/insulation.py | https://github.com/CalebBell/ht/blob/3097ef9524c4cf0068ad453c17b10ec9ce551eee/ht/insulation.py#L496-L535 | def refractory_VDI_k(ID, T=None):
r'''Returns thermal conductivity of a refractory material from a table in
[1]_. Here, thermal conductivity is a function of temperature between
673.15 K and 1473.15 K according to linear interpolation among 5
equally-spaced points. Here, thermal conductivity is not a function of
porosity, which can affect it. If T is outside the acceptable range, it is
rounded to the nearest limit. If T is not provided, the lowest temperature's
value is provided.
Parameters
----------
ID : str
ID corresponding to a material in the dictionary `refractories`
T : float, optional
Temperature of the refractory material, [K]
Returns
-------
k : float
Thermal conductivity of the refractory material, [W/m/K]
Examples
--------
>>> [refractory_VDI_k('Fused silica', i) for i in [None, 200, 1000, 1500]]
[1.44, 1.44, 1.58074, 1.73]
References
----------
.. [1] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition.
Berlin; New York:: Springer, 2010.
'''
if T is None:
return float(refractories[ID][1][0])
else:
ks = refractories[ID][1]
if T < _refractory_Ts[0]:
T = _refractory_Ts[0]
elif T > _refractory_Ts[-1]:
T = _refractory_Ts[-1]
return float(np.interp(T, _refractory_Ts, ks)) | [
"def",
"refractory_VDI_k",
"(",
"ID",
",",
"T",
"=",
"None",
")",
":",
"if",
"T",
"is",
"None",
":",
"return",
"float",
"(",
"refractories",
"[",
"ID",
"]",
"[",
"1",
"]",
"[",
"0",
"]",
")",
"else",
":",
"ks",
"=",
"refractories",
"[",
"ID",
"... | r'''Returns thermal conductivity of a refractory material from a table in
[1]_. Here, thermal conductivity is a function of temperature between
673.15 K and 1473.15 K according to linear interpolation among 5
equally-spaced points. Here, thermal conductivity is not a function of
porosity, which can affect it. If T is outside the acceptable range, it is
rounded to the nearest limit. If T is not provided, the lowest temperature's
value is provided.
Parameters
----------
ID : str
ID corresponding to a material in the dictionary `refractories`
T : float, optional
Temperature of the refractory material, [K]
Returns
-------
k : float
Thermal conductivity of the refractory material, [W/m/K]
Examples
--------
>>> [refractory_VDI_k('Fused silica', i) for i in [None, 200, 1000, 1500]]
[1.44, 1.44, 1.58074, 1.73]
References
----------
.. [1] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition.
Berlin; New York:: Springer, 2010. | [
"r",
"Returns",
"thermal",
"conductivity",
"of",
"a",
"refractory",
"material",
"from",
"a",
"table",
"in",
"[",
"1",
"]",
"_",
".",
"Here",
"thermal",
"conductivity",
"is",
"a",
"function",
"of",
"temperature",
"between",
"673",
".",
"15",
"K",
"and",
"... | python | train |
scivision/sciencedates | sciencedates/__init__.py | https://github.com/scivision/sciencedates/blob/a713389e027b42d26875cf227450a5d7c6696000/sciencedates/__init__.py#L40-L72 | def yeardoy2datetime(yeardate: int,
utsec: Union[float, int] = None) -> datetime.datetime:
"""
Inputs:
yd: yyyyddd four digit year, 3 digit day of year (INTEGER 7 digits)
outputs:
t: datetime
http://stackoverflow.com/questions/2427555/python-question-year-and-day-of-year-to-date
"""
if isinstance(yeardate, (tuple, list, np.ndarray)):
if utsec is None:
return np.asarray([yeardoy2datetime(y) for y in yeardate])
elif isinstance(utsec, (tuple, list, np.ndarray)):
return np.asarray([yeardoy2datetime(y, s) for y, s in zip(yeardate, utsec)])
yeardate = int(yeardate)
yd = str(yeardate)
if len(yd) != 7:
raise ValueError('yyyyddd expected')
year = int(yd[:4])
assert 0 < year < 3000, 'year not in expected format'
dt = datetime.datetime(year, 1, 1) + datetime.timedelta(days=int(yd[4:]) - 1)
assert isinstance(dt, datetime.datetime)
if utsec is not None:
dt += datetime.timedelta(seconds=utsec)
return dt | [
"def",
"yeardoy2datetime",
"(",
"yeardate",
":",
"int",
",",
"utsec",
":",
"Union",
"[",
"float",
",",
"int",
"]",
"=",
"None",
")",
"->",
"datetime",
".",
"datetime",
":",
"if",
"isinstance",
"(",
"yeardate",
",",
"(",
"tuple",
",",
"list",
",",
"np... | Inputs:
yd: yyyyddd four digit year, 3 digit day of year (INTEGER 7 digits)
outputs:
t: datetime
http://stackoverflow.com/questions/2427555/python-question-year-and-day-of-year-to-date | [
"Inputs",
":",
"yd",
":",
"yyyyddd",
"four",
"digit",
"year",
"3",
"digit",
"day",
"of",
"year",
"(",
"INTEGER",
"7",
"digits",
")"
] | python | train |
log2timeline/plaso | plaso/parsers/msiecf.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/msiecf.py#L193-L214 | def _ParseRedirected(
self, parser_mediator, msiecf_item, recovered=False):
"""Extract data from a MSIE Cache Files (MSIECF) redirected item.
Every item is stored as an event object, one for each timestamp.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
msiecf_item (pymsiecf.redirected): MSIECF redirected item.
recovered (Optional[bool]): True if the item was recovered.
"""
date_time = dfdatetime_semantic_time.SemanticTime('Not set')
event_data = MSIECFRedirectedEventData()
event_data.offset = msiecf_item.offset
event_data.recovered = recovered
event_data.url = msiecf_item.location
event = time_events.DateTimeValuesEvent(
date_time, definitions.TIME_DESCRIPTION_NOT_A_TIME)
parser_mediator.ProduceEventWithEventData(event, event_data) | [
"def",
"_ParseRedirected",
"(",
"self",
",",
"parser_mediator",
",",
"msiecf_item",
",",
"recovered",
"=",
"False",
")",
":",
"date_time",
"=",
"dfdatetime_semantic_time",
".",
"SemanticTime",
"(",
"'Not set'",
")",
"event_data",
"=",
"MSIECFRedirectedEventData",
"(... | Extract data from a MSIE Cache Files (MSIECF) redirected item.
Every item is stored as an event object, one for each timestamp.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
msiecf_item (pymsiecf.redirected): MSIECF redirected item.
recovered (Optional[bool]): True if the item was recovered. | [
"Extract",
"data",
"from",
"a",
"MSIE",
"Cache",
"Files",
"(",
"MSIECF",
")",
"redirected",
"item",
"."
] | python | train |
rconradharris/envparse | envparse.py | https://github.com/rconradharris/envparse/blob/e67e70307af19d925e194b2a163e0608dae7eb55/envparse.py#L167-L214 | def read_envfile(path=None, **overrides):
"""
Read a .env file (line delimited KEY=VALUE) into os.environ.
If not given a path to the file, recurses up the directory tree until
found.
Uses code from Honcho (github.com/nickstenning/honcho) for parsing the
file.
"""
if path is None:
frame = inspect.currentframe().f_back
caller_dir = os.path.dirname(frame.f_code.co_filename)
path = os.path.join(os.path.abspath(caller_dir), '.env')
try:
with open(path, 'r') as f:
content = f.read()
except getattr(__builtins__, 'FileNotFoundError', IOError):
logger.debug('envfile not found at %s, looking in parent dir.',
path)
filedir, filename = os.path.split(path)
pardir = os.path.abspath(os.path.join(filedir, os.pardir))
path = os.path.join(pardir, filename)
if filedir != pardir:
Env.read_envfile(path, **overrides)
else:
# Reached top level directory.
warnings.warn('Could not any envfile.')
return
logger.debug('Reading environment variables from: %s', path)
for line in content.splitlines():
tokens = list(shlex.shlex(line, posix=True))
# parses the assignment statement
if len(tokens) < 3:
continue
name, op = tokens[:2]
value = ''.join(tokens[2:])
if op != '=':
continue
if not re.match(r'[A-Za-z_][A-Za-z_0-9]*', name):
continue
value = value.replace(r'\n', '\n').replace(r'\t', '\t')
os.environ.setdefault(name, value)
for name, value in overrides.items():
os.environ.setdefault(name, value) | [
"def",
"read_envfile",
"(",
"path",
"=",
"None",
",",
"*",
"*",
"overrides",
")",
":",
"if",
"path",
"is",
"None",
":",
"frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
".",
"f_back",
"caller_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
... | Read a .env file (line delimited KEY=VALUE) into os.environ.
If not given a path to the file, recurses up the directory tree until
found.
Uses code from Honcho (github.com/nickstenning/honcho) for parsing the
file. | [
"Read",
"a",
".",
"env",
"file",
"(",
"line",
"delimited",
"KEY",
"=",
"VALUE",
")",
"into",
"os",
".",
"environ",
"."
] | python | train |
mkouhei/tonicdnscli | src/tonicdnscli/command.py | https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/command.py#L401-L413 | def delete_zone(args):
"""Delete zone.
Argument:
args: arguments object
"""
if args.__dict__.get('domain'):
domain = args.domain
password = get_password(args)
token = connect.get_token(args.username, password, args.server)
processing.delete_zone(args.server, token, domain) | [
"def",
"delete_zone",
"(",
"args",
")",
":",
"if",
"args",
".",
"__dict__",
".",
"get",
"(",
"'domain'",
")",
":",
"domain",
"=",
"args",
".",
"domain",
"password",
"=",
"get_password",
"(",
"args",
")",
"token",
"=",
"connect",
".",
"get_token",
"(",
... | Delete zone.
Argument:
args: arguments object | [
"Delete",
"zone",
"."
] | python | train |
tensorflow/probability | tensorflow_probability/python/stats/quantiles.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/stats/quantiles.py#L726-L787 | def _get_static_ndims(x,
expect_static=False,
expect_ndims=None,
expect_ndims_no_more_than=None,
expect_ndims_at_least=None):
"""Get static number of dimensions and assert that some expectations are met.
This function returns the number of dimensions 'ndims' of x, as a Python int.
The optional expect arguments are used to check the ndims of x, but this is
only done if the static ndims of x is not None.
Args:
x: A Tensor.
expect_static: Expect `x` to have statically defined `ndims`.
expect_ndims: Optional Python integer. If provided, assert that x has
number of dimensions equal to this.
expect_ndims_no_more_than: Optional Python integer. If provided, assert
that x has no more than this many dimensions.
expect_ndims_at_least: Optional Python integer. If provided, assert that x
has at least this many dimensions.
Returns:
ndims: A Python integer.
Raises:
ValueError: If any of the expectations above are violated.
"""
ndims = x.shape.ndims
if ndims is None:
shape_const = tf.get_static_value(tf.shape(input=x))
if shape_const is not None:
ndims = shape_const.ndim
if ndims is None:
if expect_static:
raise ValueError(
'Expected argument `x` to have statically defined `ndims`. Found: ' %
x)
return
if expect_ndims is not None:
ndims_message = ('Expected argument `x` to have ndims %s. Found tensor %s'
% (expect_ndims, x))
if ndims != expect_ndims:
raise ValueError(ndims_message)
if expect_ndims_at_least is not None:
ndims_at_least_message = (
'Expected argument `x` to have ndims >= %d. Found tensor %s' %
(expect_ndims_at_least, x))
if ndims < expect_ndims_at_least:
raise ValueError(ndims_at_least_message)
if expect_ndims_no_more_than is not None:
ndims_no_more_than_message = (
'Expected argument `x` to have ndims <= %d. Found tensor %s' %
(expect_ndims_no_more_than, x))
if ndims > expect_ndims_no_more_than:
raise ValueError(ndims_no_more_than_message)
return ndims | [
"def",
"_get_static_ndims",
"(",
"x",
",",
"expect_static",
"=",
"False",
",",
"expect_ndims",
"=",
"None",
",",
"expect_ndims_no_more_than",
"=",
"None",
",",
"expect_ndims_at_least",
"=",
"None",
")",
":",
"ndims",
"=",
"x",
".",
"shape",
".",
"ndims",
"if... | Get static number of dimensions and assert that some expectations are met.
This function returns the number of dimensions 'ndims' of x, as a Python int.
The optional expect arguments are used to check the ndims of x, but this is
only done if the static ndims of x is not None.
Args:
x: A Tensor.
expect_static: Expect `x` to have statically defined `ndims`.
expect_ndims: Optional Python integer. If provided, assert that x has
number of dimensions equal to this.
expect_ndims_no_more_than: Optional Python integer. If provided, assert
that x has no more than this many dimensions.
expect_ndims_at_least: Optional Python integer. If provided, assert that x
has at least this many dimensions.
Returns:
ndims: A Python integer.
Raises:
ValueError: If any of the expectations above are violated. | [
"Get",
"static",
"number",
"of",
"dimensions",
"and",
"assert",
"that",
"some",
"expectations",
"are",
"met",
"."
] | python | test |
KelSolaar/Umbra | umbra/ui/models.py | https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/ui/models.py#L430-L449 | def index(self, row, column=0, parent=QModelIndex()):
"""
Reimplements the :meth:`QAbstractItemModel.index` method.
:param row: Row.
:type row: int
:param column: Column.
:type column: int
:param parent: Parent.
:type parent: QModelIndex
:return: Index.
:rtype: QModelIndex
"""
parent_node = self.get_node(parent)
child = parent_node.child(row)
if child:
return self.createIndex(row, column, child)
else:
return QModelIndex() | [
"def",
"index",
"(",
"self",
",",
"row",
",",
"column",
"=",
"0",
",",
"parent",
"=",
"QModelIndex",
"(",
")",
")",
":",
"parent_node",
"=",
"self",
".",
"get_node",
"(",
"parent",
")",
"child",
"=",
"parent_node",
".",
"child",
"(",
"row",
")",
"i... | Reimplements the :meth:`QAbstractItemModel.index` method.
:param row: Row.
:type row: int
:param column: Column.
:type column: int
:param parent: Parent.
:type parent: QModelIndex
:return: Index.
:rtype: QModelIndex | [
"Reimplements",
"the",
":",
"meth",
":",
"QAbstractItemModel",
".",
"index",
"method",
"."
] | python | train |
learningequality/ricecooker | ricecooker/classes/files.py | https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/classes/files.py#L561-L573 | def is_youtube_subtitle_file_supported_language(language):
"""
Check if the language code `language` (string) is a valid language code in the
internal language id format `{primary_code}` or `{primary_code}-{subcode}`
ot alternatively if it s YouTube language code that can be mapped to one of
the languages in the internal represention.
"""
language_obj = _get_language_with_alpha2_fallback(language)
if language_obj is None:
config.LOGGER.warning("Found unsupported language code {}".format(language))
return False
else:
return True | [
"def",
"is_youtube_subtitle_file_supported_language",
"(",
"language",
")",
":",
"language_obj",
"=",
"_get_language_with_alpha2_fallback",
"(",
"language",
")",
"if",
"language_obj",
"is",
"None",
":",
"config",
".",
"LOGGER",
".",
"warning",
"(",
"\"Found unsupported ... | Check if the language code `language` (string) is a valid language code in the
internal language id format `{primary_code}` or `{primary_code}-{subcode}`
ot alternatively if it s YouTube language code that can be mapped to one of
the languages in the internal represention. | [
"Check",
"if",
"the",
"language",
"code",
"language",
"(",
"string",
")",
"is",
"a",
"valid",
"language",
"code",
"in",
"the",
"internal",
"language",
"id",
"format",
"{",
"primary_code",
"}",
"or",
"{",
"primary_code",
"}",
"-",
"{",
"subcode",
"}",
"ot... | python | train |
mikhaildubov/AST-text-analysis | east/asts/easa.py | https://github.com/mikhaildubov/AST-text-analysis/blob/055ad8d2492c100bbbaa25309ec1074bdf1dfaa5/east/asts/easa.py#L247-L266 | def _compute_lcptab(self, string, suftab):
"""Computes the LCP array in O(n) based on the input string & its suffix array.
Kasai et al. (2001).
"""
n = len(suftab)
rank = [0] * n
for i in xrange(n):
rank[suftab[i]] = i
lcptab = np.zeros(n, dtype=np.int)
h = 0
for i in xrange(n):
if rank[i] >= 1:
j = suftab[rank[i] - 1]
while string[i + h] == string[j + h]:
h += 1
lcptab[rank[i]] = h
if h > 0:
h -= 1
return lcptab | [
"def",
"_compute_lcptab",
"(",
"self",
",",
"string",
",",
"suftab",
")",
":",
"n",
"=",
"len",
"(",
"suftab",
")",
"rank",
"=",
"[",
"0",
"]",
"*",
"n",
"for",
"i",
"in",
"xrange",
"(",
"n",
")",
":",
"rank",
"[",
"suftab",
"[",
"i",
"]",
"]... | Computes the LCP array in O(n) based on the input string & its suffix array.
Kasai et al. (2001). | [
"Computes",
"the",
"LCP",
"array",
"in",
"O",
"(",
"n",
")",
"based",
"on",
"the",
"input",
"string",
"&",
"its",
"suffix",
"array",
"."
] | python | train |
ivelum/graphql-py | graphql/parser.py | https://github.com/ivelum/graphql-py/blob/72baf16d838e82349ee5e8d8f8971ce11cfcedf9/graphql/parser.py#L213-L217 | def p_field_optional1_2(self, p):
"""
field : alias name directives selection_set
"""
p[0] = Field(name=p[2], alias=p[1], directives=p[3], selections=p[5]) | [
"def",
"p_field_optional1_2",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"Field",
"(",
"name",
"=",
"p",
"[",
"2",
"]",
",",
"alias",
"=",
"p",
"[",
"1",
"]",
",",
"directives",
"=",
"p",
"[",
"3",
"]",
",",
"selections",
"=",
... | field : alias name directives selection_set | [
"field",
":",
"alias",
"name",
"directives",
"selection_set"
] | python | train |
splunk/splunk-sdk-python | examples/analytics/bottle.py | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/analytics/bottle.py#L1076-L1108 | def set_cookie(self, key, value, secret=None, **kargs):
''' Add a cookie or overwrite an old one. If the `secret` parameter is
set, create a `Signed Cookie` (described below).
:param key: the name of the cookie.
:param value: the value of the cookie.
:param secret: required for signed cookies. (default: None)
:param max_age: maximum age in seconds. (default: None)
:param expires: a datetime object or UNIX timestamp. (defaut: None)
:param domain: the domain that is allowed to read the cookie.
(default: current domain)
:param path: limits the cookie to a given path (default: /)
If neither `expires` nor `max_age` are set (default), the cookie
lasts only as long as the browser is not closed.
Signed cookies may store any pickle-able object and are
cryptographically signed to prevent manipulation. Keep in mind that
cookies are limited to 4kb in most browsers.
Warning: Signed cookies are not encrypted (the client can still see
the content) and not copy-protected (the client can restore an old
cookie). The main intention is to make pickling and unpickling
save, not to store secret information at client side.
'''
if secret:
value = touni(cookie_encode((key, value), secret))
elif not isinstance(value, six.string_types):
raise TypeError('Secret missing for non-string Cookie.')
self.COOKIES[key] = value
for k, v in six.iteritems(kargs):
self.COOKIES[key][k.replace('_', '-')] = v | [
"def",
"set_cookie",
"(",
"self",
",",
"key",
",",
"value",
",",
"secret",
"=",
"None",
",",
"*",
"*",
"kargs",
")",
":",
"if",
"secret",
":",
"value",
"=",
"touni",
"(",
"cookie_encode",
"(",
"(",
"key",
",",
"value",
")",
",",
"secret",
")",
")... | Add a cookie or overwrite an old one. If the `secret` parameter is
set, create a `Signed Cookie` (described below).
:param key: the name of the cookie.
:param value: the value of the cookie.
:param secret: required for signed cookies. (default: None)
:param max_age: maximum age in seconds. (default: None)
:param expires: a datetime object or UNIX timestamp. (defaut: None)
:param domain: the domain that is allowed to read the cookie.
(default: current domain)
:param path: limits the cookie to a given path (default: /)
If neither `expires` nor `max_age` are set (default), the cookie
lasts only as long as the browser is not closed.
Signed cookies may store any pickle-able object and are
cryptographically signed to prevent manipulation. Keep in mind that
cookies are limited to 4kb in most browsers.
Warning: Signed cookies are not encrypted (the client can still see
the content) and not copy-protected (the client can restore an old
cookie). The main intention is to make pickling and unpickling
save, not to store secret information at client side. | [
"Add",
"a",
"cookie",
"or",
"overwrite",
"an",
"old",
"one",
".",
"If",
"the",
"secret",
"parameter",
"is",
"set",
"create",
"a",
"Signed",
"Cookie",
"(",
"described",
"below",
")",
"."
] | python | train |
GoogleCloudPlatform/google-cloud-datastore | python/googledatastore/connection.py | https://github.com/GoogleCloudPlatform/google-cloud-datastore/blob/a23940d0634d7f537faf01ad9e60598046bcb40a/python/googledatastore/connection.py#L174-L204 | def _call_method(self, method, req, resp_class):
"""_call_method call the given RPC method over HTTP.
It uses the given protobuf message request as the payload and
returns the deserialized protobuf message response.
Args:
method: RPC method name to be called.
req: protobuf message for the RPC request.
resp_class: protobuf message class for the RPC response.
Returns:
Deserialized resp_class protobuf message instance.
Raises:
RPCError: The rpc method call failed.
"""
payload = req.SerializeToString()
headers = {
'Content-Type': 'application/x-protobuf',
'Content-Length': str(len(payload)),
'X-Goog-Api-Format-Version': '2'
}
response, content = self._http.request(
'%s:%s' % (self._url, method),
method='POST', body=payload, headers=headers)
if response.status != 200:
raise _make_rpc_error(method, response, content)
resp = resp_class()
resp.ParseFromString(content)
return resp | [
"def",
"_call_method",
"(",
"self",
",",
"method",
",",
"req",
",",
"resp_class",
")",
":",
"payload",
"=",
"req",
".",
"SerializeToString",
"(",
")",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/x-protobuf'",
",",
"'Content-Length'",
":",
"str",
... | _call_method call the given RPC method over HTTP.
It uses the given protobuf message request as the payload and
returns the deserialized protobuf message response.
Args:
method: RPC method name to be called.
req: protobuf message for the RPC request.
resp_class: protobuf message class for the RPC response.
Returns:
Deserialized resp_class protobuf message instance.
Raises:
RPCError: The rpc method call failed. | [
"_call_method",
"call",
"the",
"given",
"RPC",
"method",
"over",
"HTTP",
"."
] | python | train |
kubernetes-client/python | kubernetes/client/apis/rbac_authorization_v1_api.py | https://github.com/kubernetes-client/python/blob/5e512ff564c244c50cab780d821542ed56aa965a/kubernetes/client/apis/rbac_authorization_v1_api.py#L1349-L1375 | def delete_namespaced_role_binding(self, name, namespace, **kwargs):
"""
delete a RoleBinding
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_namespaced_role_binding(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the RoleBinding (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param V1DeleteOptions body:
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.delete_namespaced_role_binding_with_http_info(name, namespace, **kwargs)
else:
(data) = self.delete_namespaced_role_binding_with_http_info(name, namespace, **kwargs)
return data | [
"def",
"delete_namespaced_role_binding",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
... | delete a RoleBinding
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_namespaced_role_binding(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the RoleBinding (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param V1DeleteOptions body:
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:return: V1Status
If the method is called asynchronously,
returns the request thread. | [
"delete",
"a",
"RoleBinding",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"pass",
"async_req",
"=",
"True",
">>>",
"thread",
"=",
"api",
".",
"delete... | python | train |
molmod/molmod | molmod/randomize.py | https://github.com/molmod/molmod/blob/a7b5b4364ed514ad4c465856c05b5eda1cb561e0/molmod/randomize.py#L402-L468 | def random_dimer(molecule0, molecule1, thresholds, shoot_max):
"""Create a random dimer.
molecule0 and molecule1 are placed in one reference frame at random
relative positions. Interatomic distances are above the thresholds.
Initially a dimer is created where one interatomic distance approximates
the threshold value. Then the molecules are given an additional
separation in the range [0, shoot_max].
thresholds has the following format:
{frozenset([atom_number1, atom_number2]): distance}
"""
# apply a random rotation to molecule1
center = np.zeros(3, float)
angle = np.random.uniform(0, 2*np.pi)
axis = random_unit()
rotation = Complete.about_axis(center, angle, axis)
cor1 = np.dot(molecule1.coordinates, rotation.r)
# select a random atom in each molecule
atom0 = np.random.randint(len(molecule0.numbers))
atom1 = np.random.randint(len(molecule1.numbers))
# define a translation of molecule1 that brings both atoms in overlap
delta = molecule0.coordinates[atom0] - cor1[atom1]
cor1 += delta
# define a random direction
direction = random_unit()
cor1 += 1*direction
# move molecule1 along this direction until all intermolecular atomic
# distances are above the threshold values
threshold_mat = np.zeros((len(molecule0.numbers), len(molecule1.numbers)), float)
distance_mat = np.zeros((len(molecule0.numbers), len(molecule1.numbers)), float)
for i1, n1 in enumerate(molecule0.numbers):
for i2, n2 in enumerate(molecule1.numbers):
threshold = thresholds.get(frozenset([n1, n2]))
threshold_mat[i1, i2] = threshold**2
while True:
cor1 += 0.1*direction
distance_mat[:] = 0
for i in 0, 1, 2:
distance_mat += np.subtract.outer(molecule0.coordinates[:, i], cor1[:, i])**2
if (distance_mat > threshold_mat).all():
break
# translate over a random distance [0, shoot] along the same direction
# (if necessary repeat until no overlap is found)
while True:
cor1 += direction*np.random.uniform(0, shoot_max)
distance_mat[:] = 0
for i in 0, 1, 2:
distance_mat += np.subtract.outer(molecule0.coordinates[:, i], cor1[:, i])**2
if (distance_mat > threshold_mat).all():
break
# done
dimer = Molecule(
np.concatenate([molecule0.numbers, molecule1.numbers]),
np.concatenate([molecule0.coordinates, cor1])
)
dimer.direction = direction
dimer.atom0 = atom0
dimer.atom1 = atom1
return dimer | [
"def",
"random_dimer",
"(",
"molecule0",
",",
"molecule1",
",",
"thresholds",
",",
"shoot_max",
")",
":",
"# apply a random rotation to molecule1",
"center",
"=",
"np",
".",
"zeros",
"(",
"3",
",",
"float",
")",
"angle",
"=",
"np",
".",
"random",
".",
"unifo... | Create a random dimer.
molecule0 and molecule1 are placed in one reference frame at random
relative positions. Interatomic distances are above the thresholds.
Initially a dimer is created where one interatomic distance approximates
the threshold value. Then the molecules are given an additional
separation in the range [0, shoot_max].
thresholds has the following format:
{frozenset([atom_number1, atom_number2]): distance} | [
"Create",
"a",
"random",
"dimer",
"."
] | python | train |
bxlab/bx-python | lib/bx_extras/stats.py | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1685-L1696 | def lsumdiffsquared(x,y):
"""
Takes pairwise differences of the values in lists x and y, squares
these differences, and returns the sum of these squares.
Usage: lsumdiffsquared(x,y)
Returns: sum[(x[i]-y[i])**2]
"""
sds = 0
for i in range(len(x)):
sds = sds + (x[i]-y[i])**2
return sds | [
"def",
"lsumdiffsquared",
"(",
"x",
",",
"y",
")",
":",
"sds",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"x",
")",
")",
":",
"sds",
"=",
"sds",
"+",
"(",
"x",
"[",
"i",
"]",
"-",
"y",
"[",
"i",
"]",
")",
"**",
"2",
"return",
... | Takes pairwise differences of the values in lists x and y, squares
these differences, and returns the sum of these squares.
Usage: lsumdiffsquared(x,y)
Returns: sum[(x[i]-y[i])**2] | [
"Takes",
"pairwise",
"differences",
"of",
"the",
"values",
"in",
"lists",
"x",
"and",
"y",
"squares",
"these",
"differences",
"and",
"returns",
"the",
"sum",
"of",
"these",
"squares",
"."
] | python | train |
doanguyen/lasotuvi | lasotuvi/AmDuong.py | https://github.com/doanguyen/lasotuvi/blob/98383a3056f0a0633d6937d364c37eb788661c0d/lasotuvi/AmDuong.py#L452-L475 | def timTuVi(cuc, ngaySinhAmLich):
"""Tìm vị trí của sao Tử vi
Args:
cuc (TYPE): Description
ngaySinhAmLich (TYPE): Description
Returns:
TYPE: Description
Raises:
Exception: Description
"""
cungDan = 3 # Vị trí cung Dần ban đầu là 3
cucBanDau = cuc
if cuc not in [2, 3, 4, 5, 6]: # Tránh trường hợp infinite loop
raise Exception("Số cục phải là 2, 3, 4, 5, 6")
while cuc < ngaySinhAmLich:
cuc += cucBanDau
cungDan += 1 # Dịch vị trí cung Dần
saiLech = cuc - ngaySinhAmLich
if saiLech % 2 is 1:
saiLech = -saiLech # Nếu sai lệch là chẵn thì tiến, lẻ thì lùi
return dichCung(cungDan, saiLech) | [
"def",
"timTuVi",
"(",
"cuc",
",",
"ngaySinhAmLich",
")",
":",
"cungDan",
"=",
"3",
"# Vị trí cung Dần ban đầu là 3",
"cucBanDau",
"=",
"cuc",
"if",
"cuc",
"not",
"in",
"[",
"2",
",",
"3",
",",
"4",
",",
"5",
",",
"6",
"]",
":",
"# Tránh trường hợp infin... | Tìm vị trí của sao Tử vi
Args:
cuc (TYPE): Description
ngaySinhAmLich (TYPE): Description
Returns:
TYPE: Description
Raises:
Exception: Description | [
"Tìm",
"vị",
"trí",
"của",
"sao",
"Tử",
"vi"
] | python | train |
meng89/ipodshuffle | ipodshuffle/db/itunessd.py | https://github.com/meng89/ipodshuffle/blob/c9093dbb5cdac609376ebd3b4ef1b0fc58107d96/ipodshuffle/db/itunessd.py#L418-L516 | def dics_to_itunessd(header_dic, tracks_dics, playlists_dics_and_indexes):
"""
:param header_dic: dic of header_table
:param tracks_dics: list of all track_table's dics
:param playlists_dics_and_indexes: list of all playlists and all their track's indexes
:return: the whole iTunesSD bytes data
"""
############################################
# header
######
header_dic['length'] = get_table_size(header_table)
header_dic['number_of_tracks'] = len(tracks_dics)
header_dic['number_of_playlists'] = len(playlists_dics_and_indexes)
header_dic['number_of_tracks2'] = 0
header_part_size = get_table_size(header_table)
####################################################################################################################
# tracks
##########
# Chunk of header
tracks_header_dic = {
'length': get_table_size(tracks_header_table) + 4 * len(tracks_dics),
'number_of_tracks': len(tracks_dics)
}
tracks_header_chunk = dic_to_chunk(tracks_header_dic, tracks_header_table)
# Chunk of all tracks
[track_dic.update({'length': get_table_size(track_table)}) for track_dic in tracks_dics]
_tracks_chunks = [dic_to_chunk(dic, track_table) for dic in tracks_dics]
all_tracks_chunck = b''.join(_tracks_chunks)
# Chunk of offsets
_length_before_tracks_offsets = header_part_size + len(tracks_header_chunk)
tracks_offsets_chunck = get_offsets_chunk(_length_before_tracks_offsets, _tracks_chunks)
# Put chunks together
track_part_chunk = tracks_header_chunk + tracks_offsets_chunck + all_tracks_chunck
####################################################################################################################
# playlists
#############
# Chunk of header
_playlists_dics = [playlist_indexes[0] for playlist_indexes in playlists_dics_and_indexes]
_types = [playlist_dic['type'] for playlist_dic in _playlists_dics]
playlists_header_dic = {
'length': get_table_size(playlists_header_table) + 4 * len(playlists_dics_and_indexes),
'number_of_all_playlists': len(_types),
'flag1': 0xffffffff if _types.count(NORMAL) == 0 else 1,
'number_of_normal_playlists': _types.count(NORMAL),
'flag2': 0xffffffff if _types.count(AUDIOBOOK) == 0 else (_types.count(MASTER) + _types.count(NORMAL) +
_types.count(PODCAST)),
'number_of_audiobook_playlists': _types.count(AUDIOBOOK),
'flag3': 0xffffffff if _types.count(PODCAST) == 0 else _types.count(1) + _types.count(NORMAL),
'number_of_podcast_playlists': _types.count(PODCAST)
}
playlists_header_chunk = dic_to_chunk(playlists_header_dic, playlists_header_table)
# Chunk of all playlists
_playlists_chunks = []
for playlist_header_dic, indexes in playlists_dics_and_indexes:
dic = playlist_header_dic.copy()
dic['length'] = get_table_size(playlist_header_table) + 4 * len(indexes)
dic['number_of_all_track'] = len(indexes)
dic['number_of_normal_track'] = len(indexes) if dic['type'] in (1, 2) else 0
if dic['type'] == MASTER:
header_dic['number_of_tracks2'] = len(indexes)
_playlist_header_chunk = dic_to_chunk(dic, playlist_header_table)
_indexes_chunk = b''.join([i.to_bytes(4, 'little') for i in indexes])
playlist_chunk = _playlist_header_chunk + _indexes_chunk
_playlists_chunks.append(playlist_chunk)
all_playlists_chunk = b''.join(_playlists_chunks)
# Chunk of offsets
_length_before_playlists_offsets = header_part_size + len(track_part_chunk) + len(playlists_header_chunk)
playlists_offsets_chunk = get_offsets_chunk(_length_before_playlists_offsets, _playlists_chunks)
# Put chunks together
playlists_part_chunk = playlists_header_chunk + playlists_offsets_chunk + all_playlists_chunk
########################################################################
header_dic['tracks_header_offset'] = header_part_size
header_dic['playlists_header_offset'] = header_part_size + len(track_part_chunk)
header_part_chunk = dic_to_chunk(header_dic, header_table)
########################################################################
itunessd = header_part_chunk + track_part_chunk + playlists_part_chunk
return itunessd | [
"def",
"dics_to_itunessd",
"(",
"header_dic",
",",
"tracks_dics",
",",
"playlists_dics_and_indexes",
")",
":",
"############################################",
"# header",
"######",
"header_dic",
"[",
"'length'",
"]",
"=",
"get_table_size",
"(",
"header_table",
")",
"heade... | :param header_dic: dic of header_table
:param tracks_dics: list of all track_table's dics
:param playlists_dics_and_indexes: list of all playlists and all their track's indexes
:return: the whole iTunesSD bytes data | [
":",
"param",
"header_dic",
":",
"dic",
"of",
"header_table",
":",
"param",
"tracks_dics",
":",
"list",
"of",
"all",
"track_table",
"s",
"dics",
":",
"param",
"playlists_dics_and_indexes",
":",
"list",
"of",
"all",
"playlists",
"and",
"all",
"their",
"track",
... | python | train |
fprimex/zdesk | zdesk/zdesk_api.py | https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L1447-L1454 | def help_center_article_comment_votes(self, article_id, comment_id, locale=None, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/votes#list-votes"
api_path = "/api/v2/help_center/articles/{article_id}/comments/{comment_id}/votes.json"
api_path = api_path.format(article_id=article_id, comment_id=comment_id)
if locale:
api_opt_path = "/api/v2/help_center/{locale}/articles/{article_id}/comments/{comment_id}/votes.json"
api_path = api_opt_path.format(article_id=article_id, comment_id=comment_id, locale=locale)
return self.call(api_path, **kwargs) | [
"def",
"help_center_article_comment_votes",
"(",
"self",
",",
"article_id",
",",
"comment_id",
",",
"locale",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/help_center/articles/{article_id}/comments/{comment_id}/votes.json\"",
"api_path",
"="... | https://developer.zendesk.com/rest_api/docs/help_center/votes#list-votes | [
"https",
":",
"//",
"developer",
".",
"zendesk",
".",
"com",
"/",
"rest_api",
"/",
"docs",
"/",
"help_center",
"/",
"votes#list",
"-",
"votes"
] | python | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/targets.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/targets.py#L169-L188 | def main_target_usage_requirements (self, specification, project):
""" Returns the use requirement to use when declaraing a main target,
which are obtained by
- translating all specified property paths, and
- adding project's usage requirements
specification: Use-properties explicitly specified for a main target
project: Project where the main target is to be declared
"""
assert is_iterable_typed(specification, basestring)
assert isinstance(project, ProjectTarget)
project_usage_requirements = project.get ('usage-requirements')
# We don't use 'refine-from-user-input' because I'm not sure if:
# - removing of parent's usage requirements makes sense
# - refining of usage requirements is not needed, since usage requirements
# are always free.
usage_requirements = property_set.create_from_user_input(
specification, project.project_module(), project.get("location"))
return project_usage_requirements.add (usage_requirements) | [
"def",
"main_target_usage_requirements",
"(",
"self",
",",
"specification",
",",
"project",
")",
":",
"assert",
"is_iterable_typed",
"(",
"specification",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"project",
",",
"ProjectTarget",
")",
"project_usage_require... | Returns the use requirement to use when declaraing a main target,
which are obtained by
- translating all specified property paths, and
- adding project's usage requirements
specification: Use-properties explicitly specified for a main target
project: Project where the main target is to be declared | [
"Returns",
"the",
"use",
"requirement",
"to",
"use",
"when",
"declaraing",
"a",
"main",
"target",
"which",
"are",
"obtained",
"by",
"-",
"translating",
"all",
"specified",
"property",
"paths",
"and",
"-",
"adding",
"project",
"s",
"usage",
"requirements",
"spe... | python | train |
RudolfCardinal/pythonlib | cardinal_pythonlib/fileops.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/fileops.py#L270-L276 | def rmglob(pattern: str) -> None:
"""
Deletes all files whose filename matches the glob ``pattern`` (via
:func:`glob.glob`).
"""
for f in glob.glob(pattern):
os.remove(f) | [
"def",
"rmglob",
"(",
"pattern",
":",
"str",
")",
"->",
"None",
":",
"for",
"f",
"in",
"glob",
".",
"glob",
"(",
"pattern",
")",
":",
"os",
".",
"remove",
"(",
"f",
")"
] | Deletes all files whose filename matches the glob ``pattern`` (via
:func:`glob.glob`). | [
"Deletes",
"all",
"files",
"whose",
"filename",
"matches",
"the",
"glob",
"pattern",
"(",
"via",
":",
"func",
":",
"glob",
".",
"glob",
")",
"."
] | python | train |
ScienceLogic/amiuploader | amiimporter/AWSUtilities.py | https://github.com/ScienceLogic/amiuploader/blob/c36c247b2226107b38571cbc6119118b1fe07182/amiimporter/AWSUtilities.py#L319-L337 | def import_vmdk(self):
"""
All actions necessary to import vmdk (calls s3 upload, and import to aws ec2)
:param vmdk_location: location of vmdk to import. Can be provided as a string, or the result output of fabric
execution
:return:
"""
# Set the inital upload to be the first region in the list
first_upload_region = self.aws_regions[0]
print "Initial AMI will be created in: {}".format(first_upload_region)
self.upload_to_s3(region=first_upload_region)
# If the upload was successful, the name to reference for import is now the basename
description = "AMI upload of: {}".format(os.path.basename(self.upload_file))
temp_fd, file_location = self.create_config_file(os.path.basename(self.upload_file), description)
import_id = self.run_ec2_import(file_location, description, first_upload_region)
self.wait_for_import_to_complete(import_id)
self.rename_image(import_id, self.ami_name, source_region=first_upload_region)
return import_id | [
"def",
"import_vmdk",
"(",
"self",
")",
":",
"# Set the inital upload to be the first region in the list",
"first_upload_region",
"=",
"self",
".",
"aws_regions",
"[",
"0",
"]",
"print",
"\"Initial AMI will be created in: {}\"",
".",
"format",
"(",
"first_upload_region",
")... | All actions necessary to import vmdk (calls s3 upload, and import to aws ec2)
:param vmdk_location: location of vmdk to import. Can be provided as a string, or the result output of fabric
execution
:return: | [
"All",
"actions",
"necessary",
"to",
"import",
"vmdk",
"(",
"calls",
"s3",
"upload",
"and",
"import",
"to",
"aws",
"ec2",
")",
":",
"param",
"vmdk_location",
":",
"location",
"of",
"vmdk",
"to",
"import",
".",
"Can",
"be",
"provided",
"as",
"a",
"string"... | python | train |
esterhui/pypu | pypu/service_facebook.py | https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/service_facebook.py#L93-L101 | def Upload(self,directory,filename):
"""Uploads/Updates/Replaces files"""
if self._isMediaFile(filename):
return self._upload_media(directory,filename)
elif self._isConfigFile(filename):
return self._update_config(directory,filename)
print "Not handled!"
return False | [
"def",
"Upload",
"(",
"self",
",",
"directory",
",",
"filename",
")",
":",
"if",
"self",
".",
"_isMediaFile",
"(",
"filename",
")",
":",
"return",
"self",
".",
"_upload_media",
"(",
"directory",
",",
"filename",
")",
"elif",
"self",
".",
"_isConfigFile",
... | Uploads/Updates/Replaces files | [
"Uploads",
"/",
"Updates",
"/",
"Replaces",
"files"
] | python | train |
data61/clkhash | clkhash/cli.py | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/cli.py#L56-L92 | def hash(pii_csv, keys, schema, clk_json, quiet, no_header, check_header, validate):
"""Process data to create CLKs
Given a file containing CSV data as PII_CSV, and a JSON
document defining the expected schema, verify the schema, then
hash the data to create CLKs writing them as JSON to CLK_JSON. Note the CSV
file should contain a header row - however this row is not used
by this tool.
It is important that the keys are only known by the two data providers. Two words should be provided. For example:
$clkutil hash pii.csv horse staple pii-schema.json clk.json
Use "-" for CLK_JSON to write JSON to stdout.
"""
schema_object = clkhash.schema.from_json_file(schema_file=schema)
header = True
if not check_header:
header = 'ignore'
if no_header:
header = False
try:
clk_data = clk.generate_clk_from_csv(
pii_csv, keys, schema_object,
validate=validate,
header=header,
progress_bar=not quiet)
except (validate_data.EntryError, validate_data.FormatError) as e:
msg, = e.args
log(msg)
log('Hashing failed.')
else:
json.dump({'clks': clk_data}, clk_json)
if hasattr(clk_json, 'name'):
log("CLK data written to {}".format(clk_json.name)) | [
"def",
"hash",
"(",
"pii_csv",
",",
"keys",
",",
"schema",
",",
"clk_json",
",",
"quiet",
",",
"no_header",
",",
"check_header",
",",
"validate",
")",
":",
"schema_object",
"=",
"clkhash",
".",
"schema",
".",
"from_json_file",
"(",
"schema_file",
"=",
"sch... | Process data to create CLKs
Given a file containing CSV data as PII_CSV, and a JSON
document defining the expected schema, verify the schema, then
hash the data to create CLKs writing them as JSON to CLK_JSON. Note the CSV
file should contain a header row - however this row is not used
by this tool.
It is important that the keys are only known by the two data providers. Two words should be provided. For example:
$clkutil hash pii.csv horse staple pii-schema.json clk.json
Use "-" for CLK_JSON to write JSON to stdout. | [
"Process",
"data",
"to",
"create",
"CLKs"
] | python | train |
jbeluch/xbmcswift2 | xbmcswift2/cli/console.py | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/cli/console.py#L73-L91 | 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 interactive views
return item
except ValueError:
# Passed something that cound't be converted with int()
choice = raw_input('You entered a non-integer. Choice must be an'
' integer or "q": ')
except IndexError:
# Passed an integer that was out of range of the list of urls
choice = raw_input('You entered an invalid integer. Choice must be'
' from above url list or "q": ')
return None | [
"def",
"get_user_choice",
"(",
"items",
")",
":",
"choice",
"=",
"raw_input",
"(",
"'Choose an item or \"q\" to quit: '",
")",
"while",
"choice",
"!=",
"'q'",
":",
"try",
":",
"item",
"=",
"items",
"[",
"int",
"(",
"choice",
")",
"]",
"print",
"# Blank line ... | Returns the selected item from provided items or None if 'q' was
entered for quit. | [
"Returns",
"the",
"selected",
"item",
"from",
"provided",
"items",
"or",
"None",
"if",
"q",
"was",
"entered",
"for",
"quit",
"."
] | python | train |
RI-imaging/qpformat | qpformat/file_formats/series_zip_tif_phasics.py | https://github.com/RI-imaging/qpformat/blob/364e29d7d9e8b9f1d7a4a25c753d1baf9d73d5eb/qpformat/file_formats/series_zip_tif_phasics.py#L55-L59 | def files(self):
"""List of Phasics tif file names in the input zip file"""
if self._files is None:
self._files = SeriesZipTifPhasics._index_files(self.path)
return self._files | [
"def",
"files",
"(",
"self",
")",
":",
"if",
"self",
".",
"_files",
"is",
"None",
":",
"self",
".",
"_files",
"=",
"SeriesZipTifPhasics",
".",
"_index_files",
"(",
"self",
".",
"path",
")",
"return",
"self",
".",
"_files"
] | List of Phasics tif file names in the input zip file | [
"List",
"of",
"Phasics",
"tif",
"file",
"names",
"in",
"the",
"input",
"zip",
"file"
] | python | train |
indranilsinharoy/pyzos | pyzos/zos.py | https://github.com/indranilsinharoy/pyzos/blob/da6bf3296b0154ccee44ad9a4286055ae031ecc7/pyzos/zos.py#L53-L65 | def _delete_file(fileName, n=10):
"""Cleanly deletes a file in `n` attempts (if necessary)"""
status = False
count = 0
while not status and count < n:
try:
_os.remove(fileName)
except OSError:
count += 1
_time.sleep(0.2)
else:
status = True
return status | [
"def",
"_delete_file",
"(",
"fileName",
",",
"n",
"=",
"10",
")",
":",
"status",
"=",
"False",
"count",
"=",
"0",
"while",
"not",
"status",
"and",
"count",
"<",
"n",
":",
"try",
":",
"_os",
".",
"remove",
"(",
"fileName",
")",
"except",
"OSError",
... | Cleanly deletes a file in `n` attempts (if necessary) | [
"Cleanly",
"deletes",
"a",
"file",
"in",
"n",
"attempts",
"(",
"if",
"necessary",
")"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.