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 |
|---|---|---|---|---|---|---|---|---|
mpdavis/python-jose | jose/jws.py | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/jws.py#L19-L52 | def sign(payload, key, headers=None, algorithm=ALGORITHMS.HS256):
"""Signs a claims set and returns a JWS string.
Args:
payload (str): A string to sign
key (str or dict): The key to use for signing the claim set. Can be
individual JWK or JWK set.
headers (dict, optional): A ... | [
"def",
"sign",
"(",
"payload",
",",
"key",
",",
"headers",
"=",
"None",
",",
"algorithm",
"=",
"ALGORITHMS",
".",
"HS256",
")",
":",
"if",
"algorithm",
"not",
"in",
"ALGORITHMS",
".",
"SUPPORTED",
":",
"raise",
"JWSError",
"(",
"'Algorithm %s not supported.'... | Signs a claims set and returns a JWS string.
Args:
payload (str): A string to sign
key (str or dict): The key to use for signing the claim set. Can be
individual JWK or JWK set.
headers (dict, optional): A set of headers that will be added to
the default headers. An... | [
"Signs",
"a",
"claims",
"set",
"and",
"returns",
"a",
"JWS",
"string",
"."
] | python | train |
pricingassistant/mrq | mrq/utils.py | https://github.com/pricingassistant/mrq/blob/d0a5a34de9cba38afa94fb7c9e17f9b570b79a50/mrq/utils.py#L94-L101 | def memoize_single_argument(f):
""" Memoization decorator for a function taking a single argument """
class memodict(dict):
def __missing__(self, key):
ret = self[key] = f(key)
return ret
return memodict().__getitem__ | [
"def",
"memoize_single_argument",
"(",
"f",
")",
":",
"class",
"memodict",
"(",
"dict",
")",
":",
"def",
"__missing__",
"(",
"self",
",",
"key",
")",
":",
"ret",
"=",
"self",
"[",
"key",
"]",
"=",
"f",
"(",
"key",
")",
"return",
"ret",
"return",
"m... | Memoization decorator for a function taking a single argument | [
"Memoization",
"decorator",
"for",
"a",
"function",
"taking",
"a",
"single",
"argument"
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/psutil/_pslinux.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_pslinux.py#L551-L609 | def get_memory_maps(self):
"""Return process's mapped memory regions as a list of nameduples.
Fields are explained in 'man proc'; here is an updated (Apr 2012)
version: http://goo.gl/fmebo
"""
f = None
try:
f = open("/proc/%s/smaps" % self.pid)
fir... | [
"def",
"get_memory_maps",
"(",
"self",
")",
":",
"f",
"=",
"None",
"try",
":",
"f",
"=",
"open",
"(",
"\"/proc/%s/smaps\"",
"%",
"self",
".",
"pid",
")",
"first_line",
"=",
"f",
".",
"readline",
"(",
")",
"current_block",
"=",
"[",
"first_line",
"]",
... | Return process's mapped memory regions as a list of nameduples.
Fields are explained in 'man proc'; here is an updated (Apr 2012)
version: http://goo.gl/fmebo | [
"Return",
"process",
"s",
"mapped",
"memory",
"regions",
"as",
"a",
"list",
"of",
"nameduples",
".",
"Fields",
"are",
"explained",
"in",
"man",
"proc",
";",
"here",
"is",
"an",
"updated",
"(",
"Apr",
"2012",
")",
"version",
":",
"http",
":",
"//",
"goo... | python | test |
dpkp/kafka-python | kafka/protocol/parser.py | https://github.com/dpkp/kafka-python/blob/f6a8a38937688ea2cc5dc13d3d1039493be5c9b5/kafka/protocol/parser.py#L47-L72 | def send_request(self, request, correlation_id=None):
"""Encode and queue a kafka api request for sending.
Arguments:
request (object): An un-encoded kafka request.
correlation_id (int, optional): Optionally specify an ID to
correlate requests with responses. If ... | [
"def",
"send_request",
"(",
"self",
",",
"request",
",",
"correlation_id",
"=",
"None",
")",
":",
"log",
".",
"debug",
"(",
"'Sending request %s'",
",",
"request",
")",
"if",
"correlation_id",
"is",
"None",
":",
"correlation_id",
"=",
"self",
".",
"_next_cor... | Encode and queue a kafka api request for sending.
Arguments:
request (object): An un-encoded kafka request.
correlation_id (int, optional): Optionally specify an ID to
correlate requests with responses. If not provided, an ID will
be generated automatical... | [
"Encode",
"and",
"queue",
"a",
"kafka",
"api",
"request",
"for",
"sending",
"."
] | python | train |
zebpalmer/WeatherAlerts | weatheralerts/weather_alerts.py | https://github.com/zebpalmer/WeatherAlerts/blob/b99513571571fa0d65b90be883bb3bc000994027/weatheralerts/weather_alerts.py#L99-L116 | def event_state_counties(self):
"""DEPRECATED: this will be moved elsewhere or dropped in the near future, stop using it.
Return an event type and it's state(s) and counties (consolidated)"""
# FIXME: most of this logic should be moved to the alert instance and refactored
counties = ''
... | [
"def",
"event_state_counties",
"(",
"self",
")",
":",
"# FIXME: most of this logic should be moved to the alert instance and refactored",
"counties",
"=",
"''",
"state",
"=",
"''",
"for",
"alert",
"in",
"self",
".",
"_alerts",
":",
"locations",
"=",
"[",
"]",
"states"... | DEPRECATED: this will be moved elsewhere or dropped in the near future, stop using it.
Return an event type and it's state(s) and counties (consolidated) | [
"DEPRECATED",
":",
"this",
"will",
"be",
"moved",
"elsewhere",
"or",
"dropped",
"in",
"the",
"near",
"future",
"stop",
"using",
"it",
".",
"Return",
"an",
"event",
"type",
"and",
"it",
"s",
"state",
"(",
"s",
")",
"and",
"counties",
"(",
"consolidated",
... | python | train |
datasift/datasift-python | datasift/historics.py | https://github.com/datasift/datasift-python/blob/bfaca1a47501a18e11065ecf630d9c31df818f65/datasift/historics.py#L104-L117 | def delete(self, historics_id):
""" Delete one specified playback query. If the query is currently running, stop it.
status_code is set to 204 on success
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsdelete
:param historics_id: playbac... | [
"def",
"delete",
"(",
"self",
",",
"historics_id",
")",
":",
"return",
"self",
".",
"request",
".",
"post",
"(",
"'delete'",
",",
"data",
"=",
"dict",
"(",
"id",
"=",
"historics_id",
")",
")"
] | Delete one specified playback query. If the query is currently running, stop it.
status_code is set to 204 on success
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsdelete
:param historics_id: playback id of the query to delete
:typ... | [
"Delete",
"one",
"specified",
"playback",
"query",
".",
"If",
"the",
"query",
"is",
"currently",
"running",
"stop",
"it",
"."
] | python | train |
OLC-Bioinformatics/sipprverse | cgecore/utility.py | https://github.com/OLC-Bioinformatics/sipprverse/blob/d4f10cdf8e1a39dac0953db61c21c97efc6006de/cgecore/utility.py#L342-L358 | def load_json(json_object):
''' Load json from file or file name '''
content = None
if isinstance(json_object, str) and os.path.exists(json_object):
with open_(json_object) as f:
try:
content = json.load(f)
except Exception as e:
debug.log("Warning: Content of '%... | [
"def",
"load_json",
"(",
"json_object",
")",
":",
"content",
"=",
"None",
"if",
"isinstance",
"(",
"json_object",
",",
"str",
")",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"json_object",
")",
":",
"with",
"open_",
"(",
"json_object",
")",
"as",
"f... | Load json from file or file name | [
"Load",
"json",
"from",
"file",
"or",
"file",
"name"
] | python | train |
apache/incubator-heron | third_party/python/cpplint/cpplint.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L1534-L1542 | def FindNextMultiLineCommentStart(lines, lineix):
"""Find the beginning marker for a multiline comment."""
while lineix < len(lines):
if lines[lineix].strip().startswith('/*'):
# Only return this marker if the comment goes beyond this line
if lines[lineix].strip().find('*/', 2) < 0:
return l... | [
"def",
"FindNextMultiLineCommentStart",
"(",
"lines",
",",
"lineix",
")",
":",
"while",
"lineix",
"<",
"len",
"(",
"lines",
")",
":",
"if",
"lines",
"[",
"lineix",
"]",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"'/*'",
")",
":",
"# Only return this... | Find the beginning marker for a multiline comment. | [
"Find",
"the",
"beginning",
"marker",
"for",
"a",
"multiline",
"comment",
"."
] | python | valid |
waqasbhatti/astrobase | astrobase/lcfit/sinusoidal.py | https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcfit/sinusoidal.py#L63-L111 | def _fourier_func(fourierparams, phase, mags):
'''This returns a summed Fourier cosine series.
Parameters
----------
fourierparams : list
This MUST be a list of the following form like so::
[period,
epoch,
[amplitude_1, amplitude_2, amplitude_3, ..., ampl... | [
"def",
"_fourier_func",
"(",
"fourierparams",
",",
"phase",
",",
"mags",
")",
":",
"# figure out the order from the length of the Fourier param list",
"order",
"=",
"int",
"(",
"len",
"(",
"fourierparams",
")",
"/",
"2",
")",
"# get the amplitude and phase coefficients",
... | This returns a summed Fourier cosine series.
Parameters
----------
fourierparams : list
This MUST be a list of the following form like so::
[period,
epoch,
[amplitude_1, amplitude_2, amplitude_3, ..., amplitude_X],
[phase_1, phase_2, phase_3, ...... | [
"This",
"returns",
"a",
"summed",
"Fourier",
"cosine",
"series",
"."
] | python | valid |
mikekatz04/BOWIE | snr_calculator_folder/gwsnrcalc/utils/csnr.py | https://github.com/mikekatz04/BOWIE/blob/a941342a3536cb57c817a1643896d99a3f354a86/snr_calculator_folder/gwsnrcalc/utils/csnr.py#L21-L102 | def csnr(freqs, hc, hn, fmrg, fpeak, prefactor=1.0):
"""Calculate the SNR of a frequency domain waveform.
SNRCalculation is a function that takes waveforms (frequencies and hcs)
and a noise curve, and returns SNRs for all binary phases and the whole waveform.
Arguments:
freqs (1D or 2D array o... | [
"def",
"csnr",
"(",
"freqs",
",",
"hc",
",",
"hn",
",",
"fmrg",
",",
"fpeak",
",",
"prefactor",
"=",
"1.0",
")",
":",
"cfd",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
"if",
"'phen... | Calculate the SNR of a frequency domain waveform.
SNRCalculation is a function that takes waveforms (frequencies and hcs)
and a noise curve, and returns SNRs for all binary phases and the whole waveform.
Arguments:
freqs (1D or 2D array of floats): Frequencies corresponding to the waveforms.
... | [
"Calculate",
"the",
"SNR",
"of",
"a",
"frequency",
"domain",
"waveform",
"."
] | python | train |
hydpy-dev/hydpy | hydpy/core/masktools.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/masktools.py#L37-L43 | def array2mask(cls, array=None, **kwargs):
"""Create a new mask object based on the given |numpy.ndarray|
and return it."""
kwargs['dtype'] = bool
if array is None:
return numpy.ndarray.__new__(cls, 0, **kwargs)
return numpy.asarray(array, **kwargs).view(cls) | [
"def",
"array2mask",
"(",
"cls",
",",
"array",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'dtype'",
"]",
"=",
"bool",
"if",
"array",
"is",
"None",
":",
"return",
"numpy",
".",
"ndarray",
".",
"__new__",
"(",
"cls",
",",
"0",
... | Create a new mask object based on the given |numpy.ndarray|
and return it. | [
"Create",
"a",
"new",
"mask",
"object",
"based",
"on",
"the",
"given",
"|numpy",
".",
"ndarray|",
"and",
"return",
"it",
"."
] | python | train |
ThreatConnect-Inc/tcex | tcex/tcex_redis.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_redis.py#L88-L98 | def hset(self, key, value):
"""Create key/value pair in Redis.
Args:
key (string): The key to create in Redis.
value (any): The value to store in Redis.
Returns:
(string): The response from Redis.
"""
return self.r.hset(self.hash, key, value) | [
"def",
"hset",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"return",
"self",
".",
"r",
".",
"hset",
"(",
"self",
".",
"hash",
",",
"key",
",",
"value",
")"
] | Create key/value pair in Redis.
Args:
key (string): The key to create in Redis.
value (any): The value to store in Redis.
Returns:
(string): The response from Redis. | [
"Create",
"key",
"/",
"value",
"pair",
"in",
"Redis",
"."
] | python | train |
DerwenAI/pytextrank | pytextrank/pytextrank.py | https://github.com/DerwenAI/pytextrank/blob/181ea41375d29922eb96768cf6550e57a77a0c95/pytextrank/pytextrank.py#L496-L527 | def collect_phrases (sent, ranks, spacy_nlp):
"""
iterator for collecting the noun phrases
"""
tail = 0
last_idx = sent[0].idx - 1
phrase = []
while tail < len(sent):
w = sent[tail]
if (w.word_id > 0) and (w.root in ranks) and ((w.idx - last_idx) == 1):
# keep c... | [
"def",
"collect_phrases",
"(",
"sent",
",",
"ranks",
",",
"spacy_nlp",
")",
":",
"tail",
"=",
"0",
"last_idx",
"=",
"sent",
"[",
"0",
"]",
".",
"idx",
"-",
"1",
"phrase",
"=",
"[",
"]",
"while",
"tail",
"<",
"len",
"(",
"sent",
")",
":",
"w",
"... | iterator for collecting the noun phrases | [
"iterator",
"for",
"collecting",
"the",
"noun",
"phrases"
] | python | valid |
cosven/feeluown-core | fuocore/player.py | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/player.py#L188-L223 | def _get_good_song(self, base=0, random_=False, direction=1):
"""从播放列表中获取一首可以播放的歌曲
:param base: base index
:param random: random strategy or not
:param direction: forward if > 0 else backword
>>> pl = Playlist([1, 2, 3])
>>> pl._get_good_song()
1
>>> pl.... | [
"def",
"_get_good_song",
"(",
"self",
",",
"base",
"=",
"0",
",",
"random_",
"=",
"False",
",",
"direction",
"=",
"1",
")",
":",
"if",
"not",
"self",
".",
"_songs",
"or",
"len",
"(",
"self",
".",
"_songs",
")",
"<=",
"len",
"(",
"self",
".",
"_ba... | 从播放列表中获取一首可以播放的歌曲
:param base: base index
:param random: random strategy or not
:param direction: forward if > 0 else backword
>>> pl = Playlist([1, 2, 3])
>>> pl._get_good_song()
1
>>> pl._get_good_song(base=1)
2
>>> pl._bad_songs = [2]
... | [
"从播放列表中获取一首可以播放的歌曲"
] | python | train |
jaysonsantos/python-binary-memcached | bmemcached/protocol.py | https://github.com/jaysonsantos/python-binary-memcached/blob/6a792829349c69204d9c5045e5c34b4231216dd6/bmemcached/protocol.py#L181-L199 | def _read_socket(self, size):
"""
Reads data from socket.
:param size: Size in bytes to be read.
:return: Data from socket
"""
value = b''
while len(value) < size:
data = self.connection.recv(size - len(value))
if not data:
... | [
"def",
"_read_socket",
"(",
"self",
",",
"size",
")",
":",
"value",
"=",
"b''",
"while",
"len",
"(",
"value",
")",
"<",
"size",
":",
"data",
"=",
"self",
".",
"connection",
".",
"recv",
"(",
"size",
"-",
"len",
"(",
"value",
")",
")",
"if",
"not"... | Reads data from socket.
:param size: Size in bytes to be read.
:return: Data from socket | [
"Reads",
"data",
"from",
"socket",
"."
] | python | train |
ceph/ceph-deploy | ceph_deploy/osd.py | https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/osd.py#L177-L233 | def create_osd(
conn,
cluster,
data,
journal,
zap,
fs_type,
dmcrypt,
dmcrypt_dir,
storetype,
block_wal,
block_db,
**kw):
"""
Run on osd node, creates an OSD from a data disk.
"""
ceph_volume_executable = syst... | [
"def",
"create_osd",
"(",
"conn",
",",
"cluster",
",",
"data",
",",
"journal",
",",
"zap",
",",
"fs_type",
",",
"dmcrypt",
",",
"dmcrypt_dir",
",",
"storetype",
",",
"block_wal",
",",
"block_db",
",",
"*",
"*",
"kw",
")",
":",
"ceph_volume_executable",
"... | Run on osd node, creates an OSD from a data disk. | [
"Run",
"on",
"osd",
"node",
"creates",
"an",
"OSD",
"from",
"a",
"data",
"disk",
"."
] | python | train |
KelSolaar/Umbra | umbra/components/factory/script_editor/script_editor.py | https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/components/factory/script_editor/script_editor.py#L3764-L3781 | def loop_through_editors(self, backward=False):
"""
Loops through the editor tabs.
:param backward: Looping backward.
:type backward: bool
:return: Method success.
:rtype: bool
"""
step = not backward and 1 or -1
idx = self.Script_Editor_tabWidge... | [
"def",
"loop_through_editors",
"(",
"self",
",",
"backward",
"=",
"False",
")",
":",
"step",
"=",
"not",
"backward",
"and",
"1",
"or",
"-",
"1",
"idx",
"=",
"self",
".",
"Script_Editor_tabWidget",
".",
"currentIndex",
"(",
")",
"+",
"step",
"if",
"idx",
... | Loops through the editor tabs.
:param backward: Looping backward.
:type backward: bool
:return: Method success.
:rtype: bool | [
"Loops",
"through",
"the",
"editor",
"tabs",
"."
] | python | train |
pypa/pipenv | pipenv/vendor/toml/decoder.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/toml/decoder.py#L143-L461 | def loads(s, _dict=dict, decoder=None):
"""Parses string as toml
Args:
s: String to be parsed
_dict: (optional) Specifies the class of the returned toml dictionary
Returns:
Parsed toml file represented as a dictionary
Raises:
TypeError: When a non-string is passed
... | [
"def",
"loads",
"(",
"s",
",",
"_dict",
"=",
"dict",
",",
"decoder",
"=",
"None",
")",
":",
"implicitgroups",
"=",
"[",
"]",
"if",
"decoder",
"is",
"None",
":",
"decoder",
"=",
"TomlDecoder",
"(",
"_dict",
")",
"retval",
"=",
"decoder",
".",
"get_emp... | Parses string as toml
Args:
s: String to be parsed
_dict: (optional) Specifies the class of the returned toml dictionary
Returns:
Parsed toml file represented as a dictionary
Raises:
TypeError: When a non-string is passed
TomlDecodeError: Error while decoding toml | [
"Parses",
"string",
"as",
"toml"
] | python | train |
jonathansick/paperweight | paperweight/texutils.py | https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/texutils.py#L68-L86 | def inline_bbl(root_tex, bbl_tex):
"""Inline a compiled bibliography (.bbl) in place of a bibliography
environment.
Parameters
----------
root_tex : unicode
Text to process.
bbl_tex : unicode
Text of bibliography file.
Returns
-------
txt : unicode
Text with... | [
"def",
"inline_bbl",
"(",
"root_tex",
",",
"bbl_tex",
")",
":",
"bbl_tex",
"=",
"bbl_tex",
".",
"replace",
"(",
"u'\\\\'",
",",
"u'\\\\\\\\'",
")",
"result",
"=",
"bib_pattern",
".",
"sub",
"(",
"bbl_tex",
",",
"root_tex",
")",
"return",
"result"
] | Inline a compiled bibliography (.bbl) in place of a bibliography
environment.
Parameters
----------
root_tex : unicode
Text to process.
bbl_tex : unicode
Text of bibliography file.
Returns
-------
txt : unicode
Text with bibliography included. | [
"Inline",
"a",
"compiled",
"bibliography",
"(",
".",
"bbl",
")",
"in",
"place",
"of",
"a",
"bibliography",
"environment",
"."
] | python | train |
nuagenetworks/bambou | bambou/nurest_push_center.py | https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_push_center.py#L173-L210 | def _did_receive_event(self, connection):
""" Receive an event from connection """
if not self._is_running:
return
if connection.has_timeouted:
return
response = connection.response
data = None
if response.status_code != 200:
pushce... | [
"def",
"_did_receive_event",
"(",
"self",
",",
"connection",
")",
":",
"if",
"not",
"self",
".",
"_is_running",
":",
"return",
"if",
"connection",
".",
"has_timeouted",
":",
"return",
"response",
"=",
"connection",
".",
"response",
"data",
"=",
"None",
"if",... | Receive an event from connection | [
"Receive",
"an",
"event",
"from",
"connection"
] | python | train |
zhelev/python-afsapi | afsapi/__init__.py | https://github.com/zhelev/python-afsapi/blob/bb1990cf1460ae42f2dde75f2291625ddac2c0e4/afsapi/__init__.py#L262-L270 | def set_mode(self, value):
"""Set the currently active mode on the device (DAB, FM, Spotify)."""
mode = -1
modes = yield from self.get_modes()
for temp_mode in modes:
if temp_mode['label'] == value:
mode = temp_mode['band']
return (yield from self.han... | [
"def",
"set_mode",
"(",
"self",
",",
"value",
")",
":",
"mode",
"=",
"-",
"1",
"modes",
"=",
"yield",
"from",
"self",
".",
"get_modes",
"(",
")",
"for",
"temp_mode",
"in",
"modes",
":",
"if",
"temp_mode",
"[",
"'label'",
"]",
"==",
"value",
":",
"m... | Set the currently active mode on the device (DAB, FM, Spotify). | [
"Set",
"the",
"currently",
"active",
"mode",
"on",
"the",
"device",
"(",
"DAB",
"FM",
"Spotify",
")",
"."
] | python | valid |
insilichem/ommprotocol | ommprotocol/utils.py | https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/utils.py#L59-L65 | def assertinstance(obj, types):
"""
Make sure object `obj` is of type `types`. Else, raise TypeError.
"""
if isinstance(obj, types):
return obj
raise TypeError('{} must be instance of {}'.format(obj, types)) | [
"def",
"assertinstance",
"(",
"obj",
",",
"types",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"types",
")",
":",
"return",
"obj",
"raise",
"TypeError",
"(",
"'{} must be instance of {}'",
".",
"format",
"(",
"obj",
",",
"types",
")",
")"
] | Make sure object `obj` is of type `types`. Else, raise TypeError. | [
"Make",
"sure",
"object",
"obj",
"is",
"of",
"type",
"types",
".",
"Else",
"raise",
"TypeError",
"."
] | python | train |
ltworf/typedload | typedload/__init__.py | https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/__init__.py#L157-L168 | def dump(value: Any, **kwargs) -> Any:
"""
Quick function to dump a data structure into
something that is compatible with json or
other programs and languages.
It is useful to avoid creating the Dumper object,
in case only the default parameters are used.
"""
from . import datadumper
... | [
"def",
"dump",
"(",
"value",
":",
"Any",
",",
"*",
"*",
"kwargs",
")",
"->",
"Any",
":",
"from",
".",
"import",
"datadumper",
"dumper",
"=",
"datadumper",
".",
"Dumper",
"(",
"*",
"*",
"kwargs",
")",
"return",
"dumper",
".",
"dump",
"(",
"value",
"... | Quick function to dump a data structure into
something that is compatible with json or
other programs and languages.
It is useful to avoid creating the Dumper object,
in case only the default parameters are used. | [
"Quick",
"function",
"to",
"dump",
"a",
"data",
"structure",
"into",
"something",
"that",
"is",
"compatible",
"with",
"json",
"or",
"other",
"programs",
"and",
"languages",
"."
] | python | train |
google/grr | grr/client/grr_response_client/client_actions/windows/windows.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client/grr_response_client/client_actions/windows/windows.py#L71-L96 | def EnumerateInterfacesFromClient(args):
"""Enumerate all MAC addresses of all NICs.
Args:
args: Unused.
Yields:
`rdf_client_network.Interface` instances.
"""
del args # Unused.
pythoncom.CoInitialize()
for interface in (wmi.WMI().Win32_NetworkAdapterConfiguration() or []):
addresses = []
... | [
"def",
"EnumerateInterfacesFromClient",
"(",
"args",
")",
":",
"del",
"args",
"# Unused.",
"pythoncom",
".",
"CoInitialize",
"(",
")",
"for",
"interface",
"in",
"(",
"wmi",
".",
"WMI",
"(",
")",
".",
"Win32_NetworkAdapterConfiguration",
"(",
")",
"or",
"[",
... | Enumerate all MAC addresses of all NICs.
Args:
args: Unused.
Yields:
`rdf_client_network.Interface` instances. | [
"Enumerate",
"all",
"MAC",
"addresses",
"of",
"all",
"NICs",
"."
] | python | train |
CivicSpleen/ambry | ambry/bundle/files.py | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/files.py#L458-L466 | def record_to_fh(self, f):
"""Write the record, in filesystem format, to a file handle or file object"""
fr = self.record
if fr.contents:
yaml.safe_dump(fr.unpacked_contents, f, default_flow_style=False, encoding='utf-8')
fr.source_hash = self.fs_hash
fr.mod... | [
"def",
"record_to_fh",
"(",
"self",
",",
"f",
")",
":",
"fr",
"=",
"self",
".",
"record",
"if",
"fr",
".",
"contents",
":",
"yaml",
".",
"safe_dump",
"(",
"fr",
".",
"unpacked_contents",
",",
"f",
",",
"default_flow_style",
"=",
"False",
",",
"encoding... | Write the record, in filesystem format, to a file handle or file object | [
"Write",
"the",
"record",
"in",
"filesystem",
"format",
"to",
"a",
"file",
"handle",
"or",
"file",
"object"
] | python | train |
mwgielen/jackal | jackal/utils.py | https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/utils.py#L85-L189 | def draw_interface(objects, callback, callback_text):
"""
Draws a ncurses interface. Based on the given object list, every object should have a "string" key, this is whats displayed on the screen, callback is called with the selected object.
Rest of the code is modified from:
https://stackov... | [
"def",
"draw_interface",
"(",
"objects",
",",
"callback",
",",
"callback_text",
")",
":",
"screen",
"=",
"curses",
".",
"initscr",
"(",
")",
"height",
",",
"width",
"=",
"screen",
".",
"getmaxyx",
"(",
")",
"curses",
".",
"noecho",
"(",
")",
"curses",
... | Draws a ncurses interface. Based on the given object list, every object should have a "string" key, this is whats displayed on the screen, callback is called with the selected object.
Rest of the code is modified from:
https://stackoverflow.com/a/30834868 | [
"Draws",
"a",
"ncurses",
"interface",
".",
"Based",
"on",
"the",
"given",
"object",
"list",
"every",
"object",
"should",
"have",
"a",
"string",
"key",
"this",
"is",
"whats",
"displayed",
"on",
"the",
"screen",
"callback",
"is",
"called",
"with",
"the",
"se... | python | valid |
ankitmathur3193/song-cli | song/commands/MusicWebsiteParser/MrJattParser.py | https://github.com/ankitmathur3193/song-cli/blob/ca8ccfe547e9d702313ff6d14e81ae4355989a67/song/commands/MusicWebsiteParser/MrJattParser.py#L29-L45 | def list_of_all_href(self,html):
'''
It will return all hyper links found in the mr-jatt page for download
'''
soup=BeautifulSoup(html)
links=[]
a_list=soup.findAll('a','touch')
for x in xrange(len(a_list)-1):
link = a_list[x].get('href')
name = a_list[x]
name = str(name)
name=re.sub(r'<a.*/>... | [
"def",
"list_of_all_href",
"(",
"self",
",",
"html",
")",
":",
"soup",
"=",
"BeautifulSoup",
"(",
"html",
")",
"links",
"=",
"[",
"]",
"a_list",
"=",
"soup",
".",
"findAll",
"(",
"'a'",
",",
"'touch'",
")",
"for",
"x",
"in",
"xrange",
"(",
"len",
"... | It will return all hyper links found in the mr-jatt page for download | [
"It",
"will",
"return",
"all",
"hyper",
"links",
"found",
"in",
"the",
"mr",
"-",
"jatt",
"page",
"for",
"download"
] | python | test |
Kozea/cairocffi | cairocffi/context.py | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L1370-L1380 | def mask(self, pattern):
"""A drawing operator that paints the current source
using the alpha channel of :obj:`pattern` as a mask.
(Opaque areas of :obj:`pattern` are painted with the source,
transparent areas are not painted.)
:param pattern: A :class:`Pattern` object.
... | [
"def",
"mask",
"(",
"self",
",",
"pattern",
")",
":",
"cairo",
".",
"cairo_mask",
"(",
"self",
".",
"_pointer",
",",
"pattern",
".",
"_pointer",
")",
"self",
".",
"_check_status",
"(",
")"
] | A drawing operator that paints the current source
using the alpha channel of :obj:`pattern` as a mask.
(Opaque areas of :obj:`pattern` are painted with the source,
transparent areas are not painted.)
:param pattern: A :class:`Pattern` object. | [
"A",
"drawing",
"operator",
"that",
"paints",
"the",
"current",
"source",
"using",
"the",
"alpha",
"channel",
"of",
":",
"obj",
":",
"pattern",
"as",
"a",
"mask",
".",
"(",
"Opaque",
"areas",
"of",
":",
"obj",
":",
"pattern",
"are",
"painted",
"with",
... | python | train |
google/grr | grr/server/grr_response_server/databases/mysql_signed_binaries.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_signed_binaries.py#L85-L96 | def DeleteSignedBinaryReferences(self,
binary_id,
cursor=None):
"""Deletes blob references for the given signed binary from the DB."""
cursor.execute(
"""
DELETE FROM signed_binary_references
WHERE binary_type = %s AND bin... | [
"def",
"DeleteSignedBinaryReferences",
"(",
"self",
",",
"binary_id",
",",
"cursor",
"=",
"None",
")",
":",
"cursor",
".",
"execute",
"(",
"\"\"\"\n DELETE FROM signed_binary_references\n WHERE binary_type = %s AND binary_path_hash = %s\n \"\"\"",
",",
"[",
"binary... | Deletes blob references for the given signed binary from the DB. | [
"Deletes",
"blob",
"references",
"for",
"the",
"given",
"signed",
"binary",
"from",
"the",
"DB",
"."
] | python | train |
mitsei/dlkit | dlkit/records/osid/base_records.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/records/osid/base_records.py#L861-L867 | def clear_decimal_value(self):
"""stub"""
if (self.get_decimal_value_metadata().is_read_only() or
self.get_decimal_value_metadata().is_required()):
raise NoAccess()
self.my_osid_object_form._my_map['decimalValue'] = \
self.get_decimal_value_metadata().get_... | [
"def",
"clear_decimal_value",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"get_decimal_value_metadata",
"(",
")",
".",
"is_read_only",
"(",
")",
"or",
"self",
".",
"get_decimal_value_metadata",
"(",
")",
".",
"is_required",
"(",
")",
")",
":",
"raise",
... | stub | [
"stub"
] | python | train |
trailofbits/manticore | manticore/platforms/evm.py | https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1545-L1551 | def MSTORE(self, address, value):
"""Save word to memory"""
if istainted(self.pc):
for taint in get_taints(self.pc):
value = taint_with(value, taint)
self._allocate(address, 32)
self._store(address, value, 32) | [
"def",
"MSTORE",
"(",
"self",
",",
"address",
",",
"value",
")",
":",
"if",
"istainted",
"(",
"self",
".",
"pc",
")",
":",
"for",
"taint",
"in",
"get_taints",
"(",
"self",
".",
"pc",
")",
":",
"value",
"=",
"taint_with",
"(",
"value",
",",
"taint",... | Save word to memory | [
"Save",
"word",
"to",
"memory"
] | python | valid |
pmacosta/pcsv | pcsv/dsort.py | https://github.com/pmacosta/pcsv/blob/cd1588c19b0cd58c38bc672e396db940f88ffbd7/pcsv/dsort.py#L37-L93 | def dsort(fname, order, has_header=True, frow=0, ofname=None):
r"""
Sort file data.
:param fname: Name of the comma-separated values file to sort
:type fname: FileNameExists_
:param order: Sort order
:type order: :ref:`CsvColFilter`
:param has_header: Flag that indicates whether the com... | [
"def",
"dsort",
"(",
"fname",
",",
"order",
",",
"has_header",
"=",
"True",
",",
"frow",
"=",
"0",
",",
"ofname",
"=",
"None",
")",
":",
"ofname",
"=",
"fname",
"if",
"ofname",
"is",
"None",
"else",
"ofname",
"obj",
"=",
"CsvFile",
"(",
"fname",
"=... | r"""
Sort file data.
:param fname: Name of the comma-separated values file to sort
:type fname: FileNameExists_
:param order: Sort order
:type order: :ref:`CsvColFilter`
:param has_header: Flag that indicates whether the comma-separated
values file to sort has column ... | [
"r",
"Sort",
"file",
"data",
"."
] | python | train |
kylejusticemagnuson/pyti | pyti/average_true_range_percent.py | https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/average_true_range_percent.py#L9-L18 | def average_true_range_percent(close_data, period):
"""
Average True Range Percent.
Formula:
ATRP = (ATR / CLOSE) * 100
"""
catch_errors.check_for_period_error(close_data, period)
atrp = (atr(close_data, period) / np.array(close_data)) * 100
return atrp | [
"def",
"average_true_range_percent",
"(",
"close_data",
",",
"period",
")",
":",
"catch_errors",
".",
"check_for_period_error",
"(",
"close_data",
",",
"period",
")",
"atrp",
"=",
"(",
"atr",
"(",
"close_data",
",",
"period",
")",
"/",
"np",
".",
"array",
"(... | Average True Range Percent.
Formula:
ATRP = (ATR / CLOSE) * 100 | [
"Average",
"True",
"Range",
"Percent",
"."
] | python | train |
mitsei/dlkit | dlkit/services/repository.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/services/repository.py#L1483-L1491 | def use_federated_repository_view(self):
"""Pass through to provider AssetLookupSession.use_federated_repository_view"""
self._repository_view = FEDERATED
# self._get_provider_session('asset_lookup_session') # To make sure the session is tracked
for session in self._get_provider_sessions... | [
"def",
"use_federated_repository_view",
"(",
"self",
")",
":",
"self",
".",
"_repository_view",
"=",
"FEDERATED",
"# self._get_provider_session('asset_lookup_session') # To make sure the session is tracked",
"for",
"session",
"in",
"self",
".",
"_get_provider_sessions",
"(",
")... | Pass through to provider AssetLookupSession.use_federated_repository_view | [
"Pass",
"through",
"to",
"provider",
"AssetLookupSession",
".",
"use_federated_repository_view"
] | python | train |
zsimic/runez | src/runez/click.py | https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/click.py#L49-L53 | def debug(*args, **attrs):
"""Show debugging information."""
attrs.setdefault("is_flag", True)
attrs.setdefault("default", None)
return option(debug, *args, **attrs) | [
"def",
"debug",
"(",
"*",
"args",
",",
"*",
"*",
"attrs",
")",
":",
"attrs",
".",
"setdefault",
"(",
"\"is_flag\"",
",",
"True",
")",
"attrs",
".",
"setdefault",
"(",
"\"default\"",
",",
"None",
")",
"return",
"option",
"(",
"debug",
",",
"*",
"args"... | Show debugging information. | [
"Show",
"debugging",
"information",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/repository/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/repository/sessions.py#L697-L722 | def get_asset_contents_for_asset(self, asset_id):
"""Gets an ``AssetList`` from the given Asset.
In plenary mode, the returned list contains all known asset contents or
an error results. Otherwise, the returned list may contain only
those asset contents that are accessible through this ... | [
"def",
"get_asset_contents_for_asset",
"(",
"self",
",",
"asset_id",
")",
":",
"collection",
"=",
"JSONClientValidated",
"(",
"'repository'",
",",
"collection",
"=",
"'Asset'",
",",
"runtime",
"=",
"self",
".",
"_runtime",
")",
"result",
"=",
"collection",
".",
... | Gets an ``AssetList`` from the given Asset.
In plenary mode, the returned list contains all known asset contents or
an error results. Otherwise, the returned list may contain only
those asset contents that are accessible through this session.
:param asset_id: an asset ``Id``
:t... | [
"Gets",
"an",
"AssetList",
"from",
"the",
"given",
"Asset",
"."
] | python | train |
openego/ding0 | ding0/grid/lv_grid/build_grid.py | https://github.com/openego/ding0/blob/e2d6528f96255e4bb22ba15514a4f1883564ed5d/ding0/grid/lv_grid/build_grid.py#L601-L752 | def build_lv_graph_residential(lvgd, selected_string_df):
"""Builds nxGraph based on the LV grid model
Parameters
----------
lvgd : LVGridDistrictDing0
Low-voltage grid district object
selected_string_df: :pandas:`pandas.DataFrame<dataframe>`
Table of strings of the selected grid mo... | [
"def",
"build_lv_graph_residential",
"(",
"lvgd",
",",
"selected_string_df",
")",
":",
"houses_connected",
"=",
"(",
"selected_string_df",
"[",
"'occurence'",
"]",
"*",
"selected_string_df",
"[",
"'count house branch'",
"]",
")",
".",
"sum",
"(",
")",
"average_load"... | Builds nxGraph based on the LV grid model
Parameters
----------
lvgd : LVGridDistrictDing0
Low-voltage grid district object
selected_string_df: :pandas:`pandas.DataFrame<dataframe>`
Table of strings of the selected grid model
Notes
-----
To understand what is happening in t... | [
"Builds",
"nxGraph",
"based",
"on",
"the",
"LV",
"grid",
"model"
] | python | train |
trailofbits/manticore | manticore/native/cpu/x86.py | https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L5781-L5790 | def VEXTRACTF128(cpu, dest, src, offset):
"""Extract Packed Floating-Point Values
Extracts 128-bits of packed floating-point values from the source
operand (second operand) at an 128-bit offset from imm8[0] into the
destination operand (first operand). The destination may be either an
... | [
"def",
"VEXTRACTF128",
"(",
"cpu",
",",
"dest",
",",
"src",
",",
"offset",
")",
":",
"offset",
"=",
"offset",
".",
"read",
"(",
")",
"dest",
".",
"write",
"(",
"Operators",
".",
"EXTRACT",
"(",
"src",
".",
"read",
"(",
")",
",",
"offset",
"*",
"1... | Extract Packed Floating-Point Values
Extracts 128-bits of packed floating-point values from the source
operand (second operand) at an 128-bit offset from imm8[0] into the
destination operand (first operand). The destination may be either an
XMM register or an 128-bit memory location. | [
"Extract",
"Packed",
"Floating",
"-",
"Point",
"Values"
] | python | valid |
riga/scinum | scinum.py | https://github.com/riga/scinum/blob/55eb6d8aa77beacee5a07443392954b8a0aad8cb/scinum.py#L431-L437 | def set_uncertainty(self, name, value):
"""
Sets the uncertainty *value* for an uncertainty *name*. *value* should have one of the
formats as described in :py:meth:`uncertainties`.
"""
uncertainties = self.__class__.uncertainties.fparse(self, {name: value})
self._uncertai... | [
"def",
"set_uncertainty",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"uncertainties",
"=",
"self",
".",
"__class__",
".",
"uncertainties",
".",
"fparse",
"(",
"self",
",",
"{",
"name",
":",
"value",
"}",
")",
"self",
".",
"_uncertainties",
".",
... | Sets the uncertainty *value* for an uncertainty *name*. *value* should have one of the
formats as described in :py:meth:`uncertainties`. | [
"Sets",
"the",
"uncertainty",
"*",
"value",
"*",
"for",
"an",
"uncertainty",
"*",
"name",
"*",
".",
"*",
"value",
"*",
"should",
"have",
"one",
"of",
"the",
"formats",
"as",
"described",
"in",
":",
"py",
":",
"meth",
":",
"uncertainties",
"."
] | python | train |
openstack/networking-cisco | networking_cisco/apps/saf/server/dfa_server.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/dfa_server.py#L606-L628 | def project_delete_event(self, proj_info):
"""Process project delete event."""
LOG.debug("Processing project_delete_event...")
proj_id = proj_info.get('resource_info')
proj_name = self.get_project_name(proj_id)
if proj_name:
try:
self.dcnm_client.dele... | [
"def",
"project_delete_event",
"(",
"self",
",",
"proj_info",
")",
":",
"LOG",
".",
"debug",
"(",
"\"Processing project_delete_event...\"",
")",
"proj_id",
"=",
"proj_info",
".",
"get",
"(",
"'resource_info'",
")",
"proj_name",
"=",
"self",
".",
"get_project_name"... | Process project delete event. | [
"Process",
"project",
"delete",
"event",
"."
] | python | train |
aleju/imgaug | imgaug/augmentables/kps.py | https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/kps.py#L105-L131 | def project(self, from_shape, to_shape):
"""
Project the keypoint onto a new position on a new image.
E.g. if the keypoint is on its original image at x=(10 of 100 pixels)
and y=(20 of 100 pixels) and is projected onto a new image with
size (width=200, height=200), its new posit... | [
"def",
"project",
"(",
"self",
",",
"from_shape",
",",
"to_shape",
")",
":",
"xy_proj",
"=",
"project_coords",
"(",
"[",
"(",
"self",
".",
"x",
",",
"self",
".",
"y",
")",
"]",
",",
"from_shape",
",",
"to_shape",
")",
"return",
"self",
".",
"deepcopy... | Project the keypoint onto a new position on a new image.
E.g. if the keypoint is on its original image at x=(10 of 100 pixels)
and y=(20 of 100 pixels) and is projected onto a new image with
size (width=200, height=200), its new position will be (20, 40).
This is intended for cases whe... | [
"Project",
"the",
"keypoint",
"onto",
"a",
"new",
"position",
"on",
"a",
"new",
"image",
"."
] | python | valid |
ynop/audiomate | audiomate/corpus/io/common_voice.py | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/io/common_voice.py#L39-L48 | def get_subset_ids(path):
""" Return a list with ids of all available subsets (based on existing csv-files). """
all = []
for path in glob.glob(os.path.join(path, '*.tsv')):
file_name = os.path.split(path)[1]
basename = os.path.splitext(file_name)[0]
all.appe... | [
"def",
"get_subset_ids",
"(",
"path",
")",
":",
"all",
"=",
"[",
"]",
"for",
"path",
"in",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'*.tsv'",
")",
")",
":",
"file_name",
"=",
"os",
".",
"path",
".",
"split",
... | Return a list with ids of all available subsets (based on existing csv-files). | [
"Return",
"a",
"list",
"with",
"ids",
"of",
"all",
"available",
"subsets",
"(",
"based",
"on",
"existing",
"csv",
"-",
"files",
")",
"."
] | python | train |
CI-WATER/gsshapy | gsshapy/orm/tim.py | https://github.com/CI-WATER/gsshapy/blob/00fd4af0fd65f1614d75a52fe950a04fb0867f4c/gsshapy/orm/tim.py#L60-L82 | def _read(self, directory, filename, session, path, name, extension, spatial=None, spatialReferenceID=None, replaceParamFile=None):
"""
Generic Time Series Read from File Method
"""
# Assign file extension attribute to file object
self.fileExtension = extension
timeSerie... | [
"def",
"_read",
"(",
"self",
",",
"directory",
",",
"filename",
",",
"session",
",",
"path",
",",
"name",
",",
"extension",
",",
"spatial",
"=",
"None",
",",
"spatialReferenceID",
"=",
"None",
",",
"replaceParamFile",
"=",
"None",
")",
":",
"# Assign file ... | Generic Time Series Read from File Method | [
"Generic",
"Time",
"Series",
"Read",
"from",
"File",
"Method"
] | python | train |
fracpete/python-weka-wrapper3 | python/weka/core/classes.py | https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/classes.py#L1471-L1485 | def find(self, name):
"""
Returns the Tag that matches the name.
:param name: the string representation of the tag
:type name: str
:return: the tag, None if not found
:rtype: Tag
"""
result = None
for t in self.array:
if str(t) == name... | [
"def",
"find",
"(",
"self",
",",
"name",
")",
":",
"result",
"=",
"None",
"for",
"t",
"in",
"self",
".",
"array",
":",
"if",
"str",
"(",
"t",
")",
"==",
"name",
":",
"result",
"=",
"Tag",
"(",
"t",
".",
"jobject",
")",
"break",
"return",
"resul... | Returns the Tag that matches the name.
:param name: the string representation of the tag
:type name: str
:return: the tag, None if not found
:rtype: Tag | [
"Returns",
"the",
"Tag",
"that",
"matches",
"the",
"name",
"."
] | python | train |
tamasgal/km3pipe | km3pipe/utils/streamds.py | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/utils/streamds.py#L83-L87 | def available_streams():
"""Show a short list of available streams."""
sds = kp.db.StreamDS()
print("Available streams: ")
print(', '.join(sorted(sds.streams))) | [
"def",
"available_streams",
"(",
")",
":",
"sds",
"=",
"kp",
".",
"db",
".",
"StreamDS",
"(",
")",
"print",
"(",
"\"Available streams: \"",
")",
"print",
"(",
"', '",
".",
"join",
"(",
"sorted",
"(",
"sds",
".",
"streams",
")",
")",
")"
] | Show a short list of available streams. | [
"Show",
"a",
"short",
"list",
"of",
"available",
"streams",
"."
] | python | train |
diux-dev/ncluster | ncluster/aws_backend.py | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_backend.py#L813-L892 | def make_job(
name: str = '',
run_name: str = '',
num_tasks: int = 1,
install_script: str = '',
instance_type: str = '',
image_name: str = '',
create_resources=True,
**kwargs) -> Job:
"""
Args:
create_resources: if True, will create resources if ne... | [
"def",
"make_job",
"(",
"name",
":",
"str",
"=",
"''",
",",
"run_name",
":",
"str",
"=",
"''",
",",
"num_tasks",
":",
"int",
"=",
"1",
",",
"install_script",
":",
"str",
"=",
"''",
",",
"instance_type",
":",
"str",
"=",
"''",
",",
"image_name",
":"... | Args:
create_resources: if True, will create resources if necessary
name: see backend.make_task
run_name: see backend.make_task
num_tasks: number of tasks to launch
install_script: see make_task
instance_type: see make_task
image_name: see make_task
Returns: | [
"Args",
":",
"create_resources",
":",
"if",
"True",
"will",
"create",
"resources",
"if",
"necessary",
"name",
":",
"see",
"backend",
".",
"make_task",
"run_name",
":",
"see",
"backend",
".",
"make_task",
"num_tasks",
":",
"number",
"of",
"tasks",
"to",
"laun... | python | train |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v20/ardupilotmega.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v20/ardupilotmega.py#L10796-L10808 | def ekf_status_report_encode(self, flags, velocity_variance, pos_horiz_variance, pos_vert_variance, compass_variance, terrain_alt_variance):
'''
EKF Status message including flags and variances
flags : Flags (uint16_t)
velocity_varianc... | [
"def",
"ekf_status_report_encode",
"(",
"self",
",",
"flags",
",",
"velocity_variance",
",",
"pos_horiz_variance",
",",
"pos_vert_variance",
",",
"compass_variance",
",",
"terrain_alt_variance",
")",
":",
"return",
"MAVLink_ekf_status_report_message",
"(",
"flags",
",",
... | EKF Status message including flags and variances
flags : Flags (uint16_t)
velocity_variance : Velocity variance (float)
pos_horiz_variance : Horizontal Position variance (float)
pos_vert_variance : Vertical Posit... | [
"EKF",
"Status",
"message",
"including",
"flags",
"and",
"variances"
] | python | train |
artefactual-labs/mets-reader-writer | metsrw/metadata.py | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/metadata.py#L540-L568 | def parse(cls, root):
"""
Create a new MDWrap by parsing root.
:param root: Element or ElementTree to be parsed into a MDWrap.
:raises exceptions.ParseError: If mdWrap does not contain MDTYPE
:raises exceptions.ParseError: If xmlData contains no children
"""
if r... | [
"def",
"parse",
"(",
"cls",
",",
"root",
")",
":",
"if",
"root",
".",
"tag",
"!=",
"utils",
".",
"lxmlns",
"(",
"\"mets\"",
")",
"+",
"\"mdWrap\"",
":",
"raise",
"exceptions",
".",
"ParseError",
"(",
"\"MDWrap can only parse mdWrap elements with METS namespace.\... | Create a new MDWrap by parsing root.
:param root: Element or ElementTree to be parsed into a MDWrap.
:raises exceptions.ParseError: If mdWrap does not contain MDTYPE
:raises exceptions.ParseError: If xmlData contains no children | [
"Create",
"a",
"new",
"MDWrap",
"by",
"parsing",
"root",
"."
] | python | train |
pantsbuild/pants | src/python/pants/backend/jvm/targets/jarable.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/targets/jarable.py#L32-L43 | def get_artifact_info(self):
"""Returns a tuple composed of a :class:`pants.java.jar.JarDependency`
describing the jar for this target and a bool indicating if this target is exportable.
"""
exported = bool(self.provides)
org = self.provides.org if exported else 'internal'
name = self.provides.... | [
"def",
"get_artifact_info",
"(",
"self",
")",
":",
"exported",
"=",
"bool",
"(",
"self",
".",
"provides",
")",
"org",
"=",
"self",
".",
"provides",
".",
"org",
"if",
"exported",
"else",
"'internal'",
"name",
"=",
"self",
".",
"provides",
".",
"name",
"... | Returns a tuple composed of a :class:`pants.java.jar.JarDependency`
describing the jar for this target and a bool indicating if this target is exportable. | [
"Returns",
"a",
"tuple",
"composed",
"of",
"a",
":",
"class",
":",
"pants",
".",
"java",
".",
"jar",
".",
"JarDependency",
"describing",
"the",
"jar",
"for",
"this",
"target",
"and",
"a",
"bool",
"indicating",
"if",
"this",
"target",
"is",
"exportable",
... | python | train |
rytilahti/python-eq3bt | eq3bt/connection.py | https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/connection.py#L53-L57 | def handleNotification(self, handle, data):
"""Handle Callback from a Bluetooth (GATT) request."""
_LOGGER.debug("Got notification from %s: %s", handle, codecs.encode(data, 'hex'))
if handle in self._callbacks:
self._callbacks[handle](data) | [
"def",
"handleNotification",
"(",
"self",
",",
"handle",
",",
"data",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Got notification from %s: %s\"",
",",
"handle",
",",
"codecs",
".",
"encode",
"(",
"data",
",",
"'hex'",
")",
")",
"if",
"handle",
"in",
"self"... | Handle Callback from a Bluetooth (GATT) request. | [
"Handle",
"Callback",
"from",
"a",
"Bluetooth",
"(",
"GATT",
")",
"request",
"."
] | python | train |
mdickinson/bigfloat | bigfloat/core.py | https://github.com/mdickinson/bigfloat/blob/e5fdd1048615191ed32a2b7460e14b3b3ff24662/bigfloat/core.py#L99-L113 | def _mpfr_get_str2(base, ndigits, op, rounding_mode):
"""
Variant of mpfr_get_str, for internal use: simply splits off the '-'
sign from the digit string, and returns a triple
(sign, digits, exp)
Also converts the byte-string produced by mpfr_get_str to Unicode.
"""
digits, exp = mpf... | [
"def",
"_mpfr_get_str2",
"(",
"base",
",",
"ndigits",
",",
"op",
",",
"rounding_mode",
")",
":",
"digits",
",",
"exp",
"=",
"mpfr",
".",
"mpfr_get_str",
"(",
"base",
",",
"ndigits",
",",
"op",
",",
"rounding_mode",
")",
"negative",
"=",
"digits",
".",
... | Variant of mpfr_get_str, for internal use: simply splits off the '-'
sign from the digit string, and returns a triple
(sign, digits, exp)
Also converts the byte-string produced by mpfr_get_str to Unicode. | [
"Variant",
"of",
"mpfr_get_str",
"for",
"internal",
"use",
":",
"simply",
"splits",
"off",
"the",
"-",
"sign",
"from",
"the",
"digit",
"string",
"and",
"returns",
"a",
"triple"
] | python | train |
python-odin/odinweb | odinweb/containers.py | https://github.com/python-odin/odinweb/blob/198424133584acc18cb41c8d18d91f803abc810f/odinweb/containers.py#L298-L345 | def dispatch_operation(self, operation, request, path_args):
# type: (Operation, BaseHttpRequest, Dict[str, Any]) -> Tuple[Any, Optional[HTTPStatus], Optional[dict]]
"""
Dispatch and handle exceptions from operation.
"""
try:
# path_args is passed by ref so changes ca... | [
"def",
"dispatch_operation",
"(",
"self",
",",
"operation",
",",
"request",
",",
"path_args",
")",
":",
"# type: (Operation, BaseHttpRequest, Dict[str, Any]) -> Tuple[Any, Optional[HTTPStatus], Optional[dict]]",
"try",
":",
"# path_args is passed by ref so changes can be made.",
"for... | Dispatch and handle exceptions from operation. | [
"Dispatch",
"and",
"handle",
"exceptions",
"from",
"operation",
"."
] | python | train |
canonical-ols/acceptable | acceptable/_service.py | https://github.com/canonical-ols/acceptable/blob/6ccbe969078166a5315d857da38b59b43b29fadc/acceptable/_service.py#L234-L266 | def api(self,
url,
name,
introduced_at=None,
undocumented=False,
deprecated_at=None,
title=None,
**options):
"""Add an API to the service.
:param url: This is the url that the API should be registered at.
:param... | [
"def",
"api",
"(",
"self",
",",
"url",
",",
"name",
",",
"introduced_at",
"=",
"None",
",",
"undocumented",
"=",
"False",
",",
"deprecated_at",
"=",
"None",
",",
"title",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"location",
"=",
"get_callsite_l... | Add an API to the service.
:param url: This is the url that the API should be registered at.
:param name: This is the name of the api, and will be registered with
flask apps under.
Other keyword arguments may be used, and they will be passed to the
flask application when in... | [
"Add",
"an",
"API",
"to",
"the",
"service",
"."
] | python | train |
xav/Grapefruit | grapefruit.py | https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1123-L1147 | def from_rgb(r, g, b, alpha=1.0, wref=_DEFAULT_WREF):
"""Create a new instance based on the specifed RGB values.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
:alpha:
The color t... | [
"def",
"from_rgb",
"(",
"r",
",",
"g",
",",
"b",
",",
"alpha",
"=",
"1.0",
",",
"wref",
"=",
"_DEFAULT_WREF",
")",
":",
"return",
"Color",
"(",
"(",
"r",
",",
"g",
",",
"b",
")",
",",
"'rgb'",
",",
"alpha",
",",
"wref",
")"
] | Create a new instance based on the specifed RGB values.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
:alpha:
The color transparency [0...1], default is opaque
:wref:
T... | [
"Create",
"a",
"new",
"instance",
"based",
"on",
"the",
"specifed",
"RGB",
"values",
"."
] | python | train |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L1734-L1759 | def do_filter(self, filter_type, line):
"""
Applying filter, caring about prev line, interlacing etc.
`filter_type` may be integer to apply basic filter or
adaptive strategy with dict
(`name` is reqired field, others may tune strategy)
"""
# Recall that filtering... | [
"def",
"do_filter",
"(",
"self",
",",
"filter_type",
",",
"line",
")",
":",
"# Recall that filtering algorithms are applied to bytes,",
"# not to pixels, regardless of the bit depth or colour type",
"# of the image.",
"line",
"=",
"bytearray",
"(",
"line",
")",
"if",
"isinsta... | Applying filter, caring about prev line, interlacing etc.
`filter_type` may be integer to apply basic filter or
adaptive strategy with dict
(`name` is reqired field, others may tune strategy) | [
"Applying",
"filter",
"caring",
"about",
"prev",
"line",
"interlacing",
"etc",
"."
] | python | train |
alex-kostirin/pyatomac | atomac/Clipboard.py | https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/Clipboard.py#L99-L130 | def copy(cls, data):
"""Set the clipboard data ('Copy').
Parameters: data to set (string)
Optional: datatype if it's not a string
Returns: True / False on successful copy, Any exception raised (like
passes the NSPasteboardCommunicationError) should be caught
... | [
"def",
"copy",
"(",
"cls",
",",
"data",
")",
":",
"pp",
"=",
"pprint",
".",
"PrettyPrinter",
"(",
")",
"copy_data",
"=",
"'Data to copy (put in pasteboard): %s'",
"logging",
".",
"debug",
"(",
"copy_data",
"%",
"pp",
".",
"pformat",
"(",
"data",
")",
")",
... | Set the clipboard data ('Copy').
Parameters: data to set (string)
Optional: datatype if it's not a string
Returns: True / False on successful copy, Any exception raised (like
passes the NSPasteboardCommunicationError) should be caught
by the caller. | [
"Set",
"the",
"clipboard",
"data",
"(",
"Copy",
")",
"."
] | python | valid |
CivicSpleen/ambry | ambry/valuetype/geo.py | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/valuetype/geo.py#L139-L150 | def subclass(cls, vt_code, vt_args):
"""Return a dynamic subclass that has the extra parameters built in"""
from geoid import get_class
import geoid.census
parser = get_class(geoid.census, vt_args.strip('/')).parse
cls = type(vt_code.replace('/', '_'), (cls,), {'vt_code': vt_co... | [
"def",
"subclass",
"(",
"cls",
",",
"vt_code",
",",
"vt_args",
")",
":",
"from",
"geoid",
"import",
"get_class",
"import",
"geoid",
".",
"census",
"parser",
"=",
"get_class",
"(",
"geoid",
".",
"census",
",",
"vt_args",
".",
"strip",
"(",
"'/'",
")",
"... | Return a dynamic subclass that has the extra parameters built in | [
"Return",
"a",
"dynamic",
"subclass",
"that",
"has",
"the",
"extra",
"parameters",
"built",
"in"
] | python | train |
SoftwareDefinedBuildings/XBOS | apps/occupancy/OccupancyThanos.py | https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/occupancy/OccupancyThanos.py#L48-L88 | def find_similar_days(training_data, now, observation_length, k, method=hamming_distance):
min_time = training_data.index[0] + timedelta(minutes=observation_length)
# Find moments in our dataset that have the same hour/minute and is_weekend() == weekend.
selector = ((training_data.index.minute == now.minute) &
... | [
"def",
"find_similar_days",
"(",
"training_data",
",",
"now",
",",
"observation_length",
",",
"k",
",",
"method",
"=",
"hamming_distance",
")",
":",
"min_time",
"=",
"training_data",
".",
"index",
"[",
"0",
"]",
"+",
"timedelta",
"(",
"minutes",
"=",
"observ... | if now.weekday() < 5:
selector = (
(training_data.index.minute == now.minute) &
(training_data.index.hour == now.hour) &
(training_data.index > min_time) &
(training_data.index.weekday < 5)
)
else:
selector = (
(training_data.index.minute == now.minute) &
(training_data.index.hour == now.hour) ... | [
"if",
"now",
".",
"weekday",
"()",
"<",
"5",
":",
"selector",
"=",
"(",
"(",
"training_data",
".",
"index",
".",
"minute",
"==",
"now",
".",
"minute",
")",
"&",
"(",
"training_data",
".",
"index",
".",
"hour",
"==",
"now",
".",
"hour",
")",
"&",
... | python | train |
pantsbuild/pants | contrib/scrooge/src/python/pants/contrib/scrooge/tasks/thrift_util.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/scrooge/src/python/pants/contrib/scrooge/tasks/thrift_util.py#L46-L57 | def find_root_thrifts(basedirs, sources, log=None):
"""Finds the root thrift files in the graph formed by sources and their recursive includes.
:basedirs: A set of thrift source file base directories to look for includes in.
:sources: Seed thrift files to examine.
:log: An optional logger.
"""
root_source... | [
"def",
"find_root_thrifts",
"(",
"basedirs",
",",
"sources",
",",
"log",
"=",
"None",
")",
":",
"root_sources",
"=",
"set",
"(",
"sources",
")",
"for",
"source",
"in",
"sources",
":",
"root_sources",
".",
"difference_update",
"(",
"find_includes",
"(",
"base... | Finds the root thrift files in the graph formed by sources and their recursive includes.
:basedirs: A set of thrift source file base directories to look for includes in.
:sources: Seed thrift files to examine.
:log: An optional logger. | [
"Finds",
"the",
"root",
"thrift",
"files",
"in",
"the",
"graph",
"formed",
"by",
"sources",
"and",
"their",
"recursive",
"includes",
"."
] | python | train |
astropy/astropy-healpix | astropy_healpix/bench.py | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/bench.py#L210-L214 | def main(fast=False):
"""Run all benchmarks and print report to the console."""
print('Running benchmarks...\n')
results = bench_run(fast=fast)
bench_report(results) | [
"def",
"main",
"(",
"fast",
"=",
"False",
")",
":",
"print",
"(",
"'Running benchmarks...\\n'",
")",
"results",
"=",
"bench_run",
"(",
"fast",
"=",
"fast",
")",
"bench_report",
"(",
"results",
")"
] | Run all benchmarks and print report to the console. | [
"Run",
"all",
"benchmarks",
"and",
"print",
"report",
"to",
"the",
"console",
"."
] | python | train |
its-rigs/Trolly | trolly/trelloobject.py | https://github.com/its-rigs/Trolly/blob/483dc94c352df40dc05ead31820b059b2545cf82/trolly/trelloobject.py#L130-L134 | def create_checklist_item(self, card_id, checklist_id, checklistitem_json, **kwargs):
'''
Create a ChecklistItem object from JSON object
'''
return self.client.create_checklist_item(card_id, checklist_id, checklistitem_json, **kwargs) | [
"def",
"create_checklist_item",
"(",
"self",
",",
"card_id",
",",
"checklist_id",
",",
"checklistitem_json",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"client",
".",
"create_checklist_item",
"(",
"card_id",
",",
"checklist_id",
",",
"checklistite... | Create a ChecklistItem object from JSON object | [
"Create",
"a",
"ChecklistItem",
"object",
"from",
"JSON",
"object"
] | python | test |
manns/pyspread | pyspread/src/lib/_grid_cairo_renderer.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/lib/_grid_cairo_renderer.py#L1151-L1159 | def _get_bottom_line_coordinates(self):
"""Returns start and stop coordinates of bottom line"""
rect_x, rect_y, rect_width, rect_height = self.rect
start_point = rect_x, rect_y + rect_height
end_point = rect_x + rect_width, rect_y + rect_height
return start_point, end_point | [
"def",
"_get_bottom_line_coordinates",
"(",
"self",
")",
":",
"rect_x",
",",
"rect_y",
",",
"rect_width",
",",
"rect_height",
"=",
"self",
".",
"rect",
"start_point",
"=",
"rect_x",
",",
"rect_y",
"+",
"rect_height",
"end_point",
"=",
"rect_x",
"+",
"rect_widt... | Returns start and stop coordinates of bottom line | [
"Returns",
"start",
"and",
"stop",
"coordinates",
"of",
"bottom",
"line"
] | python | train |
wummel/patool | patoolib/programs/tar.py | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/tar.py#L27-L32 | def list_tar (archive, compression, cmd, verbosity, interactive):
"""List a TAR archive."""
cmdlist = [cmd, '--list']
add_tar_opts(cmdlist, compression, verbosity)
cmdlist.extend(["--file", archive])
return cmdlist | [
"def",
"list_tar",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
")",
":",
"cmdlist",
"=",
"[",
"cmd",
",",
"'--list'",
"]",
"add_tar_opts",
"(",
"cmdlist",
",",
"compression",
",",
"verbosity",
")",
"cmdlist",
".",
... | List a TAR archive. | [
"List",
"a",
"TAR",
"archive",
"."
] | python | train |
python-bonobo/bonobo | bonobo/execution/contexts/node.py | https://github.com/python-bonobo/bonobo/blob/70c8e62c4a88576976e5b52e58d380d6e3227ab4/bonobo/execution/contexts/node.py#L325-L356 | def _cast(self, _input, _output):
"""
Transforms a pair of input/output into the real slim shoutput.
:param _input: Bag
:param _output: mixed
:return: Bag
"""
if isenvelope(_output):
_output, _flags, _options = _output.unfold()
else:
... | [
"def",
"_cast",
"(",
"self",
",",
"_input",
",",
"_output",
")",
":",
"if",
"isenvelope",
"(",
"_output",
")",
":",
"_output",
",",
"_flags",
",",
"_options",
"=",
"_output",
".",
"unfold",
"(",
")",
"else",
":",
"_flags",
",",
"_options",
"=",
"[",
... | Transforms a pair of input/output into the real slim shoutput.
:param _input: Bag
:param _output: mixed
:return: Bag | [
"Transforms",
"a",
"pair",
"of",
"input",
"/",
"output",
"into",
"the",
"real",
"slim",
"shoutput",
"."
] | python | train |
saltstack/salt | salt/modules/mac_power.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_power.py#L238-L263 | def set_harddisk_sleep(minutes):
'''
Set the amount of idle time until the harddisk sleeps. Pass "Never" of "Off"
to never sleep.
:param minutes: Can be an integer between 1 and 180 or "Never" or "Off"
:ptype: int, str
:return: True if successful, False if not
:rtype: bool
CLI Example... | [
"def",
"set_harddisk_sleep",
"(",
"minutes",
")",
":",
"value",
"=",
"_validate_sleep",
"(",
"minutes",
")",
"cmd",
"=",
"'systemsetup -setharddisksleep {0}'",
".",
"format",
"(",
"value",
")",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_success",... | Set the amount of idle time until the harddisk sleeps. Pass "Never" of "Off"
to never sleep.
:param minutes: Can be an integer between 1 and 180 or "Never" or "Off"
:ptype: int, str
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*'... | [
"Set",
"the",
"amount",
"of",
"idle",
"time",
"until",
"the",
"harddisk",
"sleeps",
".",
"Pass",
"Never",
"of",
"Off",
"to",
"never",
"sleep",
"."
] | python | train |
batiste/django-page-cms | pages/views.py | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/views.py#L149-L165 | def choose_language(self, lang, request):
"""Deal with the multiple corner case of choosing the language."""
# Can be an empty string or None
if not lang:
lang = get_language_from_request(request)
# Raise a 404 if the language is not in not in the list
if lang not i... | [
"def",
"choose_language",
"(",
"self",
",",
"lang",
",",
"request",
")",
":",
"# Can be an empty string or None",
"if",
"not",
"lang",
":",
"lang",
"=",
"get_language_from_request",
"(",
"request",
")",
"# Raise a 404 if the language is not in not in the list",
"if",
"l... | Deal with the multiple corner case of choosing the language. | [
"Deal",
"with",
"the",
"multiple",
"corner",
"case",
"of",
"choosing",
"the",
"language",
"."
] | python | train |
alphagov/performanceplatform-collector | performanceplatform/collector/arguments.py | https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/arguments.py#L6-L63 | def parse_args(name="", args=None):
"""Parse command line argument for a collector
Returns an argparse.Namespace with 'config' and 'query' options"""
def _load_json_file(path):
with open(path) as f:
json_data = json.load(f)
json_data['path_to_json_file'] = path
r... | [
"def",
"parse_args",
"(",
"name",
"=",
"\"\"",
",",
"args",
"=",
"None",
")",
":",
"def",
"_load_json_file",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
")",
"as",
"f",
":",
"json_data",
"=",
"json",
".",
"load",
"(",
"f",
")",
"json_data",... | Parse command line argument for a collector
Returns an argparse.Namespace with 'config' and 'query' options | [
"Parse",
"command",
"line",
"argument",
"for",
"a",
"collector"
] | python | train |
base4sistemas/satcfe | satcfe/resposta/consultarnumerosessao.py | https://github.com/base4sistemas/satcfe/blob/cb8e8815f4133d3e3d94cf526fa86767b4521ed9/satcfe/resposta/consultarnumerosessao.py#L65-L81 | def analisar(retorno):
"""Constrói uma :class:`RespostaSAT` ou especialização dependendo da
função SAT encontrada na sessão consultada.
:param unicode retorno: Retorno da função ``ConsultarNumeroSessao``.
"""
if '|' not in retorno:
raise ErroRespostaSATInvalida('Resp... | [
"def",
"analisar",
"(",
"retorno",
")",
":",
"if",
"'|'",
"not",
"in",
"retorno",
":",
"raise",
"ErroRespostaSATInvalida",
"(",
"'Resposta nao possui pipes '",
"'separando os campos: {!r}'",
".",
"format",
"(",
"retorno",
")",
")",
"resposta",
"=",
"_RespostaParcial... | Constrói uma :class:`RespostaSAT` ou especialização dependendo da
função SAT encontrada na sessão consultada.
:param unicode retorno: Retorno da função ``ConsultarNumeroSessao``. | [
"Constrói",
"uma",
":",
"class",
":",
"RespostaSAT",
"ou",
"especialização",
"dependendo",
"da",
"função",
"SAT",
"encontrada",
"na",
"sessão",
"consultada",
"."
] | python | train |
dw/mitogen | mitogen/parent.py | https://github.com/dw/mitogen/blob/a7fdb55e1300a7e0a5e404b09eb730cf9a525da7/mitogen/parent.py#L1340-L1351 | def get_python_argv(self):
"""
Return the initial argument vector elements necessary to invoke Python,
by returning a 1-element list containing :attr:`python_path` if it is a
string, or simply returning it if it is already a list.
This allows emulation of existing tools where th... | [
"def",
"get_python_argv",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"python_path",
",",
"list",
")",
":",
"return",
"self",
".",
"python_path",
"return",
"[",
"self",
".",
"python_path",
"]"
] | Return the initial argument vector elements necessary to invoke Python,
by returning a 1-element list containing :attr:`python_path` if it is a
string, or simply returning it if it is already a list.
This allows emulation of existing tools where the Python invocation may
be set to e.g. ... | [
"Return",
"the",
"initial",
"argument",
"vector",
"elements",
"necessary",
"to",
"invoke",
"Python",
"by",
"returning",
"a",
"1",
"-",
"element",
"list",
"containing",
":",
"attr",
":",
"python_path",
"if",
"it",
"is",
"a",
"string",
"or",
"simply",
"returni... | python | train |
openid/python-openid | openid/store/filestore.py | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/filestore.py#L182-L204 | def getAssociationFilename(self, server_url, handle):
"""Create a unique filename for a given server url and
handle. This implementation does not assume anything about the
format of the handle. The filename that is returned will
contain the domain name from the server URL for ease of hum... | [
"def",
"getAssociationFilename",
"(",
"self",
",",
"server_url",
",",
"handle",
")",
":",
"if",
"server_url",
".",
"find",
"(",
"'://'",
")",
"==",
"-",
"1",
":",
"raise",
"ValueError",
"(",
"'Bad server URL: %r'",
"%",
"server_url",
")",
"proto",
",",
"re... | Create a unique filename for a given server url and
handle. This implementation does not assume anything about the
format of the handle. The filename that is returned will
contain the domain name from the server URL for ease of human
inspection of the data directory.
(str, str) ... | [
"Create",
"a",
"unique",
"filename",
"for",
"a",
"given",
"server",
"url",
"and",
"handle",
".",
"This",
"implementation",
"does",
"not",
"assume",
"anything",
"about",
"the",
"format",
"of",
"the",
"handle",
".",
"The",
"filename",
"that",
"is",
"returned",... | python | train |
PmagPy/PmagPy | programs/demag_gui.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/demag_gui.py#L844-L1085 | def create_menu(self):
"""
Create the MenuBar for the GUI current structure is:
File : Change Working Directory, Import Interpretations from LSQ
file, Import interpretations from a redo file, Save interpretations
to a redo file, Save MagIC tables, Save Plots
Edit : New In... | [
"def",
"create_menu",
"(",
"self",
")",
":",
"self",
".",
"menubar",
"=",
"wx",
".",
"MenuBar",
"(",
")",
"# -----------------",
"# File Menu",
"# -----------------",
"menu_file",
"=",
"wx",
".",
"Menu",
"(",
")",
"m_change_WD",
"=",
"menu_file",
".",
"Appen... | Create the MenuBar for the GUI current structure is:
File : Change Working Directory, Import Interpretations from LSQ
file, Import interpretations from a redo file, Save interpretations
to a redo file, Save MagIC tables, Save Plots
Edit : New Interpretation, Delete Interpretation, Next
... | [
"Create",
"the",
"MenuBar",
"for",
"the",
"GUI",
"current",
"structure",
"is",
":",
"File",
":",
"Change",
"Working",
"Directory",
"Import",
"Interpretations",
"from",
"LSQ",
"file",
"Import",
"interpretations",
"from",
"a",
"redo",
"file",
"Save",
"interpretati... | python | train |
blockcypher/blockcypher-python | blockcypher/api.py | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L1904-L1927 | def get_metadata(address=None, tx_hash=None, block_hash=None, api_key=None, private=True, coin_symbol='btc'):
'''
Get metadata using blockcypher's API.
This is data on blockcypher's servers and not embedded into the bitcoin (or other) blockchain.
'''
assert is_valid_coin_symbol(coin_symbol), coin_s... | [
"def",
"get_metadata",
"(",
"address",
"=",
"None",
",",
"tx_hash",
"=",
"None",
",",
"block_hash",
"=",
"None",
",",
"api_key",
"=",
"None",
",",
"private",
"=",
"True",
",",
"coin_symbol",
"=",
"'btc'",
")",
":",
"assert",
"is_valid_coin_symbol",
"(",
... | Get metadata using blockcypher's API.
This is data on blockcypher's servers and not embedded into the bitcoin (or other) blockchain. | [
"Get",
"metadata",
"using",
"blockcypher",
"s",
"API",
"."
] | python | train |
timknip/pyswf | swf/stream.py | https://github.com/timknip/pyswf/blob/3740cc80d7650156831e728ea0d408819e5671eb/swf/stream.py#L459-L468 | def readtag_header(self):
""" Read a tag header """
pos = self.tell()
tag_type_and_length = self.readUI16()
tag_length = tag_type_and_length & 0x003f
if tag_length == 0x3f:
# The SWF10 spec sez that this is a signed int.
# Shouldn't it be an unsigned int?
... | [
"def",
"readtag_header",
"(",
"self",
")",
":",
"pos",
"=",
"self",
".",
"tell",
"(",
")",
"tag_type_and_length",
"=",
"self",
".",
"readUI16",
"(",
")",
"tag_length",
"=",
"tag_type_and_length",
"&",
"0x003f",
"if",
"tag_length",
"==",
"0x3f",
":",
"# The... | Read a tag header | [
"Read",
"a",
"tag",
"header"
] | python | train |
benoitkugler/abstractDataLibrary | pyDLib/Core/controller.py | https://github.com/benoitkugler/abstractDataLibrary/blob/16be28e99837e40287a63803bbfdf67ac1806b7b/pyDLib/Core/controller.py#L322-L339 | def loggin(self, user_id, mdp, autolog):
"""Check mdp and return True it's ok"""
r = sql.abstractRequetesSQL.check_mdp_user(user_id, mdp)
if r():
# update auto-log params
self.autolog[user_id] = autolog and mdp or False
self.modules = self.users[user_id]["modu... | [
"def",
"loggin",
"(",
"self",
",",
"user_id",
",",
"mdp",
",",
"autolog",
")",
":",
"r",
"=",
"sql",
".",
"abstractRequetesSQL",
".",
"check_mdp_user",
"(",
"user_id",
",",
"mdp",
")",
"if",
"r",
"(",
")",
":",
"# update auto-log params",
"self",
".",
... | Check mdp and return True it's ok | [
"Check",
"mdp",
"and",
"return",
"True",
"it",
"s",
"ok"
] | python | train |
tjcsl/ion | intranet/apps/files/views.py | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/files/views.py#L102-L122 | def get_authinfo(request):
"""Get authentication info from the encrypted message."""
if (("files_iv" not in request.session) or ("files_text" not in request.session) or ("files_key" not in request.COOKIES)):
return False
"""
Decrypt the password given the SERVER-side IV, SERVER-side
... | [
"def",
"get_authinfo",
"(",
"request",
")",
":",
"if",
"(",
"(",
"\"files_iv\"",
"not",
"in",
"request",
".",
"session",
")",
"or",
"(",
"\"files_text\"",
"not",
"in",
"request",
".",
"session",
")",
"or",
"(",
"\"files_key\"",
"not",
"in",
"request",
".... | Get authentication info from the encrypted message. | [
"Get",
"authentication",
"info",
"from",
"the",
"encrypted",
"message",
"."
] | python | train |
Alveo/pyalveo | pyalveo/pyalveo.py | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L947-L959 | def get_items(self, collection_uri):
"""Return all items in this collection.
:param collection_uri: The URI that references the collection
:type collection_uri: String
:rtype: List
:returns: a list of the URIs of the items in this collection
"""
cname = os.pat... | [
"def",
"get_items",
"(",
"self",
",",
"collection_uri",
")",
":",
"cname",
"=",
"os",
".",
"path",
".",
"split",
"(",
"collection_uri",
")",
"[",
"1",
"]",
"return",
"self",
".",
"search_metadata",
"(",
"\"collection_name:%s\"",
"%",
"cname",
")"
] | Return all items in this collection.
:param collection_uri: The URI that references the collection
:type collection_uri: String
:rtype: List
:returns: a list of the URIs of the items in this collection | [
"Return",
"all",
"items",
"in",
"this",
"collection",
"."
] | python | train |
wdm0006/sklearn-extensions | sklearn_extensions/extreme_learning_machines/random_layer.py | https://github.com/wdm0006/sklearn-extensions/blob/329f3efdb8c3c3a367b264f7c76c76411a784530/sklearn_extensions/extreme_learning_machines/random_layer.py#L114-L132 | def transform(self, X, y=None):
"""Generate the random hidden layer's activations given X as input.
Parameters
----------
X : {array-like, sparse matrix}, shape [n_samples, n_features]
Data to transform
y : is not used: placeholder to allow for usage in a Pipeline.
... | [
"def",
"transform",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"if",
"(",
"self",
".",
"components_",
"is",
"None",
")",
":",
"raise",
"ValueError",
"(",
"'No components initialized'",
")",
"return",
"self",
".",
"_compute_hidden_activations",
... | Generate the random hidden layer's activations given X as input.
Parameters
----------
X : {array-like, sparse matrix}, shape [n_samples, n_features]
Data to transform
y : is not used: placeholder to allow for usage in a Pipeline.
Returns
-------
X_... | [
"Generate",
"the",
"random",
"hidden",
"layer",
"s",
"activations",
"given",
"X",
"as",
"input",
"."
] | python | train |
wummel/linkchecker | third_party/dnspython/dns/query.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/third_party/dnspython/dns/query.py#L48-L73 | def _poll_for(fd, readable, writable, error, timeout):
"""
@param fd: File descriptor (int).
@param readable: Whether to wait for readability (bool).
@param writable: Whether to wait for writability (bool).
@param expiration: Deadline timeout (expiration time, in seconds (float)).
@return True ... | [
"def",
"_poll_for",
"(",
"fd",
",",
"readable",
",",
"writable",
",",
"error",
",",
"timeout",
")",
":",
"event_mask",
"=",
"0",
"if",
"readable",
":",
"event_mask",
"|=",
"select",
".",
"POLLIN",
"if",
"writable",
":",
"event_mask",
"|=",
"select",
".",... | @param fd: File descriptor (int).
@param readable: Whether to wait for readability (bool).
@param writable: Whether to wait for writability (bool).
@param expiration: Deadline timeout (expiration time, in seconds (float)).
@return True on success, False on timeout | [
"@param",
"fd",
":",
"File",
"descriptor",
"(",
"int",
")",
".",
"@param",
"readable",
":",
"Whether",
"to",
"wait",
"for",
"readability",
"(",
"bool",
")",
".",
"@param",
"writable",
":",
"Whether",
"to",
"wait",
"for",
"writability",
"(",
"bool",
")",
... | python | train |
sorgerlab/indra | indra/tools/executable_subnetwork.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/executable_subnetwork.py#L47-L70 | def _filter_statements(statements, agents):
"""Return INDRA Statements which have Agents in the given list.
Only statements are returned in which all appearing Agents as in the
agents list.
Parameters
----------
statements : list[indra.statements.Statement]
A list of INDRA Statements t... | [
"def",
"_filter_statements",
"(",
"statements",
",",
"agents",
")",
":",
"filtered_statements",
"=",
"[",
"]",
"for",
"s",
"in",
"stmts",
":",
"if",
"all",
"(",
"[",
"a",
"is",
"not",
"None",
"for",
"a",
"in",
"s",
".",
"agent_list",
"(",
")",
"]",
... | Return INDRA Statements which have Agents in the given list.
Only statements are returned in which all appearing Agents as in the
agents list.
Parameters
----------
statements : list[indra.statements.Statement]
A list of INDRA Statements to filter.
agents : list[str]
A list of ... | [
"Return",
"INDRA",
"Statements",
"which",
"have",
"Agents",
"in",
"the",
"given",
"list",
"."
] | python | train |
idlesign/uwsgiconf | uwsgiconf/options/networking.py | https://github.com/idlesign/uwsgiconf/blob/475407acb44199edbf7e0a66261bfeb51de1afae/uwsgiconf/options/networking.py#L56-L81 | def set_socket_params(
self, send_timeout=None, keep_alive=None, no_defer_accept=None,
buffer_send=None, buffer_receive=None):
"""Sets common socket params.
:param int send_timeout: Send (write) timeout in seconds.
:param bool keep_alive: Enable TCP KEEPALIVEs.
... | [
"def",
"set_socket_params",
"(",
"self",
",",
"send_timeout",
"=",
"None",
",",
"keep_alive",
"=",
"None",
",",
"no_defer_accept",
"=",
"None",
",",
"buffer_send",
"=",
"None",
",",
"buffer_receive",
"=",
"None",
")",
":",
"self",
".",
"_set",
"(",
"'so-se... | Sets common socket params.
:param int send_timeout: Send (write) timeout in seconds.
:param bool keep_alive: Enable TCP KEEPALIVEs.
:param bool no_defer_accept: Disable deferred ``accept()`` on sockets
by default (where available) uWSGI will defer the accept() of requests until so... | [
"Sets",
"common",
"socket",
"params",
"."
] | python | train |
project-rig/rig | rig/machine_control/machine_controller.py | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/machine_control/machine_controller.py#L1590-L1646 | def wait_for_cores_to_reach_state(self, state, count, app_id,
poll_interval=0.1, timeout=None):
"""Block until the specified number of cores reach the specified state.
This is a simple utility-wrapper around the
:py:meth:`.count_cores_in_state` method which... | [
"def",
"wait_for_cores_to_reach_state",
"(",
"self",
",",
"state",
",",
"count",
",",
"app_id",
",",
"poll_interval",
"=",
"0.1",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"not",
"None",
":",
"timeout_time",
"=",
"time",
".",
"time",
... | Block until the specified number of cores reach the specified state.
This is a simple utility-wrapper around the
:py:meth:`.count_cores_in_state` method which polls the machine until
(at least) the supplied number of cores has reached the specified
state.
.. warning::
... | [
"Block",
"until",
"the",
"specified",
"number",
"of",
"cores",
"reach",
"the",
"specified",
"state",
"."
] | python | train |
mlenzen/collections-extended | collections_extended/setlists.py | https://github.com/mlenzen/collections-extended/blob/ee9e86f6bbef442dbebcb3a5970642c5c969e2cf/collections_extended/setlists.py#L506-L515 | def symmetric_difference_update(self, other):
"""Update self to include only the symmetric difference with other."""
other = setlist(other)
indices_to_delete = set()
for i, item in enumerate(self):
if item in other:
indices_to_delete.add(i)
for item in other:
self.add(item)
self._delete_values_by_... | [
"def",
"symmetric_difference_update",
"(",
"self",
",",
"other",
")",
":",
"other",
"=",
"setlist",
"(",
"other",
")",
"indices_to_delete",
"=",
"set",
"(",
")",
"for",
"i",
",",
"item",
"in",
"enumerate",
"(",
"self",
")",
":",
"if",
"item",
"in",
"ot... | Update self to include only the symmetric difference with other. | [
"Update",
"self",
"to",
"include",
"only",
"the",
"symmetric",
"difference",
"with",
"other",
"."
] | python | train |
aws/sagemaker-python-sdk | src/sagemaker/predictor.py | https://github.com/aws/sagemaker-python-sdk/blob/a9e724c7d3f5572b68c3903548c792a59d99799a/src/sagemaker/predictor.py#L131-L146 | def delete_model(self):
"""Deletes the Amazon SageMaker models backing this predictor.
"""
request_failed = False
failed_models = []
for model_name in self._model_names:
try:
self.sagemaker_session.delete_model(model_name)
except Exception... | [
"def",
"delete_model",
"(",
"self",
")",
":",
"request_failed",
"=",
"False",
"failed_models",
"=",
"[",
"]",
"for",
"model_name",
"in",
"self",
".",
"_model_names",
":",
"try",
":",
"self",
".",
"sagemaker_session",
".",
"delete_model",
"(",
"model_name",
"... | Deletes the Amazon SageMaker models backing this predictor. | [
"Deletes",
"the",
"Amazon",
"SageMaker",
"models",
"backing",
"this",
"predictor",
"."
] | python | train |
SeattleTestbed/seash | seash_helper.py | https://github.com/SeattleTestbed/seash/blob/40f9d2285662ff8b61e0468b4196acee089b273b/seash_helper.py#L79-L109 | def local_updatetime(port):
"""
<Purpose>
Callback for time_interface.r2py to update the time that is used
internally for nodemanager communications.
<Arguments>
port:
The port to update on. This is not used however. It is only
specified to adhere to the function signature expected ... | [
"def",
"local_updatetime",
"(",
"port",
")",
":",
"print",
"'Time update failed, could not connect to any time servers...'",
"print",
"'Your network connection may be down.'",
"print",
"\"Falling back to using your computer's local clock.\"",
"print",
"# time.time() gives us the # of secon... | <Purpose>
Callback for time_interface.r2py to update the time that is used
internally for nodemanager communications.
<Arguments>
port:
The port to update on. This is not used however. It is only
specified to adhere to the function signature expected by
time_interface.r2py.
<... | [
"<Purpose",
">",
"Callback",
"for",
"time_interface",
".",
"r2py",
"to",
"update",
"the",
"time",
"that",
"is",
"used",
"internally",
"for",
"nodemanager",
"communications",
"."
] | python | train |
inveniosoftware-attic/invenio-utils | invenio_utils/html.py | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/html.py#L498-L658 | def get_html_text_editor(
name,
id=None,
content='',
textual_content=None,
width='300px',
height='200px',
enabled=True,
file_upload_url=None,
toolbar_set="Basic",
custom_configurations_path='/js/ckeditor/invenio-ckeditor-config.js',
... | [
"def",
"get_html_text_editor",
"(",
"name",
",",
"id",
"=",
"None",
",",
"content",
"=",
"''",
",",
"textual_content",
"=",
"None",
",",
"width",
"=",
"'300px'",
",",
"height",
"=",
"'200px'",
",",
"enabled",
"=",
"True",
",",
"file_upload_url",
"=",
"No... | Returns a wysiwyg editor (CKEditor) to embed in html pages.
Fall back to a simple textarea when the library is not installed,
or when the user's browser is not compatible with the editor, or
when 'enable' is False, or when javascript is not enabled.
NOTE that the output also contains a hidden field na... | [
"Returns",
"a",
"wysiwyg",
"editor",
"(",
"CKEditor",
")",
"to",
"embed",
"in",
"html",
"pages",
"."
] | python | train |
cpenv/cpenv | cpenv/resolver.py | https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/resolver.py#L207-L223 | def redirect_resolver(resolver, path):
'''Resolves environment from .cpenv file...recursively walks up the tree
in attempt to find a .cpenv file'''
if not os.path.exists(path):
raise ResolveError
if os.path.isfile(path):
path = os.path.dirname(path)
for root, _, _ in walk_up(path)... | [
"def",
"redirect_resolver",
"(",
"resolver",
",",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"raise",
"ResolveError",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"path",
"=",
"os",
"."... | Resolves environment from .cpenv file...recursively walks up the tree
in attempt to find a .cpenv file | [
"Resolves",
"environment",
"from",
".",
"cpenv",
"file",
"...",
"recursively",
"walks",
"up",
"the",
"tree",
"in",
"attempt",
"to",
"find",
"a",
".",
"cpenv",
"file"
] | python | valid |
tjcsl/ion | intranet/apps/announcements/views.py | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/announcements/views.py#L387-L405 | def hide_announcement_view(request):
""" Hide an announcement for the logged-in user.
announcements_hidden in the user model is the related_name for
"users_hidden" in the announcement model.
"""
if request.method == "POST":
announcement_id = request.POST.get("announcement_id")
... | [
"def",
"hide_announcement_view",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"announcement_id",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"\"announcement_id\"",
")",
"if",
"announcement_id",
":",
"announcement",
"=",
"A... | Hide an announcement for the logged-in user.
announcements_hidden in the user model is the related_name for
"users_hidden" in the announcement model. | [
"Hide",
"an",
"announcement",
"for",
"the",
"logged",
"-",
"in",
"user",
"."
] | python | train |
hosford42/xcs | xcs/scenarios.py | https://github.com/hosford42/xcs/blob/183bdd0dd339e19ded3be202f86e1b38bdb9f1e5/xcs/scenarios.py#L898-L915 | def get_classifications(self):
"""Return the classifications made by the algorithm for this
scenario.
Usage:
model.run(scenario, learn=False)
classifications = scenario.get_classifications()
Arguments: None
Return:
An indexable sequence conta... | [
"def",
"get_classifications",
"(",
"self",
")",
":",
"if",
"bitstrings",
".",
"using_numpy",
"(",
")",
":",
"return",
"numpy",
".",
"array",
"(",
"self",
".",
"classifications",
")",
"else",
":",
"return",
"self",
".",
"classifications"
] | Return the classifications made by the algorithm for this
scenario.
Usage:
model.run(scenario, learn=False)
classifications = scenario.get_classifications()
Arguments: None
Return:
An indexable sequence containing the classifications made by
... | [
"Return",
"the",
"classifications",
"made",
"by",
"the",
"algorithm",
"for",
"this",
"scenario",
"."
] | python | train |
ttinies/sc2gameLobby | sc2gameLobby/gameConfig.py | https://github.com/ttinies/sc2gameLobby/blob/5352d51d53ddeb4858e92e682da89c4434123e52/sc2gameLobby/gameConfig.py#L489-L504 | def requestCreateDetails(self):
"""add configuration to the SC2 protocol create request"""
createReq = sc_pb.RequestCreateGame( # used to advance to Status.initGame state, when hosting
realtime = self.realtime,
disable_fog = self.fogDisabled,
random_seed = int(time... | [
"def",
"requestCreateDetails",
"(",
"self",
")",
":",
"createReq",
"=",
"sc_pb",
".",
"RequestCreateGame",
"(",
"# used to advance to Status.initGame state, when hosting",
"realtime",
"=",
"self",
".",
"realtime",
",",
"disable_fog",
"=",
"self",
".",
"fogDisabled",
"... | add configuration to the SC2 protocol create request | [
"add",
"configuration",
"to",
"the",
"SC2",
"protocol",
"create",
"request"
] | python | train |
pandas-dev/pandas | pandas/core/generic.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L5932-L5977 | def infer_objects(self):
"""
Attempt to infer better dtypes for object columns.
Attempts soft conversion of object-dtyped
columns, leaving non-object and unconvertible
columns unchanged. The inference rules are the
same as during normal Series/DataFrame construction.
... | [
"def",
"infer_objects",
"(",
"self",
")",
":",
"# numeric=False necessary to only soft convert;",
"# python objects will still be converted to",
"# native numpy numeric types",
"return",
"self",
".",
"_constructor",
"(",
"self",
".",
"_data",
".",
"convert",
"(",
"datetime",
... | Attempt to infer better dtypes for object columns.
Attempts soft conversion of object-dtyped
columns, leaving non-object and unconvertible
columns unchanged. The inference rules are the
same as during normal Series/DataFrame construction.
.. versionadded:: 0.21.0
Retur... | [
"Attempt",
"to",
"infer",
"better",
"dtypes",
"for",
"object",
"columns",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/symmetry/analyzer.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/symmetry/analyzer.py#L1370-L1416 | def symmetrize_molecule(self):
"""Returns a symmetrized molecule
The equivalent atoms obtained via
:meth:`~pymatgen.symmetry.analyzer.PointGroupAnalyzer.get_equivalent_atoms`
are rotated, mirrored... unto one position.
Then the average position is calculated.
The average... | [
"def",
"symmetrize_molecule",
"(",
"self",
")",
":",
"eq",
"=",
"self",
".",
"get_equivalent_atoms",
"(",
")",
"eq_sets",
",",
"ops",
"=",
"eq",
"[",
"'eq_sets'",
"]",
",",
"eq",
"[",
"'sym_ops'",
"]",
"coords",
"=",
"self",
".",
"centered_mol",
".",
"... | Returns a symmetrized molecule
The equivalent atoms obtained via
:meth:`~pymatgen.symmetry.analyzer.PointGroupAnalyzer.get_equivalent_atoms`
are rotated, mirrored... unto one position.
Then the average position is calculated.
The average position is rotated, mirrored... back wit... | [
"Returns",
"a",
"symmetrized",
"molecule"
] | python | train |
DLR-RM/RAFCON | share/examples/plugins/templates/core_template_observer.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/share/examples/plugins/templates/core_template_observer.py#L47-L55 | def register_states_of_state_machine(self, state_machine):
""" This functions registers all states of state machine.
:param state_machine: the state machine to register all states of
:return:
"""
root = state_machine.root_state
root.add_observer(self, "state_execution_sta... | [
"def",
"register_states_of_state_machine",
"(",
"self",
",",
"state_machine",
")",
":",
"root",
"=",
"state_machine",
".",
"root_state",
"root",
".",
"add_observer",
"(",
"self",
",",
"\"state_execution_status\"",
",",
"notify_after_function",
"=",
"self",
".",
"on_... | This functions registers all states of state machine.
:param state_machine: the state machine to register all states of
:return: | [
"This",
"functions",
"registers",
"all",
"states",
"of",
"state",
"machine",
".",
":",
"param",
"state_machine",
":",
"the",
"state",
"machine",
"to",
"register",
"all",
"states",
"of",
":",
"return",
":"
] | python | train |
saltstack/salt | salt/utils/vmware.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vmware.py#L125-L179 | def esxcli(host, user, pwd, cmd, protocol=None, port=None, esxi_host=None, credstore=None):
'''
Shell out and call the specified esxcli commmand, parse the result
and return something sane.
:param host: ESXi or vCenter host to connect to
:param user: User to connect as, usually root
:param pwd:... | [
"def",
"esxcli",
"(",
"host",
",",
"user",
",",
"pwd",
",",
"cmd",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"esxi_host",
"=",
"None",
",",
"credstore",
"=",
"None",
")",
":",
"esx_cmd",
"=",
"salt",
".",
"utils",
".",
"path",
... | Shell out and call the specified esxcli commmand, parse the result
and return something sane.
:param host: ESXi or vCenter host to connect to
:param user: User to connect as, usually root
:param pwd: Password to connect with
:param port: TCP port
:param cmd: esxcli command and arguments
:pa... | [
"Shell",
"out",
"and",
"call",
"the",
"specified",
"esxcli",
"commmand",
"parse",
"the",
"result",
"and",
"return",
"something",
"sane",
"."
] | python | train |
joyent/python-manta | manta/client.py | https://github.com/joyent/python-manta/blob/f68ef142bdbac058c981e3b28e18d77612f5b7c6/manta/client.py#L483-L496 | def add_job_inputs(self, job_id, keys):
"""AddJobInputs
https://apidocs.joyent.com/manta/api.html#AddJobInputs
"""
log.debug("AddJobInputs %r", job_id)
path = "/%s/jobs/%s/live/in" % (self.account, job_id)
body = '\r\n'.join(keys) + '\r\n'
headers = {
... | [
"def",
"add_job_inputs",
"(",
"self",
",",
"job_id",
",",
"keys",
")",
":",
"log",
".",
"debug",
"(",
"\"AddJobInputs %r\"",
",",
"job_id",
")",
"path",
"=",
"\"/%s/jobs/%s/live/in\"",
"%",
"(",
"self",
".",
"account",
",",
"job_id",
")",
"body",
"=",
"'... | AddJobInputs
https://apidocs.joyent.com/manta/api.html#AddJobInputs | [
"AddJobInputs",
"https",
":",
"//",
"apidocs",
".",
"joyent",
".",
"com",
"/",
"manta",
"/",
"api",
".",
"html#AddJobInputs"
] | python | train |
LordGaav/python-chaos | chaos/amqp/rpc.py | https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/amqp/rpc.py#L304-L320 | def reply(self, original_headers, message, properties=None):
"""
Reply to a RPC request. This function will use the default exchange, to directly contact the reply_to queue.
Parameters
----------
original_headers: dict
The headers of the originating message that caused this reply.
message: string
Mes... | [
"def",
"reply",
"(",
"self",
",",
"original_headers",
",",
"message",
",",
"properties",
"=",
"None",
")",
":",
"rpc_reply",
"(",
"self",
".",
"channel",
",",
"original_headers",
",",
"message",
",",
"properties",
")"
] | Reply to a RPC request. This function will use the default exchange, to directly contact the reply_to queue.
Parameters
----------
original_headers: dict
The headers of the originating message that caused this reply.
message: string
Message to reply with
properties: dict
Properties to set on message... | [
"Reply",
"to",
"a",
"RPC",
"request",
".",
"This",
"function",
"will",
"use",
"the",
"default",
"exchange",
"to",
"directly",
"contact",
"the",
"reply_to",
"queue",
"."
] | python | train |
madzak/python-json-logger | src/pythonjsonlogger/jsonlogger.py | https://github.com/madzak/python-json-logger/blob/687cc52260876fd2189cbb7c5856e3fbaff65279/src/pythonjsonlogger/jsonlogger.py#L136-L144 | def parse(self):
"""
Parses format string looking for substitutions
This method is responsible for returning a list of fields (as strings)
to include in all log messages.
"""
standard_formatters = re.compile(r'\((.+?)\)', re.IGNORECASE)
return standard_formatters... | [
"def",
"parse",
"(",
"self",
")",
":",
"standard_formatters",
"=",
"re",
".",
"compile",
"(",
"r'\\((.+?)\\)'",
",",
"re",
".",
"IGNORECASE",
")",
"return",
"standard_formatters",
".",
"findall",
"(",
"self",
".",
"_fmt",
")"
] | Parses format string looking for substitutions
This method is responsible for returning a list of fields (as strings)
to include in all log messages. | [
"Parses",
"format",
"string",
"looking",
"for",
"substitutions"
] | python | train |
OSSOS/MOP | src/ossos/core/ossos/storage.py | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1366-L1383 | def get_property(node_uri, property_name, ossos_base=True):
"""
Retrieves the value associated with a property on a node in VOSpace.
@param node_uri:
@param property_name:
@param ossos_base:
@return:
"""
# Must use force or we could have a cached copy of the node from before
# prope... | [
"def",
"get_property",
"(",
"node_uri",
",",
"property_name",
",",
"ossos_base",
"=",
"True",
")",
":",
"# Must use force or we could have a cached copy of the node from before",
"# properties of interest were set/updated.",
"node",
"=",
"client",
".",
"get_node",
"(",
"node_... | Retrieves the value associated with a property on a node in VOSpace.
@param node_uri:
@param property_name:
@param ossos_base:
@return: | [
"Retrieves",
"the",
"value",
"associated",
"with",
"a",
"property",
"on",
"a",
"node",
"in",
"VOSpace",
"."
] | python | train |
python-gitlab/python-gitlab | gitlab/mixins.py | https://github.com/python-gitlab/python-gitlab/blob/16de1b03fde3dbbe8f851614dd1d8c09de102fe5/gitlab/mixins.py#L602-L619 | def render(self, link_url, image_url, **kwargs):
"""Preview link_url and image_url after interpolation.
Args:
link_url (str): URL of the badge link
image_url (str): URL of the badge image
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
... | [
"def",
"render",
"(",
"self",
",",
"link_url",
",",
"image_url",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"'%s/render'",
"%",
"self",
".",
"path",
"data",
"=",
"{",
"'link_url'",
":",
"link_url",
",",
"'image_url'",
":",
"image_url",
"}",
"retur... | Preview link_url and image_url after interpolation.
Args:
link_url (str): URL of the badge link
image_url (str): URL of the badge image
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not ... | [
"Preview",
"link_url",
"and",
"image_url",
"after",
"interpolation",
"."
] | python | train |
danilobellini/audiolazy | audiolazy/lazy_misc.py | https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_misc.py#L70-L125 | def blocks(seq, size=None, hop=None, padval=0.):
"""
General iterable blockenizer.
Generator that gets ``size`` elements from ``seq``, and outputs them in a
collections.deque (mutable circular queue) sequence container. Next output
starts ``hop`` elements after the first element in last output block. Last
... | [
"def",
"blocks",
"(",
"seq",
",",
"size",
"=",
"None",
",",
"hop",
"=",
"None",
",",
"padval",
"=",
"0.",
")",
":",
"# Initialization",
"res",
"=",
"deque",
"(",
"maxlen",
"=",
"size",
")",
"# Circular queue",
"idx",
"=",
"0",
"last_idx",
"=",
"size"... | General iterable blockenizer.
Generator that gets ``size`` elements from ``seq``, and outputs them in a
collections.deque (mutable circular queue) sequence container. Next output
starts ``hop`` elements after the first element in last output block. Last
block may be appended with ``padval``, if needed to get t... | [
"General",
"iterable",
"blockenizer",
"."
] | python | train |
saltstack/salt | salt/state.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L677-L711 | def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in e... | [
"def",
"apply_exclude",
"(",
"self",
",",
"high",
")",
":",
"if",
"'__exclude__'",
"not",
"in",
"high",
":",
"return",
"high",
"ex_sls",
"=",
"set",
"(",
")",
"ex_id",
"=",
"set",
"(",
")",
"exclude",
"=",
"high",
".",
"pop",
"(",
"'__exclude__'",
")... | Read in the __exclude__ list and remove all excluded objects from the
high data | [
"Read",
"in",
"the",
"__exclude__",
"list",
"and",
"remove",
"all",
"excluded",
"objects",
"from",
"the",
"high",
"data"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.