repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
sporsh/carnifex | carnifex/sshprocess.py | SSHProcessInductor._getUserAuthObject | def _getUserAuthObject(self, user, connection):
"""Get a SSHUserAuthClient object to use for authentication
@param user: The username to authenticate for
@param connection: The connection service to start after authentication
"""
credentials = self._getCredentials(user)
... | python | def _getUserAuthObject(self, user, connection):
"""Get a SSHUserAuthClient object to use for authentication
@param user: The username to authenticate for
@param connection: The connection service to start after authentication
"""
credentials = self._getCredentials(user)
... | [
"def",
"_getUserAuthObject",
"(",
"self",
",",
"user",
",",
"connection",
")",
":",
"credentials",
"=",
"self",
".",
"_getCredentials",
"(",
"user",
")",
"userAuthObject",
"=",
"AutomaticUserAuthClient",
"(",
"user",
",",
"connection",
",",
"*",
"*",
"credenti... | Get a SSHUserAuthClient object to use for authentication
@param user: The username to authenticate for
@param connection: The connection service to start after authentication | [
"Get",
"a",
"SSHUserAuthClient",
"object",
"to",
"use",
"for",
"authentication"
] | 82dd3bd2bc134dfb69a78f43171e227f2127060b | https://github.com/sporsh/carnifex/blob/82dd3bd2bc134dfb69a78f43171e227f2127060b/carnifex/sshprocess.py#L140-L148 | train | 56,100 |
sporsh/carnifex | carnifex/sshprocess.py | SSHProcessInductor._verifyHostKey | def _verifyHostKey(self, hostKey, fingerprint):
"""Called when ssh transport requests us to verify a given host key.
Return a deferred that callback if we accept the key or errback if we
decide to reject it.
"""
if fingerprint in self.knownHosts:
return defer.succeed(... | python | def _verifyHostKey(self, hostKey, fingerprint):
"""Called when ssh transport requests us to verify a given host key.
Return a deferred that callback if we accept the key or errback if we
decide to reject it.
"""
if fingerprint in self.knownHosts:
return defer.succeed(... | [
"def",
"_verifyHostKey",
"(",
"self",
",",
"hostKey",
",",
"fingerprint",
")",
":",
"if",
"fingerprint",
"in",
"self",
".",
"knownHosts",
":",
"return",
"defer",
".",
"succeed",
"(",
"True",
")",
"return",
"defer",
".",
"fail",
"(",
"UnknownHostKey",
"(",
... | Called when ssh transport requests us to verify a given host key.
Return a deferred that callback if we accept the key or errback if we
decide to reject it. | [
"Called",
"when",
"ssh",
"transport",
"requests",
"us",
"to",
"verify",
"a",
"given",
"host",
"key",
".",
"Return",
"a",
"deferred",
"that",
"callback",
"if",
"we",
"accept",
"the",
"key",
"or",
"errback",
"if",
"we",
"decide",
"to",
"reject",
"it",
"."
... | 82dd3bd2bc134dfb69a78f43171e227f2127060b | https://github.com/sporsh/carnifex/blob/82dd3bd2bc134dfb69a78f43171e227f2127060b/carnifex/sshprocess.py#L150-L157 | train | 56,101 |
coala/coala-decorators-USE-cOALA-UTILS-INSTEAD | coala_decorators/__init__.py | yield_once | def yield_once(iterator):
"""
Decorator to make an iterator returned by a method yield each result only
once.
>>> @yield_once
... def generate_list(foo):
... return foo
>>> list(generate_list([1, 2, 1]))
[1, 2]
:param iterator: Any method that returns an iterator
:return: ... | python | def yield_once(iterator):
"""
Decorator to make an iterator returned by a method yield each result only
once.
>>> @yield_once
... def generate_list(foo):
... return foo
>>> list(generate_list([1, 2, 1]))
[1, 2]
:param iterator: Any method that returns an iterator
:return: ... | [
"def",
"yield_once",
"(",
"iterator",
")",
":",
"@",
"wraps",
"(",
"iterator",
")",
"def",
"yield_once_generator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"yielded",
"=",
"set",
"(",
")",
"for",
"item",
"in",
"iterator",
"(",
"*",
"args"... | Decorator to make an iterator returned by a method yield each result only
once.
>>> @yield_once
... def generate_list(foo):
... return foo
>>> list(generate_list([1, 2, 1]))
[1, 2]
:param iterator: Any method that returns an iterator
:return: An method returning an iterator... | [
"Decorator",
"to",
"make",
"an",
"iterator",
"returned",
"by",
"a",
"method",
"yield",
"each",
"result",
"only",
"once",
"."
] | b1c4463f364bbcd0ad5138f697a52f11c9afe326 | https://github.com/coala/coala-decorators-USE-cOALA-UTILS-INSTEAD/blob/b1c4463f364bbcd0ad5138f697a52f11c9afe326/coala_decorators/__init__.py#L6-L29 | train | 56,102 |
coala/coala-decorators-USE-cOALA-UTILS-INSTEAD | coala_decorators/__init__.py | _to_list | def _to_list(var):
"""
Make variable to list.
>>> _to_list(None)
[]
>>> _to_list('whee')
['whee']
>>> _to_list([None])
[None]
>>> _to_list((1, 2, 3))
[1, 2, 3]
:param var: variable of any type
:return: list
"""
if isinstance(var, list):
return var
... | python | def _to_list(var):
"""
Make variable to list.
>>> _to_list(None)
[]
>>> _to_list('whee')
['whee']
>>> _to_list([None])
[None]
>>> _to_list((1, 2, 3))
[1, 2, 3]
:param var: variable of any type
:return: list
"""
if isinstance(var, list):
return var
... | [
"def",
"_to_list",
"(",
"var",
")",
":",
"if",
"isinstance",
"(",
"var",
",",
"list",
")",
":",
"return",
"var",
"elif",
"var",
"is",
"None",
":",
"return",
"[",
"]",
"elif",
"isinstance",
"(",
"var",
",",
"str",
")",
"or",
"isinstance",
"(",
"var"... | Make variable to list.
>>> _to_list(None)
[]
>>> _to_list('whee')
['whee']
>>> _to_list([None])
[None]
>>> _to_list((1, 2, 3))
[1, 2, 3]
:param var: variable of any type
:return: list | [
"Make",
"variable",
"to",
"list",
"."
] | b1c4463f364bbcd0ad5138f697a52f11c9afe326 | https://github.com/coala/coala-decorators-USE-cOALA-UTILS-INSTEAD/blob/b1c4463f364bbcd0ad5138f697a52f11c9afe326/coala_decorators/__init__.py#L32-L59 | train | 56,103 |
coala/coala-decorators-USE-cOALA-UTILS-INSTEAD | coala_decorators/__init__.py | arguments_to_lists | def arguments_to_lists(function):
"""
Decorator for a function that converts all arguments to lists.
:param function: target function
:return: target function with only lists as parameters
"""
def l_function(*args, **kwargs):
l_args = [_to_list(arg) for arg in args]
l_kw... | python | def arguments_to_lists(function):
"""
Decorator for a function that converts all arguments to lists.
:param function: target function
:return: target function with only lists as parameters
"""
def l_function(*args, **kwargs):
l_args = [_to_list(arg) for arg in args]
l_kw... | [
"def",
"arguments_to_lists",
"(",
"function",
")",
":",
"def",
"l_function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"l_args",
"=",
"[",
"_to_list",
"(",
"arg",
")",
"for",
"arg",
"in",
"args",
"]",
"l_kwargs",
"=",
"{",
"}",
"for",
"k... | Decorator for a function that converts all arguments to lists.
:param function: target function
:return: target function with only lists as parameters | [
"Decorator",
"for",
"a",
"function",
"that",
"converts",
"all",
"arguments",
"to",
"lists",
"."
] | b1c4463f364bbcd0ad5138f697a52f11c9afe326 | https://github.com/coala/coala-decorators-USE-cOALA-UTILS-INSTEAD/blob/b1c4463f364bbcd0ad5138f697a52f11c9afe326/coala_decorators/__init__.py#L62-L77 | train | 56,104 |
coala/coala-decorators-USE-cOALA-UTILS-INSTEAD | coala_decorators/__init__.py | generate_eq | def generate_eq(*members):
"""
Decorator that generates equality and inequality operators for the
decorated class. The given members as well as the type of self and other
will be taken into account.
Note that this decorator modifies the given class in place!
:param members: A list of members t... | python | def generate_eq(*members):
"""
Decorator that generates equality and inequality operators for the
decorated class. The given members as well as the type of self and other
will be taken into account.
Note that this decorator modifies the given class in place!
:param members: A list of members t... | [
"def",
"generate_eq",
"(",
"*",
"members",
")",
":",
"def",
"decorator",
"(",
"cls",
")",
":",
"def",
"eq",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"cls",
")",
":",
"return",
"False",
"return",
"all",
"(",... | Decorator that generates equality and inequality operators for the
decorated class. The given members as well as the type of self and other
will be taken into account.
Note that this decorator modifies the given class in place!
:param members: A list of members to compare for equality. | [
"Decorator",
"that",
"generates",
"equality",
"and",
"inequality",
"operators",
"for",
"the",
"decorated",
"class",
".",
"The",
"given",
"members",
"as",
"well",
"as",
"the",
"type",
"of",
"self",
"and",
"other",
"will",
"be",
"taken",
"into",
"account",
"."... | b1c4463f364bbcd0ad5138f697a52f11c9afe326 | https://github.com/coala/coala-decorators-USE-cOALA-UTILS-INSTEAD/blob/b1c4463f364bbcd0ad5138f697a52f11c9afe326/coala_decorators/__init__.py#L196-L221 | train | 56,105 |
coala/coala-decorators-USE-cOALA-UTILS-INSTEAD | coala_decorators/__init__.py | enforce_signature | def enforce_signature(function):
"""
Enforces the signature of the function by throwing TypeError's if invalid
arguments are provided. The return value is not checked.
You can annotate any parameter of your function with the desired type or a
tuple of allowed types. If you annotate the function wit... | python | def enforce_signature(function):
"""
Enforces the signature of the function by throwing TypeError's if invalid
arguments are provided. The return value is not checked.
You can annotate any parameter of your function with the desired type or a
tuple of allowed types. If you annotate the function wit... | [
"def",
"enforce_signature",
"(",
"function",
")",
":",
"argspec",
"=",
"inspect",
".",
"getfullargspec",
"(",
"function",
")",
"annotations",
"=",
"argspec",
".",
"annotations",
"argnames",
"=",
"argspec",
".",
"args",
"unnamed_annotations",
"=",
"{",
"}",
"fo... | Enforces the signature of the function by throwing TypeError's if invalid
arguments are provided. The return value is not checked.
You can annotate any parameter of your function with the desired type or a
tuple of allowed types. If you annotate the function with a value, this
value only will be allowe... | [
"Enforces",
"the",
"signature",
"of",
"the",
"function",
"by",
"throwing",
"TypeError",
"s",
"if",
"invalid",
"arguments",
"are",
"provided",
".",
"The",
"return",
"value",
"is",
"not",
"checked",
"."
] | b1c4463f364bbcd0ad5138f697a52f11c9afe326 | https://github.com/coala/coala-decorators-USE-cOALA-UTILS-INSTEAD/blob/b1c4463f364bbcd0ad5138f697a52f11c9afe326/coala_decorators/__init__.py#L277-L317 | train | 56,106 |
nicferrier/md | src/mdlib/api.py | MdMessage.as_string | def as_string(self):
"""Get the underlying message object as a string"""
if self.headers_only:
self.msgobj = self._get_content()
# We could just use msgobj.as_string() but this is more flexible... we might need it.
from email.generator import Generator
fp = StringIO(... | python | def as_string(self):
"""Get the underlying message object as a string"""
if self.headers_only:
self.msgobj = self._get_content()
# We could just use msgobj.as_string() but this is more flexible... we might need it.
from email.generator import Generator
fp = StringIO(... | [
"def",
"as_string",
"(",
"self",
")",
":",
"if",
"self",
".",
"headers_only",
":",
"self",
".",
"msgobj",
"=",
"self",
".",
"_get_content",
"(",
")",
"# We could just use msgobj.as_string() but this is more flexible... we might need it.",
"from",
"email",
".",
"genera... | Get the underlying message object as a string | [
"Get",
"the",
"underlying",
"message",
"object",
"as",
"a",
"string"
] | 302ca8882dae060fb15bd5ae470d8e661fb67ec4 | https://github.com/nicferrier/md/blob/302ca8882dae060fb15bd5ae470d8e661fb67ec4/src/mdlib/api.py#L94-L105 | train | 56,107 |
nicferrier/md | src/mdlib/api.py | MdMessage.iteritems | def iteritems(self):
"""Present the email headers"""
for n,v in self.msgobj.__dict__["_headers"]:
yield n.lower(), v
return | python | def iteritems(self):
"""Present the email headers"""
for n,v in self.msgobj.__dict__["_headers"]:
yield n.lower(), v
return | [
"def",
"iteritems",
"(",
"self",
")",
":",
"for",
"n",
",",
"v",
"in",
"self",
".",
"msgobj",
".",
"__dict__",
"[",
"\"_headers\"",
"]",
":",
"yield",
"n",
".",
"lower",
"(",
")",
",",
"v",
"return"
] | Present the email headers | [
"Present",
"the",
"email",
"headers"
] | 302ca8882dae060fb15bd5ae470d8e661fb67ec4 | https://github.com/nicferrier/md/blob/302ca8882dae060fb15bd5ae470d8e661fb67ec4/src/mdlib/api.py#L129-L133 | train | 56,108 |
nicferrier/md | src/mdlib/api.py | MdMessage._set_flag | def _set_flag(self, flag):
"""Turns the specified flag on"""
self.folder._invalidate_cache()
# TODO::: turn the flag off when it's already on
def replacer(m):
return "%s/%s.%s%s" % (
joinpath(self.folder.base, self.folder.folder, "cur"),
m.grou... | python | def _set_flag(self, flag):
"""Turns the specified flag on"""
self.folder._invalidate_cache()
# TODO::: turn the flag off when it's already on
def replacer(m):
return "%s/%s.%s%s" % (
joinpath(self.folder.base, self.folder.folder, "cur"),
m.grou... | [
"def",
"_set_flag",
"(",
"self",
",",
"flag",
")",
":",
"self",
".",
"folder",
".",
"_invalidate_cache",
"(",
")",
"# TODO::: turn the flag off when it's already on",
"def",
"replacer",
"(",
"m",
")",
":",
"return",
"\"%s/%s.%s%s\"",
"%",
"(",
"joinpath",
"(",
... | Turns the specified flag on | [
"Turns",
"the",
"specified",
"flag",
"on"
] | 302ca8882dae060fb15bd5ae470d8e661fb67ec4 | https://github.com/nicferrier/md/blob/302ca8882dae060fb15bd5ae470d8e661fb67ec4/src/mdlib/api.py#L143-L159 | train | 56,109 |
nicferrier/md | src/mdlib/api.py | _KeysCache._get_message | def _get_message(self, key, since=None):
"""Return the MdMessage object for the key.
The object is either returned from the cache in the store or
made, cached and then returned.
If 'since' is passed in the modification time of the file is
checked and the message is only returne... | python | def _get_message(self, key, since=None):
"""Return the MdMessage object for the key.
The object is either returned from the cache in the store or
made, cached and then returned.
If 'since' is passed in the modification time of the file is
checked and the message is only returne... | [
"def",
"_get_message",
"(",
"self",
",",
"key",
",",
"since",
"=",
"None",
")",
":",
"stored",
"=",
"self",
".",
"store",
"[",
"key",
"]",
"if",
"isinstance",
"(",
"stored",
",",
"dict",
")",
":",
"filename",
"=",
"stored",
"[",
"\"path\"",
"]",
"f... | Return the MdMessage object for the key.
The object is either returned from the cache in the store or
made, cached and then returned.
If 'since' is passed in the modification time of the file is
checked and the message is only returned if the mtime is since
the specified time. ... | [
"Return",
"the",
"MdMessage",
"object",
"for",
"the",
"key",
"."
] | 302ca8882dae060fb15bd5ae470d8e661fb67ec4 | https://github.com/nicferrier/md/blob/302ca8882dae060fb15bd5ae470d8e661fb67ec4/src/mdlib/api.py#L209-L244 | train | 56,110 |
nicferrier/md | src/mdlib/api.py | MdFolder._foldername | def _foldername(self, additionalpath=""):
"""Dot decorate a folder name."""
if not self._foldername_cache.get(additionalpath):
fn = joinpath(self.base, self.folder, additionalpath) \
if not self.is_subfolder \
else joinpath(self.base, ".%s" % self.folder, addi... | python | def _foldername(self, additionalpath=""):
"""Dot decorate a folder name."""
if not self._foldername_cache.get(additionalpath):
fn = joinpath(self.base, self.folder, additionalpath) \
if not self.is_subfolder \
else joinpath(self.base, ".%s" % self.folder, addi... | [
"def",
"_foldername",
"(",
"self",
",",
"additionalpath",
"=",
"\"\"",
")",
":",
"if",
"not",
"self",
".",
"_foldername_cache",
".",
"get",
"(",
"additionalpath",
")",
":",
"fn",
"=",
"joinpath",
"(",
"self",
".",
"base",
",",
"self",
".",
"folder",
",... | Dot decorate a folder name. | [
"Dot",
"decorate",
"a",
"folder",
"name",
"."
] | 302ca8882dae060fb15bd5ae470d8e661fb67ec4 | https://github.com/nicferrier/md/blob/302ca8882dae060fb15bd5ae470d8e661fb67ec4/src/mdlib/api.py#L298-L305 | train | 56,111 |
nicferrier/md | src/mdlib/api.py | MdFolder.folders | def folders(self):
"""Return a map of the subfolder objects for this folder.
This is a snapshot of the folder list at the time the call was made.
It does not update over time.
The map contains MdFolder objects:
maildir.folders()["Sent"]
might retrieve the folder .S... | python | def folders(self):
"""Return a map of the subfolder objects for this folder.
This is a snapshot of the folder list at the time the call was made.
It does not update over time.
The map contains MdFolder objects:
maildir.folders()["Sent"]
might retrieve the folder .S... | [
"def",
"folders",
"(",
"self",
")",
":",
"entrys",
"=",
"self",
".",
"filesystem",
".",
"listdir",
"(",
"abspath",
"(",
"self",
".",
"_foldername",
"(",
")",
")",
")",
"regex",
"=",
"re",
".",
"compile",
"(",
"\"\\\\..*\"",
")",
"just_dirs",
"=",
"di... | Return a map of the subfolder objects for this folder.
This is a snapshot of the folder list at the time the call was made.
It does not update over time.
The map contains MdFolder objects:
maildir.folders()["Sent"]
might retrieve the folder .Sent from the maildir. | [
"Return",
"a",
"map",
"of",
"the",
"subfolder",
"objects",
"for",
"this",
"folder",
"."
] | 302ca8882dae060fb15bd5ae470d8e661fb67ec4 | https://github.com/nicferrier/md/blob/302ca8882dae060fb15bd5ae470d8e661fb67ec4/src/mdlib/api.py#L307-L355 | train | 56,112 |
nicferrier/md | src/mdlib/api.py | MdFolder.move | def move(self, key, folder):
"""Move the specified key to folder.
folder must be an MdFolder instance. MdFolders can be obtained
through the 'folders' method call.
"""
# Basically this is a sophisticated __delitem__
# We need the path so we can make it in the new folder
... | python | def move(self, key, folder):
"""Move the specified key to folder.
folder must be an MdFolder instance. MdFolders can be obtained
through the 'folders' method call.
"""
# Basically this is a sophisticated __delitem__
# We need the path so we can make it in the new folder
... | [
"def",
"move",
"(",
"self",
",",
"key",
",",
"folder",
")",
":",
"# Basically this is a sophisticated __delitem__",
"# We need the path so we can make it in the new folder",
"path",
",",
"host",
",",
"flags",
"=",
"self",
".",
"_exists",
"(",
"key",
")",
"self",
"."... | Move the specified key to folder.
folder must be an MdFolder instance. MdFolders can be obtained
through the 'folders' method call. | [
"Move",
"the",
"specified",
"key",
"to",
"folder",
"."
] | 302ca8882dae060fb15bd5ae470d8e661fb67ec4 | https://github.com/nicferrier/md/blob/302ca8882dae060fb15bd5ae470d8e661fb67ec4/src/mdlib/api.py#L357-L377 | train | 56,113 |
nicferrier/md | src/mdlib/api.py | MdFolder._muaprocessnew | def _muaprocessnew(self):
"""Moves all 'new' files into cur, correctly flagging"""
foldername = self._foldername("new")
files = self.filesystem.listdir(foldername)
for filename in files:
if filename == "":
continue
curfilename = self._foldername(jo... | python | def _muaprocessnew(self):
"""Moves all 'new' files into cur, correctly flagging"""
foldername = self._foldername("new")
files = self.filesystem.listdir(foldername)
for filename in files:
if filename == "":
continue
curfilename = self._foldername(jo... | [
"def",
"_muaprocessnew",
"(",
"self",
")",
":",
"foldername",
"=",
"self",
".",
"_foldername",
"(",
"\"new\"",
")",
"files",
"=",
"self",
".",
"filesystem",
".",
"listdir",
"(",
"foldername",
")",
"for",
"filename",
"in",
"files",
":",
"if",
"filename",
... | Moves all 'new' files into cur, correctly flagging | [
"Moves",
"all",
"new",
"files",
"into",
"cur",
"correctly",
"flagging"
] | 302ca8882dae060fb15bd5ae470d8e661fb67ec4 | https://github.com/nicferrier/md/blob/302ca8882dae060fb15bd5ae470d8e661fb67ec4/src/mdlib/api.py#L382-L394 | train | 56,114 |
nicferrier/md | src/mdlib/api.py | MdFolder._exists | def _exists(self, key):
"""Find a key in a particular section
Searches through all the files and looks for matches with a regex.
"""
filecache, keycache = self._fileslist()
msg = keycache.get(key, None)
if msg:
path = msg.filename
meta = filecache... | python | def _exists(self, key):
"""Find a key in a particular section
Searches through all the files and looks for matches with a regex.
"""
filecache, keycache = self._fileslist()
msg = keycache.get(key, None)
if msg:
path = msg.filename
meta = filecache... | [
"def",
"_exists",
"(",
"self",
",",
"key",
")",
":",
"filecache",
",",
"keycache",
"=",
"self",
".",
"_fileslist",
"(",
")",
"msg",
"=",
"keycache",
".",
"get",
"(",
"key",
",",
"None",
")",
"if",
"msg",
":",
"path",
"=",
"msg",
".",
"filename",
... | Find a key in a particular section
Searches through all the files and looks for matches with a regex. | [
"Find",
"a",
"key",
"in",
"a",
"particular",
"section"
] | 302ca8882dae060fb15bd5ae470d8e661fb67ec4 | https://github.com/nicferrier/md/blob/302ca8882dae060fb15bd5ae470d8e661fb67ec4/src/mdlib/api.py#L432-L443 | train | 56,115 |
mjirik/sed3 | sed3/sed3.py | __put_slice_in_slim | def __put_slice_in_slim(slim, dataim, sh, i):
"""
put one small slice as a tile in a big image
"""
a, b = np.unravel_index(int(i), sh)
st0 = int(dataim.shape[0] * a)
st1 = int(dataim.shape[1] * b)
sp0 = int(st0 + dataim.shape[0])
sp1 = int(st1 + dataim.shape[1])
slim[
... | python | def __put_slice_in_slim(slim, dataim, sh, i):
"""
put one small slice as a tile in a big image
"""
a, b = np.unravel_index(int(i), sh)
st0 = int(dataim.shape[0] * a)
st1 = int(dataim.shape[1] * b)
sp0 = int(st0 + dataim.shape[0])
sp1 = int(st1 + dataim.shape[1])
slim[
... | [
"def",
"__put_slice_in_slim",
"(",
"slim",
",",
"dataim",
",",
"sh",
",",
"i",
")",
":",
"a",
",",
"b",
"=",
"np",
".",
"unravel_index",
"(",
"int",
"(",
"i",
")",
",",
"sh",
")",
"st0",
"=",
"int",
"(",
"dataim",
".",
"shape",
"[",
"0",
"]",
... | put one small slice as a tile in a big image | [
"put",
"one",
"small",
"slice",
"as",
"a",
"tile",
"in",
"a",
"big",
"image"
] | 270c12836218fd2fa2fe192c6b6fef882322c173 | https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L738-L754 | train | 56,116 |
mjirik/sed3 | sed3/sed3.py | _import_data | def _import_data(data, axis, slice_step, first_slice_offset=0):
"""
import ndarray or SimpleITK data
"""
try:
import SimpleITK as sitk
if type(data) is sitk.SimpleITK.Image:
data = sitk.GetArrayFromImage(data)
except:
pass
data = __select_slices(da... | python | def _import_data(data, axis, slice_step, first_slice_offset=0):
"""
import ndarray or SimpleITK data
"""
try:
import SimpleITK as sitk
if type(data) is sitk.SimpleITK.Image:
data = sitk.GetArrayFromImage(data)
except:
pass
data = __select_slices(da... | [
"def",
"_import_data",
"(",
"data",
",",
"axis",
",",
"slice_step",
",",
"first_slice_offset",
"=",
"0",
")",
":",
"try",
":",
"import",
"SimpleITK",
"as",
"sitk",
"if",
"type",
"(",
"data",
")",
"is",
"sitk",
".",
"SimpleITK",
".",
"Image",
":",
"data... | import ndarray or SimpleITK data | [
"import",
"ndarray",
"or",
"SimpleITK",
"data"
] | 270c12836218fd2fa2fe192c6b6fef882322c173 | https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L845-L857 | train | 56,117 |
mjirik/sed3 | sed3/sed3.py | index_to_coords | def index_to_coords(index, shape):
'''convert index to coordinates given the shape'''
coords = []
for i in xrange(1, len(shape)):
divisor = int(np.product(shape[i:]))
value = index // divisor
coords.append(value)
index -= value * divisor
coords.append(index)
... | python | def index_to_coords(index, shape):
'''convert index to coordinates given the shape'''
coords = []
for i in xrange(1, len(shape)):
divisor = int(np.product(shape[i:]))
value = index // divisor
coords.append(value)
index -= value * divisor
coords.append(index)
... | [
"def",
"index_to_coords",
"(",
"index",
",",
"shape",
")",
":",
"coords",
"=",
"[",
"]",
"for",
"i",
"in",
"xrange",
"(",
"1",
",",
"len",
"(",
"shape",
")",
")",
":",
"divisor",
"=",
"int",
"(",
"np",
".",
"product",
"(",
"shape",
"[",
"i",
":... | convert index to coordinates given the shape | [
"convert",
"index",
"to",
"coordinates",
"given",
"the",
"shape"
] | 270c12836218fd2fa2fe192c6b6fef882322c173 | https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L1115-L1124 | train | 56,118 |
mjirik/sed3 | sed3/sed3.py | sed3.on_scroll | def on_scroll(self, event):
''' mouse wheel is used for setting slider value'''
if event.button == 'up':
self.next_slice()
if event.button == 'down':
self.prev_slice()
self.actual_slice_slider.set_val(self.actual_slice) | python | def on_scroll(self, event):
''' mouse wheel is used for setting slider value'''
if event.button == 'up':
self.next_slice()
if event.button == 'down':
self.prev_slice()
self.actual_slice_slider.set_val(self.actual_slice) | [
"def",
"on_scroll",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
".",
"button",
"==",
"'up'",
":",
"self",
".",
"next_slice",
"(",
")",
"if",
"event",
".",
"button",
"==",
"'down'",
":",
"self",
".",
"prev_slice",
"(",
")",
"self",
".",
"act... | mouse wheel is used for setting slider value | [
"mouse",
"wheel",
"is",
"used",
"for",
"setting",
"slider",
"value"
] | 270c12836218fd2fa2fe192c6b6fef882322c173 | https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L517-L523 | train | 56,119 |
mjirik/sed3 | sed3/sed3.py | sed3.on_press | def on_press(self, event):
'on but-ton press we will see if the mouse is over us and store data'
if event.inaxes != self.ax:
return
# contains, attrd = self.rect.contains(event)
# if not contains: return
# print('event contains', self.rect.xy)
# x0, y0 ... | python | def on_press(self, event):
'on but-ton press we will see if the mouse is over us and store data'
if event.inaxes != self.ax:
return
# contains, attrd = self.rect.contains(event)
# if not contains: return
# print('event contains', self.rect.xy)
# x0, y0 ... | [
"def",
"on_press",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
".",
"inaxes",
"!=",
"self",
".",
"ax",
":",
"return",
"# contains, attrd = self.rect.contains(event)\r",
"# if not contains: return\r",
"# print('event contains', self.rect.xy)\r",
"# x0, y0 = self.rect... | on but-ton press we will see if the mouse is over us and store data | [
"on",
"but",
"-",
"ton",
"press",
"we",
"will",
"see",
"if",
"the",
"mouse",
"is",
"over",
"us",
"and",
"store",
"data"
] | 270c12836218fd2fa2fe192c6b6fef882322c173 | https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L529-L537 | train | 56,120 |
mjirik/sed3 | sed3/sed3.py | sed3.on_motion | def on_motion(self, event):
'on motion we will move the rect if the mouse is over us'
if self.press is None:
return
if event.inaxes != self.ax:
return
# print(event.inaxes)
x0, y0, btn = self.press
x0.append(event.xdata)
y0.app... | python | def on_motion(self, event):
'on motion we will move the rect if the mouse is over us'
if self.press is None:
return
if event.inaxes != self.ax:
return
# print(event.inaxes)
x0, y0, btn = self.press
x0.append(event.xdata)
y0.app... | [
"def",
"on_motion",
"(",
"self",
",",
"event",
")",
":",
"if",
"self",
".",
"press",
"is",
"None",
":",
"return",
"if",
"event",
".",
"inaxes",
"!=",
"self",
".",
"ax",
":",
"return",
"# print(event.inaxes)\r",
"x0",
",",
"y0",
",",
"btn",
"=",
"self... | on motion we will move the rect if the mouse is over us | [
"on",
"motion",
"we",
"will",
"move",
"the",
"rect",
"if",
"the",
"mouse",
"is",
"over",
"us"
] | 270c12836218fd2fa2fe192c6b6fef882322c173 | https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L540-L551 | train | 56,121 |
mjirik/sed3 | sed3/sed3.py | sed3.on_release | def on_release(self, event):
'on release we reset the press data'
if self.press is None:
return
# print(self.press)
x0, y0, btn = self.press
if btn == 1:
color = 'r'
elif btn == 2:
color = 'b' # noqa
# plt.axes(self... | python | def on_release(self, event):
'on release we reset the press data'
if self.press is None:
return
# print(self.press)
x0, y0, btn = self.press
if btn == 1:
color = 'r'
elif btn == 2:
color = 'b' # noqa
# plt.axes(self... | [
"def",
"on_release",
"(",
"self",
",",
"event",
")",
":",
"if",
"self",
".",
"press",
"is",
"None",
":",
"return",
"# print(self.press)\r",
"x0",
",",
"y0",
",",
"btn",
"=",
"self",
".",
"press",
"if",
"btn",
"==",
"1",
":",
"color",
"=",
"'r'",
"e... | on release we reset the press data | [
"on",
"release",
"we",
"reset",
"the",
"press",
"data"
] | 270c12836218fd2fa2fe192c6b6fef882322c173 | https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L553-L573 | train | 56,122 |
mjirik/sed3 | sed3/sed3.py | sed3.get_seed_sub | def get_seed_sub(self, label):
""" Return list of all seeds with specific label
"""
sx, sy, sz = np.nonzero(self.seeds == label)
return sx, sy, sz | python | def get_seed_sub(self, label):
""" Return list of all seeds with specific label
"""
sx, sy, sz = np.nonzero(self.seeds == label)
return sx, sy, sz | [
"def",
"get_seed_sub",
"(",
"self",
",",
"label",
")",
":",
"sx",
",",
"sy",
",",
"sz",
"=",
"np",
".",
"nonzero",
"(",
"self",
".",
"seeds",
"==",
"label",
")",
"return",
"sx",
",",
"sy",
",",
"sz"
] | Return list of all seeds with specific label | [
"Return",
"list",
"of",
"all",
"seeds",
"with",
"specific",
"label"
] | 270c12836218fd2fa2fe192c6b6fef882322c173 | https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L595-L600 | train | 56,123 |
Ceasar/trees | trees/heap.py | heap.push | def push(self, item):
'''Push the value item onto the heap, maintaining the heap invariant.
If the item is not hashable, a TypeError is raised.
'''
hash(item)
heapq.heappush(self._items, item) | python | def push(self, item):
'''Push the value item onto the heap, maintaining the heap invariant.
If the item is not hashable, a TypeError is raised.
'''
hash(item)
heapq.heappush(self._items, item) | [
"def",
"push",
"(",
"self",
",",
"item",
")",
":",
"hash",
"(",
"item",
")",
"heapq",
".",
"heappush",
"(",
"self",
".",
"_items",
",",
"item",
")"
] | Push the value item onto the heap, maintaining the heap invariant.
If the item is not hashable, a TypeError is raised. | [
"Push",
"the",
"value",
"item",
"onto",
"the",
"heap",
"maintaining",
"the",
"heap",
"invariant",
".",
"If",
"the",
"item",
"is",
"not",
"hashable",
"a",
"TypeError",
"is",
"raised",
"."
] | 09059857112d3607942c81e87ab9ad04be4641f7 | https://github.com/Ceasar/trees/blob/09059857112d3607942c81e87ab9ad04be4641f7/trees/heap.py#L51-L56 | train | 56,124 |
what-studio/smartformat | smartformat/local.py | LocalFormatter.format_field_by_match | def format_field_by_match(self, value, match):
"""Formats a field by a Regex match of the format spec pattern."""
groups = match.groups()
fill, align, sign, sharp, zero, width, comma, prec, type_ = groups
if not comma and not prec and type_ not in list('fF%'):
return None
... | python | def format_field_by_match(self, value, match):
"""Formats a field by a Regex match of the format spec pattern."""
groups = match.groups()
fill, align, sign, sharp, zero, width, comma, prec, type_ = groups
if not comma and not prec and type_ not in list('fF%'):
return None
... | [
"def",
"format_field_by_match",
"(",
"self",
",",
"value",
",",
"match",
")",
":",
"groups",
"=",
"match",
".",
"groups",
"(",
")",
"fill",
",",
"align",
",",
"sign",
",",
"sharp",
",",
"zero",
",",
"width",
",",
"comma",
",",
"prec",
",",
"type_",
... | Formats a field by a Regex match of the format spec pattern. | [
"Formats",
"a",
"field",
"by",
"a",
"Regex",
"match",
"of",
"the",
"format",
"spec",
"pattern",
"."
] | 5731203cbf29617ab8d42542f9dac03d5e34b217 | https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/local.py#L102-L133 | train | 56,125 |
jaredLunde/redis_structures | redis_structures/debug/__init__.py | Timer.reset | def reset(self):
""" Resets the time intervals """
self._start = 0
self._first_start = 0
self._stop = time.perf_counter()
self._array = None
self._array_len = 0
self.intervals = []
self._intervals_len = 0 | python | def reset(self):
""" Resets the time intervals """
self._start = 0
self._first_start = 0
self._stop = time.perf_counter()
self._array = None
self._array_len = 0
self.intervals = []
self._intervals_len = 0 | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"_start",
"=",
"0",
"self",
".",
"_first_start",
"=",
"0",
"self",
".",
"_stop",
"=",
"time",
".",
"perf_counter",
"(",
")",
"self",
".",
"_array",
"=",
"None",
"self",
".",
"_array_len",
"=",
"0"... | Resets the time intervals | [
"Resets",
"the",
"time",
"intervals"
] | b9cce5f5c85db5e12c292633ff8d04e3ae053294 | https://github.com/jaredLunde/redis_structures/blob/b9cce5f5c85db5e12c292633ff8d04e3ae053294/redis_structures/debug/__init__.py#L2147-L2155 | train | 56,126 |
HPENetworking/topology_lib_ip | setup.py | read | def read(filename):
"""
Read a file relative to setup.py location.
"""
import os
here = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(here, filename)) as fd:
return fd.read() | python | def read(filename):
"""
Read a file relative to setup.py location.
"""
import os
here = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(here, filename)) as fd:
return fd.read() | [
"def",
"read",
"(",
"filename",
")",
":",
"import",
"os",
"here",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"here",
",",
... | Read a file relative to setup.py location. | [
"Read",
"a",
"file",
"relative",
"to",
"setup",
".",
"py",
"location",
"."
] | c69cc3db80d96575d787fdc903a9370d2df1c5ae | https://github.com/HPENetworking/topology_lib_ip/blob/c69cc3db80d96575d787fdc903a9370d2df1c5ae/setup.py#L22-L29 | train | 56,127 |
HPENetworking/topology_lib_ip | setup.py | find_version | def find_version(filename):
"""
Find package version in file.
"""
import re
content = read(filename)
version_match = re.search(
r"^__version__ = ['\"]([^'\"]*)['\"]", content, re.M
)
if version_match:
return version_match.group(1)
raise RuntimeError('Unable to find ve... | python | def find_version(filename):
"""
Find package version in file.
"""
import re
content = read(filename)
version_match = re.search(
r"^__version__ = ['\"]([^'\"]*)['\"]", content, re.M
)
if version_match:
return version_match.group(1)
raise RuntimeError('Unable to find ve... | [
"def",
"find_version",
"(",
"filename",
")",
":",
"import",
"re",
"content",
"=",
"read",
"(",
"filename",
")",
"version_match",
"=",
"re",
".",
"search",
"(",
"r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\"",
",",
"content",
",",
"re",
".",
"M",
")",
"if",
"... | Find package version in file. | [
"Find",
"package",
"version",
"in",
"file",
"."
] | c69cc3db80d96575d787fdc903a9370d2df1c5ae | https://github.com/HPENetworking/topology_lib_ip/blob/c69cc3db80d96575d787fdc903a9370d2df1c5ae/setup.py#L32-L43 | train | 56,128 |
HPENetworking/topology_lib_ip | setup.py | find_requirements | def find_requirements(filename):
"""
Find requirements in file.
"""
import string
content = read(filename)
requirements = []
for line in content.splitlines():
line = line.strip()
if line and line[:1] in string.ascii_letters:
requirements.append(line)
return re... | python | def find_requirements(filename):
"""
Find requirements in file.
"""
import string
content = read(filename)
requirements = []
for line in content.splitlines():
line = line.strip()
if line and line[:1] in string.ascii_letters:
requirements.append(line)
return re... | [
"def",
"find_requirements",
"(",
"filename",
")",
":",
"import",
"string",
"content",
"=",
"read",
"(",
"filename",
")",
"requirements",
"=",
"[",
"]",
"for",
"line",
"in",
"content",
".",
"splitlines",
"(",
")",
":",
"line",
"=",
"line",
".",
"strip",
... | Find requirements in file. | [
"Find",
"requirements",
"in",
"file",
"."
] | c69cc3db80d96575d787fdc903a9370d2df1c5ae | https://github.com/HPENetworking/topology_lib_ip/blob/c69cc3db80d96575d787fdc903a9370d2df1c5ae/setup.py#L46-L57 | train | 56,129 |
botstory/botstory | botstory/integrations/ga/universal_analytics/tracker.py | generate_uuid | def generate_uuid(basedata=None):
""" Provides a _random_ UUID with no input, or a UUID4-format MD5 checksum of any input data provided """
if basedata is None:
return str(uuid.uuid4())
elif isinstance(basedata, str):
checksum = hashlib.md5(basedata).hexdigest()
return '%8s-%4s-%4s-%... | python | def generate_uuid(basedata=None):
""" Provides a _random_ UUID with no input, or a UUID4-format MD5 checksum of any input data provided """
if basedata is None:
return str(uuid.uuid4())
elif isinstance(basedata, str):
checksum = hashlib.md5(basedata).hexdigest()
return '%8s-%4s-%4s-%... | [
"def",
"generate_uuid",
"(",
"basedata",
"=",
"None",
")",
":",
"if",
"basedata",
"is",
"None",
":",
"return",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"elif",
"isinstance",
"(",
"basedata",
",",
"str",
")",
":",
"checksum",
"=",
"hashlib",
"... | Provides a _random_ UUID with no input, or a UUID4-format MD5 checksum of any input data provided | [
"Provides",
"a",
"_random_",
"UUID",
"with",
"no",
"input",
"or",
"a",
"UUID4",
"-",
"format",
"MD5",
"checksum",
"of",
"any",
"input",
"data",
"provided"
] | 9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3 | https://github.com/botstory/botstory/blob/9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3/botstory/integrations/ga/universal_analytics/tracker.py#L30-L37 | train | 56,130 |
botstory/botstory | botstory/integrations/ga/universal_analytics/tracker.py | Time.from_unix | def from_unix(cls, seconds, milliseconds=0):
""" Produce a full |datetime.datetime| object from a Unix timestamp """
base = list(time.gmtime(seconds))[0:6]
base.append(milliseconds * 1000) # microseconds
return cls(*base) | python | def from_unix(cls, seconds, milliseconds=0):
""" Produce a full |datetime.datetime| object from a Unix timestamp """
base = list(time.gmtime(seconds))[0:6]
base.append(milliseconds * 1000) # microseconds
return cls(*base) | [
"def",
"from_unix",
"(",
"cls",
",",
"seconds",
",",
"milliseconds",
"=",
"0",
")",
":",
"base",
"=",
"list",
"(",
"time",
".",
"gmtime",
"(",
"seconds",
")",
")",
"[",
"0",
":",
"6",
"]",
"base",
".",
"append",
"(",
"milliseconds",
"*",
"1000",
... | Produce a full |datetime.datetime| object from a Unix timestamp | [
"Produce",
"a",
"full",
"|datetime",
".",
"datetime|",
"object",
"from",
"a",
"Unix",
"timestamp"
] | 9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3 | https://github.com/botstory/botstory/blob/9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3/botstory/integrations/ga/universal_analytics/tracker.py#L44-L48 | train | 56,131 |
botstory/botstory | botstory/integrations/ga/universal_analytics/tracker.py | Time.to_unix | def to_unix(cls, timestamp):
""" Wrapper over time module to produce Unix epoch time as a float """
if not isinstance(timestamp, datetime.datetime):
raise TypeError('Time.milliseconds expects a datetime object')
base = time.mktime(timestamp.timetuple())
return base | python | def to_unix(cls, timestamp):
""" Wrapper over time module to produce Unix epoch time as a float """
if not isinstance(timestamp, datetime.datetime):
raise TypeError('Time.milliseconds expects a datetime object')
base = time.mktime(timestamp.timetuple())
return base | [
"def",
"to_unix",
"(",
"cls",
",",
"timestamp",
")",
":",
"if",
"not",
"isinstance",
"(",
"timestamp",
",",
"datetime",
".",
"datetime",
")",
":",
"raise",
"TypeError",
"(",
"'Time.milliseconds expects a datetime object'",
")",
"base",
"=",
"time",
".",
"mktim... | Wrapper over time module to produce Unix epoch time as a float | [
"Wrapper",
"over",
"time",
"module",
"to",
"produce",
"Unix",
"epoch",
"time",
"as",
"a",
"float"
] | 9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3 | https://github.com/botstory/botstory/blob/9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3/botstory/integrations/ga/universal_analytics/tracker.py#L51-L56 | train | 56,132 |
botstory/botstory | botstory/integrations/ga/universal_analytics/tracker.py | HTTPRequest.fixUTF8 | def fixUTF8(cls, data): # Ensure proper encoding for UA's servers...
""" Convert all strings to UTF-8 """
for key in data:
if isinstance(data[key], str):
data[key] = data[key].encode('utf-8')
return data | python | def fixUTF8(cls, data): # Ensure proper encoding for UA's servers...
""" Convert all strings to UTF-8 """
for key in data:
if isinstance(data[key], str):
data[key] = data[key].encode('utf-8')
return data | [
"def",
"fixUTF8",
"(",
"cls",
",",
"data",
")",
":",
"# Ensure proper encoding for UA's servers...",
"for",
"key",
"in",
"data",
":",
"if",
"isinstance",
"(",
"data",
"[",
"key",
"]",
",",
"str",
")",
":",
"data",
"[",
"key",
"]",
"=",
"data",
"[",
"ke... | Convert all strings to UTF-8 | [
"Convert",
"all",
"strings",
"to",
"UTF",
"-",
"8"
] | 9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3 | https://github.com/botstory/botstory/blob/9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3/botstory/integrations/ga/universal_analytics/tracker.py#L86-L91 | train | 56,133 |
botstory/botstory | botstory/integrations/ga/universal_analytics/tracker.py | Tracker.consume_options | def consume_options(cls, data, hittype, args):
""" Interpret sequential arguments related to known hittypes based on declared structures """
opt_position = 0
data['t'] = hittype # integrate hit type parameter
if hittype in cls.option_sequence:
for expected_type, optname in c... | python | def consume_options(cls, data, hittype, args):
""" Interpret sequential arguments related to known hittypes based on declared structures """
opt_position = 0
data['t'] = hittype # integrate hit type parameter
if hittype in cls.option_sequence:
for expected_type, optname in c... | [
"def",
"consume_options",
"(",
"cls",
",",
"data",
",",
"hittype",
",",
"args",
")",
":",
"opt_position",
"=",
"0",
"data",
"[",
"'t'",
"]",
"=",
"hittype",
"# integrate hit type parameter",
"if",
"hittype",
"in",
"cls",
".",
"option_sequence",
":",
"for",
... | Interpret sequential arguments related to known hittypes based on declared structures | [
"Interpret",
"sequential",
"arguments",
"related",
"to",
"known",
"hittypes",
"based",
"on",
"declared",
"structures"
] | 9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3 | https://github.com/botstory/botstory/blob/9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3/botstory/integrations/ga/universal_analytics/tracker.py#L173-L181 | train | 56,134 |
botstory/botstory | botstory/integrations/ga/universal_analytics/tracker.py | Tracker.set_timestamp | def set_timestamp(self, data):
""" Interpret time-related options, apply queue-time parameter as needed """
if 'hittime' in data: # an absolute timestamp
data['qt'] = self.hittime(timestamp=data.pop('hittime', None))
if 'hitage' in data: # a relative age (in seconds)
da... | python | def set_timestamp(self, data):
""" Interpret time-related options, apply queue-time parameter as needed """
if 'hittime' in data: # an absolute timestamp
data['qt'] = self.hittime(timestamp=data.pop('hittime', None))
if 'hitage' in data: # a relative age (in seconds)
da... | [
"def",
"set_timestamp",
"(",
"self",
",",
"data",
")",
":",
"if",
"'hittime'",
"in",
"data",
":",
"# an absolute timestamp",
"data",
"[",
"'qt'",
"]",
"=",
"self",
".",
"hittime",
"(",
"timestamp",
"=",
"data",
".",
"pop",
"(",
"'hittime'",
",",
"None",
... | Interpret time-related options, apply queue-time parameter as needed | [
"Interpret",
"time",
"-",
"related",
"options",
"apply",
"queue",
"-",
"time",
"parameter",
"as",
"needed"
] | 9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3 | https://github.com/botstory/botstory/blob/9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3/botstory/integrations/ga/universal_analytics/tracker.py#L218-L223 | train | 56,135 |
botstory/botstory | botstory/integrations/ga/universal_analytics/tracker.py | Tracker.send | async def send(self, hittype, *args, **data):
""" Transmit HTTP requests to Google Analytics using the measurement protocol """
if hittype not in self.valid_hittypes:
raise KeyError('Unsupported Universal Analytics Hit Type: {0}'.format(repr(hittype)))
self.set_timestamp(data)
... | python | async def send(self, hittype, *args, **data):
""" Transmit HTTP requests to Google Analytics using the measurement protocol """
if hittype not in self.valid_hittypes:
raise KeyError('Unsupported Universal Analytics Hit Type: {0}'.format(repr(hittype)))
self.set_timestamp(data)
... | [
"async",
"def",
"send",
"(",
"self",
",",
"hittype",
",",
"*",
"args",
",",
"*",
"*",
"data",
")",
":",
"if",
"hittype",
"not",
"in",
"self",
".",
"valid_hittypes",
":",
"raise",
"KeyError",
"(",
"'Unsupported Universal Analytics Hit Type: {0}'",
".",
"forma... | Transmit HTTP requests to Google Analytics using the measurement protocol | [
"Transmit",
"HTTP",
"requests",
"to",
"Google",
"Analytics",
"using",
"the",
"measurement",
"protocol"
] | 9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3 | https://github.com/botstory/botstory/blob/9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3/botstory/integrations/ga/universal_analytics/tracker.py#L225-L249 | train | 56,136 |
opereto/pyopereto | pyopereto/client.py | OperetoClient.get_process_log | def get_process_log(self, pid=None, start=0, limit=1000):
'''
get_process_log(self, pid=None, start=0, limit=1000
Get process logs
:Parameters:
* *pid* (`string`) -- Identifier of an existing process
* *pid* (`string`) -- start index to retrieve logs from
* *pid... | python | def get_process_log(self, pid=None, start=0, limit=1000):
'''
get_process_log(self, pid=None, start=0, limit=1000
Get process logs
:Parameters:
* *pid* (`string`) -- Identifier of an existing process
* *pid* (`string`) -- start index to retrieve logs from
* *pid... | [
"def",
"get_process_log",
"(",
"self",
",",
"pid",
"=",
"None",
",",
"start",
"=",
"0",
",",
"limit",
"=",
"1000",
")",
":",
"pid",
"=",
"self",
".",
"_get_pid",
"(",
"pid",
")",
"data",
"=",
"self",
".",
"_call_rest_api",
"(",
"'get'",
",",
"'/pro... | get_process_log(self, pid=None, start=0, limit=1000
Get process logs
:Parameters:
* *pid* (`string`) -- Identifier of an existing process
* *pid* (`string`) -- start index to retrieve logs from
* *pid* (`string`) -- maximum number of entities to retrieve
:return: Proce... | [
"get_process_log",
"(",
"self",
"pid",
"=",
"None",
"start",
"=",
"0",
"limit",
"=",
"1000"
] | 16ca987738a7e1b82b52b0b099794a74ed557223 | https://github.com/opereto/pyopereto/blob/16ca987738a7e1b82b52b0b099794a74ed557223/pyopereto/client.py#L1178-L1194 | train | 56,137 |
standage/tag | tag/writer.py | GFF3Writer.write | def write(self):
"""Pull features from the instream and write them to the output."""
for entry in self._instream:
if isinstance(entry, Feature):
for feature in entry:
if feature.num_children > 0 or feature.is_multi:
if feature.is_mu... | python | def write(self):
"""Pull features from the instream and write them to the output."""
for entry in self._instream:
if isinstance(entry, Feature):
for feature in entry:
if feature.num_children > 0 or feature.is_multi:
if feature.is_mu... | [
"def",
"write",
"(",
"self",
")",
":",
"for",
"entry",
"in",
"self",
".",
"_instream",
":",
"if",
"isinstance",
"(",
"entry",
",",
"Feature",
")",
":",
"for",
"feature",
"in",
"entry",
":",
"if",
"feature",
".",
"num_children",
">",
"0",
"or",
"featu... | Pull features from the instream and write them to the output. | [
"Pull",
"features",
"from",
"the",
"instream",
"and",
"write",
"them",
"to",
"the",
"output",
"."
] | 94686adf57115cea1c5235e99299e691f80ba10b | https://github.com/standage/tag/blob/94686adf57115cea1c5235e99299e691f80ba10b/tag/writer.py#L55-L72 | train | 56,138 |
scivision/sciencedates | sciencedates/__init__.py | date2doy | def date2doy(time: Union[str, datetime.datetime]) -> Tuple[int, int]:
"""
< 366 for leap year too. normal year 0..364. Leap 0..365.
"""
T = np.atleast_1d(time)
year = np.empty(T.size, dtype=int)
doy = np.empty_like(year)
for i, t in enumerate(T):
yd = str(datetime2yeardoy(t)[0])
... | python | def date2doy(time: Union[str, datetime.datetime]) -> Tuple[int, int]:
"""
< 366 for leap year too. normal year 0..364. Leap 0..365.
"""
T = np.atleast_1d(time)
year = np.empty(T.size, dtype=int)
doy = np.empty_like(year)
for i, t in enumerate(T):
yd = str(datetime2yeardoy(t)[0])
... | [
"def",
"date2doy",
"(",
"time",
":",
"Union",
"[",
"str",
",",
"datetime",
".",
"datetime",
"]",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
"]",
":",
"T",
"=",
"np",
".",
"atleast_1d",
"(",
"time",
")",
"year",
"=",
"np",
".",
"empty",
"(",
"T... | < 366 for leap year too. normal year 0..364. Leap 0..365. | [
"<",
"366",
"for",
"leap",
"year",
"too",
".",
"normal",
"year",
"0",
"..",
"364",
".",
"Leap",
"0",
"..",
"365",
"."
] | a713389e027b42d26875cf227450a5d7c6696000 | https://github.com/scivision/sciencedates/blob/a713389e027b42d26875cf227450a5d7c6696000/sciencedates/__init__.py#L75-L93 | train | 56,139 |
scivision/sciencedates | sciencedates/__init__.py | randomdate | def randomdate(year: int) -> datetime.date:
""" gives random date in year"""
if calendar.isleap(year):
doy = random.randrange(366)
else:
doy = random.randrange(365)
return datetime.date(year, 1, 1) + datetime.timedelta(days=doy) | python | def randomdate(year: int) -> datetime.date:
""" gives random date in year"""
if calendar.isleap(year):
doy = random.randrange(366)
else:
doy = random.randrange(365)
return datetime.date(year, 1, 1) + datetime.timedelta(days=doy) | [
"def",
"randomdate",
"(",
"year",
":",
"int",
")",
"->",
"datetime",
".",
"date",
":",
"if",
"calendar",
".",
"isleap",
"(",
"year",
")",
":",
"doy",
"=",
"random",
".",
"randrange",
"(",
"366",
")",
"else",
":",
"doy",
"=",
"random",
".",
"randran... | gives random date in year | [
"gives",
"random",
"date",
"in",
"year"
] | a713389e027b42d26875cf227450a5d7c6696000 | https://github.com/scivision/sciencedates/blob/a713389e027b42d26875cf227450a5d7c6696000/sciencedates/__init__.py#L210-L217 | train | 56,140 |
iskandr/serializable | serializable/helpers.py | function_to_serializable_representation | def function_to_serializable_representation(fn):
"""
Converts a Python function into a serializable representation. Does not
currently work for methods or functions with closure data.
"""
if type(fn) not in (FunctionType, BuiltinFunctionType):
raise ValueError(
"Can't serialize %... | python | def function_to_serializable_representation(fn):
"""
Converts a Python function into a serializable representation. Does not
currently work for methods or functions with closure data.
"""
if type(fn) not in (FunctionType, BuiltinFunctionType):
raise ValueError(
"Can't serialize %... | [
"def",
"function_to_serializable_representation",
"(",
"fn",
")",
":",
"if",
"type",
"(",
"fn",
")",
"not",
"in",
"(",
"FunctionType",
",",
"BuiltinFunctionType",
")",
":",
"raise",
"ValueError",
"(",
"\"Can't serialize %s : %s, must be globally defined function\"",
"%"... | Converts a Python function into a serializable representation. Does not
currently work for methods or functions with closure data. | [
"Converts",
"a",
"Python",
"function",
"into",
"a",
"serializable",
"representation",
".",
"Does",
"not",
"currently",
"work",
"for",
"methods",
"or",
"functions",
"with",
"closure",
"data",
"."
] | 6807dfd582567b3bda609910806b7429d8d53b44 | https://github.com/iskandr/serializable/blob/6807dfd582567b3bda609910806b7429d8d53b44/serializable/helpers.py#L120-L133 | train | 56,141 |
iskandr/serializable | serializable/helpers.py | from_serializable_dict | def from_serializable_dict(x):
"""
Reconstruct a dictionary by recursively reconstructing all its keys and
values.
This is the most hackish part since we rely on key names such as
__name__, __class__, __module__ as metadata about how to reconstruct
an object.
TODO: It would be cleaner to a... | python | def from_serializable_dict(x):
"""
Reconstruct a dictionary by recursively reconstructing all its keys and
values.
This is the most hackish part since we rely on key names such as
__name__, __class__, __module__ as metadata about how to reconstruct
an object.
TODO: It would be cleaner to a... | [
"def",
"from_serializable_dict",
"(",
"x",
")",
":",
"if",
"\"__name__\"",
"in",
"x",
":",
"return",
"_lookup_value",
"(",
"x",
".",
"pop",
"(",
"\"__module__\"",
")",
",",
"x",
".",
"pop",
"(",
"\"__name__\"",
")",
")",
"non_string_key_objects",
"=",
"[",... | Reconstruct a dictionary by recursively reconstructing all its keys and
values.
This is the most hackish part since we rely on key names such as
__name__, __class__, __module__ as metadata about how to reconstruct
an object.
TODO: It would be cleaner to always wrap each object in a layer of type
... | [
"Reconstruct",
"a",
"dictionary",
"by",
"recursively",
"reconstructing",
"all",
"its",
"keys",
"and",
"values",
"."
] | 6807dfd582567b3bda609910806b7429d8d53b44 | https://github.com/iskandr/serializable/blob/6807dfd582567b3bda609910806b7429d8d53b44/serializable/helpers.py#L188-L224 | train | 56,142 |
iskandr/serializable | serializable/helpers.py | to_serializable_repr | def to_serializable_repr(x):
"""
Convert an instance of Serializable or a primitive collection containing
such instances into serializable types.
"""
t = type(x)
if isinstance(x, list):
return list_to_serializable_repr(x)
elif t in (set, tuple):
return {
"__class_... | python | def to_serializable_repr(x):
"""
Convert an instance of Serializable or a primitive collection containing
such instances into serializable types.
"""
t = type(x)
if isinstance(x, list):
return list_to_serializable_repr(x)
elif t in (set, tuple):
return {
"__class_... | [
"def",
"to_serializable_repr",
"(",
"x",
")",
":",
"t",
"=",
"type",
"(",
"x",
")",
"if",
"isinstance",
"(",
"x",
",",
"list",
")",
":",
"return",
"list_to_serializable_repr",
"(",
"x",
")",
"elif",
"t",
"in",
"(",
"set",
",",
"tuple",
")",
":",
"r... | Convert an instance of Serializable or a primitive collection containing
such instances into serializable types. | [
"Convert",
"an",
"instance",
"of",
"Serializable",
"or",
"a",
"primitive",
"collection",
"containing",
"such",
"instances",
"into",
"serializable",
"types",
"."
] | 6807dfd582567b3bda609910806b7429d8d53b44 | https://github.com/iskandr/serializable/blob/6807dfd582567b3bda609910806b7429d8d53b44/serializable/helpers.py#L247-L270 | train | 56,143 |
GeorgeArgyros/symautomata | symautomata/pdastring.py | PdaString._combine_rest_push | def _combine_rest_push(self):
"""Combining Rest and Push States"""
new = []
change = 0
# DEBUG
# logging.debug('Combining Rest and Push')
i = 0
examinetypes = self.quickresponse_types[3]
for state in examinetypes:
if state.type == 3:
... | python | def _combine_rest_push(self):
"""Combining Rest and Push States"""
new = []
change = 0
# DEBUG
# logging.debug('Combining Rest and Push')
i = 0
examinetypes = self.quickresponse_types[3]
for state in examinetypes:
if state.type == 3:
... | [
"def",
"_combine_rest_push",
"(",
"self",
")",
":",
"new",
"=",
"[",
"]",
"change",
"=",
"0",
"# DEBUG",
"# logging.debug('Combining Rest and Push')",
"i",
"=",
"0",
"examinetypes",
"=",
"self",
".",
"quickresponse_types",
"[",
"3",
"]",
"for",
"state",
"in",
... | Combining Rest and Push States | [
"Combining",
"Rest",
"and",
"Push",
"States"
] | f5d66533573b27e155bec3f36b8c00b8e3937cb3 | https://github.com/GeorgeArgyros/symautomata/blob/f5d66533573b27e155bec3f36b8c00b8e3937cb3/symautomata/pdastring.py#L18-L82 | train | 56,144 |
GeorgeArgyros/symautomata | symautomata/pdastring.py | PdaString._check | def _check(self, accepted):
"""_check for string existence"""
# logging.debug('A check is now happening...')
# for key in self.statediag[1].trans:
# logging.debug('transition to '+`key`+" with "+self.statediag[1].trans[key][0])
total = []
if 1 in self.quickresponse:
... | python | def _check(self, accepted):
"""_check for string existence"""
# logging.debug('A check is now happening...')
# for key in self.statediag[1].trans:
# logging.debug('transition to '+`key`+" with "+self.statediag[1].trans[key][0])
total = []
if 1 in self.quickresponse:
... | [
"def",
"_check",
"(",
"self",
",",
"accepted",
")",
":",
"# logging.debug('A check is now happening...')",
"# for key in self.statediag[1].trans:",
"# logging.debug('transition to '+`key`+\" with \"+self.statediag[1].trans[key][0])",
"total",
"=",
"[",
"]",
"if",
"1",
"in",
"s... | _check for string existence | [
"_check",
"for",
"string",
"existence"
] | f5d66533573b27e155bec3f36b8c00b8e3937cb3 | https://github.com/GeorgeArgyros/symautomata/blob/f5d66533573b27e155bec3f36b8c00b8e3937cb3/symautomata/pdastring.py#L414-L435 | train | 56,145 |
GeorgeArgyros/symautomata | symautomata/pdastring.py | PdaString._stage | def _stage(self, accepted, count=0):
"""This is a repeated state in the state removal algorithm"""
new5 = self._combine_rest_push()
new1 = self._combine_push_pop()
new2 = self._combine_push_rest()
new3 = self._combine_pop_rest()
new4 = self._combine_rest_rest()
ne... | python | def _stage(self, accepted, count=0):
"""This is a repeated state in the state removal algorithm"""
new5 = self._combine_rest_push()
new1 = self._combine_push_pop()
new2 = self._combine_push_rest()
new3 = self._combine_pop_rest()
new4 = self._combine_rest_rest()
ne... | [
"def",
"_stage",
"(",
"self",
",",
"accepted",
",",
"count",
"=",
"0",
")",
":",
"new5",
"=",
"self",
".",
"_combine_rest_push",
"(",
")",
"new1",
"=",
"self",
".",
"_combine_push_pop",
"(",
")",
"new2",
"=",
"self",
".",
"_combine_push_rest",
"(",
")"... | This is a repeated state in the state removal algorithm | [
"This",
"is",
"a",
"repeated",
"state",
"in",
"the",
"state",
"removal",
"algorithm"
] | f5d66533573b27e155bec3f36b8c00b8e3937cb3 | https://github.com/GeorgeArgyros/symautomata/blob/f5d66533573b27e155bec3f36b8c00b8e3937cb3/symautomata/pdastring.py#L437-L501 | train | 56,146 |
GeorgeArgyros/symautomata | symautomata/pdastring.py | PdaString.printer | def printer(self):
"""Visualizes the current state"""
for key in self.statediag:
if key.trans is not None and len(key.trans) > 0:
print '****** ' + repr(key.id) + '(' + repr(key.type)\
+ ' on sym ' + repr(key.sym) + ') ******'
print key.t... | python | def printer(self):
"""Visualizes the current state"""
for key in self.statediag:
if key.trans is not None and len(key.trans) > 0:
print '****** ' + repr(key.id) + '(' + repr(key.type)\
+ ' on sym ' + repr(key.sym) + ') ******'
print key.t... | [
"def",
"printer",
"(",
"self",
")",
":",
"for",
"key",
"in",
"self",
".",
"statediag",
":",
"if",
"key",
".",
"trans",
"is",
"not",
"None",
"and",
"len",
"(",
"key",
".",
"trans",
")",
">",
"0",
":",
"print",
"'****** '",
"+",
"repr",
"(",
"key",... | Visualizes the current state | [
"Visualizes",
"the",
"current",
"state"
] | f5d66533573b27e155bec3f36b8c00b8e3937cb3 | https://github.com/GeorgeArgyros/symautomata/blob/f5d66533573b27e155bec3f36b8c00b8e3937cb3/symautomata/pdastring.py#L503-L509 | train | 56,147 |
GeorgeArgyros/symautomata | symautomata/pdastring.py | PdaString.init | def init(self, states, accepted):
"""Initialization of the indexing dictionaries"""
self.statediag = []
for key in states:
self.statediag.append(states[key])
self.quickresponse = {}
self.quickresponse_types = {}
self.quickresponse_types[0] = []
self.qu... | python | def init(self, states, accepted):
"""Initialization of the indexing dictionaries"""
self.statediag = []
for key in states:
self.statediag.append(states[key])
self.quickresponse = {}
self.quickresponse_types = {}
self.quickresponse_types[0] = []
self.qu... | [
"def",
"init",
"(",
"self",
",",
"states",
",",
"accepted",
")",
":",
"self",
".",
"statediag",
"=",
"[",
"]",
"for",
"key",
"in",
"states",
":",
"self",
".",
"statediag",
".",
"append",
"(",
"states",
"[",
"key",
"]",
")",
"self",
".",
"quickrespo... | Initialization of the indexing dictionaries | [
"Initialization",
"of",
"the",
"indexing",
"dictionaries"
] | f5d66533573b27e155bec3f36b8c00b8e3937cb3 | https://github.com/GeorgeArgyros/symautomata/blob/f5d66533573b27e155bec3f36b8c00b8e3937cb3/symautomata/pdastring.py#L511-L531 | train | 56,148 |
hollenstein/maspy | maspy_resources/cluster.py | execute | def execute(filelocation, outpath, executable, args=None, switchArgs=None):
"""Executes the dinosaur tool on Windows operating systems.
:param filelocation: either a single mgf file path or a list of file paths.
:param outpath: path of the output file, file must not exist
:param executable: must specif... | python | def execute(filelocation, outpath, executable, args=None, switchArgs=None):
"""Executes the dinosaur tool on Windows operating systems.
:param filelocation: either a single mgf file path or a list of file paths.
:param outpath: path of the output file, file must not exist
:param executable: must specif... | [
"def",
"execute",
"(",
"filelocation",
",",
"outpath",
",",
"executable",
",",
"args",
"=",
"None",
",",
"switchArgs",
"=",
"None",
")",
":",
"procArgs",
"=",
"[",
"'java'",
",",
"'-jar'",
",",
"executable",
"]",
"procArgs",
".",
"extend",
"(",
"[",
"'... | Executes the dinosaur tool on Windows operating systems.
:param filelocation: either a single mgf file path or a list of file paths.
:param outpath: path of the output file, file must not exist
:param executable: must specify the complete file path of the
spectra-cluster-cli.jar file, supported ver... | [
"Executes",
"the",
"dinosaur",
"tool",
"on",
"Windows",
"operating",
"systems",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy_resources/cluster.py#L41-L75 | train | 56,149 |
kevinconway/confpy | confpy/cmd.py | generate_example | def generate_example():
"""Generate a configuration file example.
This utility will load some number of Python modules which are assumed
to register options with confpy and generate an example configuration file
based on those options.
"""
cmd_args = sys.argv[1:]
parser = argparse.ArgumentP... | python | def generate_example():
"""Generate a configuration file example.
This utility will load some number of Python modules which are assumed
to register options with confpy and generate an example configuration file
based on those options.
"""
cmd_args = sys.argv[1:]
parser = argparse.ArgumentP... | [
"def",
"generate_example",
"(",
")",
":",
"cmd_args",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Confpy example generator.'",
")",
"parser",
".",
"add_argument",
"(",
"'--module'",
... | Generate a configuration file example.
This utility will load some number of Python modules which are assumed
to register options with confpy and generate an example configuration file
based on those options. | [
"Generate",
"a",
"configuration",
"file",
"example",
"."
] | 1ee8afcab46ac6915a5ff4184180434ac7b84a60 | https://github.com/kevinconway/confpy/blob/1ee8afcab46ac6915a5ff4184180434ac7b84a60/confpy/cmd.py#L16-L54 | train | 56,150 |
diamondman/proteusisc | proteusisc/bittypes.py | CompositeBitarray.count | def count(self, val=True):
"""Get the number of bits in the array with the specified value.
Args:
val: A boolean value to check against the array's value.
Returns:
An integer of the number of bits in the array equal to val.
"""
return sum((elem.count(val... | python | def count(self, val=True):
"""Get the number of bits in the array with the specified value.
Args:
val: A boolean value to check against the array's value.
Returns:
An integer of the number of bits in the array equal to val.
"""
return sum((elem.count(val... | [
"def",
"count",
"(",
"self",
",",
"val",
"=",
"True",
")",
":",
"return",
"sum",
"(",
"(",
"elem",
".",
"count",
"(",
"val",
")",
"for",
"elem",
"in",
"self",
".",
"_iter_components",
"(",
")",
")",
")"
] | Get the number of bits in the array with the specified value.
Args:
val: A boolean value to check against the array's value.
Returns:
An integer of the number of bits in the array equal to val. | [
"Get",
"the",
"number",
"of",
"bits",
"in",
"the",
"array",
"with",
"the",
"specified",
"value",
"."
] | 7622b7b04e63f9dc0f5a04429ff78d9a490c9c5c | https://github.com/diamondman/proteusisc/blob/7622b7b04e63f9dc0f5a04429ff78d9a490c9c5c/proteusisc/bittypes.py#L673-L682 | train | 56,151 |
LeastAuthority/txkube | src/txkube/_memory.py | _api_group_for_type | def _api_group_for_type(cls):
"""
Determine which Kubernetes API group a particular PClass is likely to
belong with.
This is basically nonsense. The question being asked is wrong. An
abstraction has failed somewhere. Fixing that will get rid of the need
for this.
"""
_groups = {
... | python | def _api_group_for_type(cls):
"""
Determine which Kubernetes API group a particular PClass is likely to
belong with.
This is basically nonsense. The question being asked is wrong. An
abstraction has failed somewhere. Fixing that will get rid of the need
for this.
"""
_groups = {
... | [
"def",
"_api_group_for_type",
"(",
"cls",
")",
":",
"_groups",
"=",
"{",
"(",
"u\"v1beta1\"",
",",
"u\"Deployment\"",
")",
":",
"u\"extensions\"",
",",
"(",
"u\"v1beta1\"",
",",
"u\"DeploymentList\"",
")",
":",
"u\"extensions\"",
",",
"(",
"u\"v1beta1\"",
",",
... | Determine which Kubernetes API group a particular PClass is likely to
belong with.
This is basically nonsense. The question being asked is wrong. An
abstraction has failed somewhere. Fixing that will get rid of the need
for this. | [
"Determine",
"which",
"Kubernetes",
"API",
"group",
"a",
"particular",
"PClass",
"is",
"likely",
"to",
"belong",
"with",
"."
] | a7e555d00535ff787d4b1204c264780da40cf736 | https://github.com/LeastAuthority/txkube/blob/a7e555d00535ff787d4b1204c264780da40cf736/src/txkube/_memory.py#L141-L161 | train | 56,152 |
LeastAuthority/txkube | src/txkube/_memory.py | response | def response(request, status, obj):
"""
Generate a response.
:param IRequest request: The request being responsed to.
:param int status: The response status code to set.
:param obj: Something JSON-dumpable to write into the response body.
:return bytes: The response body to write out. eg, ret... | python | def response(request, status, obj):
"""
Generate a response.
:param IRequest request: The request being responsed to.
:param int status: The response status code to set.
:param obj: Something JSON-dumpable to write into the response body.
:return bytes: The response body to write out. eg, ret... | [
"def",
"response",
"(",
"request",
",",
"status",
",",
"obj",
")",
":",
"request",
".",
"setResponseCode",
"(",
"status",
")",
"request",
".",
"responseHeaders",
".",
"setRawHeaders",
"(",
"u\"content-type\"",
",",
"[",
"u\"application/json\"",
"]",
",",
")",
... | Generate a response.
:param IRequest request: The request being responsed to.
:param int status: The response status code to set.
:param obj: Something JSON-dumpable to write into the response body.
:return bytes: The response body to write out. eg, return this from a
*render_* method. | [
"Generate",
"a",
"response",
"."
] | a7e555d00535ff787d4b1204c264780da40cf736 | https://github.com/LeastAuthority/txkube/blob/a7e555d00535ff787d4b1204c264780da40cf736/src/txkube/_memory.py#L384-L400 | train | 56,153 |
LeastAuthority/txkube | src/txkube/_memory.py | _KubernetesState.create | def create(self, collection_name, obj):
"""
Create a new object in the named collection.
:param unicode collection_name: The name of the collection in which to
create the object.
:param IObject obj: A description of the object to create.
:return _KubernetesState: A... | python | def create(self, collection_name, obj):
"""
Create a new object in the named collection.
:param unicode collection_name: The name of the collection in which to
create the object.
:param IObject obj: A description of the object to create.
:return _KubernetesState: A... | [
"def",
"create",
"(",
"self",
",",
"collection_name",
",",
"obj",
")",
":",
"obj",
"=",
"self",
".",
"agency",
".",
"before_create",
"(",
"self",
",",
"obj",
")",
"new",
"=",
"self",
".",
"agency",
".",
"after_create",
"(",
"self",
",",
"obj",
")",
... | Create a new object in the named collection.
:param unicode collection_name: The name of the collection in which to
create the object.
:param IObject obj: A description of the object to create.
:return _KubernetesState: A new state based on the current state but
also c... | [
"Create",
"a",
"new",
"object",
"in",
"the",
"named",
"collection",
"."
] | a7e555d00535ff787d4b1204c264780da40cf736 | https://github.com/LeastAuthority/txkube/blob/a7e555d00535ff787d4b1204c264780da40cf736/src/txkube/_memory.py#L320-L338 | train | 56,154 |
LeastAuthority/txkube | src/txkube/_memory.py | _KubernetesState.replace | def replace(self, collection_name, old, new):
"""
Replace an existing object with a new version of it.
:param unicode collection_name: The name of the collection in which to
replace an object.
:param IObject old: A description of the object being replaced.
:param I... | python | def replace(self, collection_name, old, new):
"""
Replace an existing object with a new version of it.
:param unicode collection_name: The name of the collection in which to
replace an object.
:param IObject old: A description of the object being replaced.
:param I... | [
"def",
"replace",
"(",
"self",
",",
"collection_name",
",",
"old",
",",
"new",
")",
":",
"self",
".",
"agency",
".",
"before_replace",
"(",
"self",
",",
"old",
",",
"new",
")",
"updated",
"=",
"self",
".",
"transform",
"(",
"[",
"collection_name",
"]",... | Replace an existing object with a new version of it.
:param unicode collection_name: The name of the collection in which to
replace an object.
:param IObject old: A description of the object being replaced.
:param IObject new: A description of the object to take the place of
... | [
"Replace",
"an",
"existing",
"object",
"with",
"a",
"new",
"version",
"of",
"it",
"."
] | a7e555d00535ff787d4b1204c264780da40cf736 | https://github.com/LeastAuthority/txkube/blob/a7e555d00535ff787d4b1204c264780da40cf736/src/txkube/_memory.py#L341-L361 | train | 56,155 |
sprockets/sprockets.clients.statsd | sprockets/clients/statsd/__init__.py | execution_timer | def execution_timer(value):
"""The ``execution_timer`` decorator allows for easy instrumentation of
the duration of function calls, using the method name in the key.
The following example would add duration timing with the key ``my_function``
.. code: python
@statsd.execution_timer
de... | python | def execution_timer(value):
"""The ``execution_timer`` decorator allows for easy instrumentation of
the duration of function calls, using the method name in the key.
The following example would add duration timing with the key ``my_function``
.. code: python
@statsd.execution_timer
de... | [
"def",
"execution_timer",
"(",
"value",
")",
":",
"def",
"_invoke",
"(",
"method",
",",
"key_arg_position",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"result",
"=",
"method",
"(",
"*",
"arg... | The ``execution_timer`` decorator allows for easy instrumentation of
the duration of function calls, using the method name in the key.
The following example would add duration timing with the key ``my_function``
.. code: python
@statsd.execution_timer
def my_function(foo):
pas... | [
"The",
"execution_timer",
"decorator",
"allows",
"for",
"easy",
"instrumentation",
"of",
"the",
"duration",
"of",
"function",
"calls",
"using",
"the",
"method",
"name",
"in",
"the",
"key",
"."
] | 34daf6972ebdc5ed1e8fde2ff85b3443b9c04d2c | https://github.com/sprockets/sprockets.clients.statsd/blob/34daf6972ebdc5ed1e8fde2ff85b3443b9c04d2c/sprockets/clients/statsd/__init__.py#L67-L112 | train | 56,156 |
jplusplus/statscraper | statscraper/scrapers/StatistikcentralenScraper.py | Statistikcentralen._get_lang | def _get_lang(self, *args, **kwargs):
""" Let users select language
"""
if "lang" in kwargs:
if kwargs["lang"] in self._available_languages:
self.lang = kwargs["lang"] | python | def _get_lang(self, *args, **kwargs):
""" Let users select language
"""
if "lang" in kwargs:
if kwargs["lang"] in self._available_languages:
self.lang = kwargs["lang"] | [
"def",
"_get_lang",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"\"lang\"",
"in",
"kwargs",
":",
"if",
"kwargs",
"[",
"\"lang\"",
"]",
"in",
"self",
".",
"_available_languages",
":",
"self",
".",
"lang",
"=",
"kwargs",
"["... | Let users select language | [
"Let",
"users",
"select",
"language"
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/scrapers/StatistikcentralenScraper.py#L25-L30 | train | 56,157 |
achiku/hipnotify | hipnotify/hipnotify.py | Room.notify | def notify(self, msg, color='green', notify='true', message_format='text'):
"""Send notification to specified HipChat room"""
self.message_dict = {
'message': msg,
'color': color,
'notify': notify,
'message_format': message_format,
}
if not... | python | def notify(self, msg, color='green', notify='true', message_format='text'):
"""Send notification to specified HipChat room"""
self.message_dict = {
'message': msg,
'color': color,
'notify': notify,
'message_format': message_format,
}
if not... | [
"def",
"notify",
"(",
"self",
",",
"msg",
",",
"color",
"=",
"'green'",
",",
"notify",
"=",
"'true'",
",",
"message_format",
"=",
"'text'",
")",
":",
"self",
".",
"message_dict",
"=",
"{",
"'message'",
":",
"msg",
",",
"'color'",
":",
"color",
",",
"... | Send notification to specified HipChat room | [
"Send",
"notification",
"to",
"specified",
"HipChat",
"room"
] | 749f5dba25c8a5a9f9d8318b720671be3e6dd7ac | https://github.com/achiku/hipnotify/blob/749f5dba25c8a5a9f9d8318b720671be3e6dd7ac/hipnotify/hipnotify.py#L24-L40 | train | 56,158 |
sporsh/carnifex | fabfile.py | trial | def trial(path=TESTS_PATH, coverage=False):
"""Run tests using trial
"""
args = ['trial']
if coverage:
args.append('--coverage')
args.append(path)
print args
local(' '.join(args)) | python | def trial(path=TESTS_PATH, coverage=False):
"""Run tests using trial
"""
args = ['trial']
if coverage:
args.append('--coverage')
args.append(path)
print args
local(' '.join(args)) | [
"def",
"trial",
"(",
"path",
"=",
"TESTS_PATH",
",",
"coverage",
"=",
"False",
")",
":",
"args",
"=",
"[",
"'trial'",
"]",
"if",
"coverage",
":",
"args",
".",
"append",
"(",
"'--coverage'",
")",
"args",
".",
"append",
"(",
"path",
")",
"print",
"args... | Run tests using trial | [
"Run",
"tests",
"using",
"trial"
] | 82dd3bd2bc134dfb69a78f43171e227f2127060b | https://github.com/sporsh/carnifex/blob/82dd3bd2bc134dfb69a78f43171e227f2127060b/fabfile.py#L22-L30 | train | 56,159 |
Equitable/trump | trump/tools/reprobj.py | ReprObjType.process_result_value | def process_result_value(self, value, dialect):
"""
When SQLAlchemy gets the string representation from a ReprObjType
column, it converts it to the python equivalent via exec.
"""
if value is not None:
cmd = "value = {}".format(value)
exec(cmd)
ret... | python | def process_result_value(self, value, dialect):
"""
When SQLAlchemy gets the string representation from a ReprObjType
column, it converts it to the python equivalent via exec.
"""
if value is not None:
cmd = "value = {}".format(value)
exec(cmd)
ret... | [
"def",
"process_result_value",
"(",
"self",
",",
"value",
",",
"dialect",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"cmd",
"=",
"\"value = {}\"",
".",
"format",
"(",
"value",
")",
"exec",
"(",
"cmd",
")",
"return",
"value"
] | When SQLAlchemy gets the string representation from a ReprObjType
column, it converts it to the python equivalent via exec. | [
"When",
"SQLAlchemy",
"gets",
"the",
"string",
"representation",
"from",
"a",
"ReprObjType",
"column",
"it",
"converts",
"it",
"to",
"the",
"python",
"equivalent",
"via",
"exec",
"."
] | a2802692bc642fa32096374159eea7ceca2947b4 | https://github.com/Equitable/trump/blob/a2802692bc642fa32096374159eea7ceca2947b4/trump/tools/reprobj.py#L43-L51 | train | 56,160 |
Cadasta/django-tutelary | tutelary/engine.py | make_regex | def make_regex(separator):
"""Utility function to create regexp for matching escaped separators
in strings.
"""
return re.compile(r'(?:' + re.escape(separator) + r')?((?:[^' +
re.escape(separator) + r'\\]|\\.)+)') | python | def make_regex(separator):
"""Utility function to create regexp for matching escaped separators
in strings.
"""
return re.compile(r'(?:' + re.escape(separator) + r')?((?:[^' +
re.escape(separator) + r'\\]|\\.)+)') | [
"def",
"make_regex",
"(",
"separator",
")",
":",
"return",
"re",
".",
"compile",
"(",
"r'(?:'",
"+",
"re",
".",
"escape",
"(",
"separator",
")",
"+",
"r')?((?:[^'",
"+",
"re",
".",
"escape",
"(",
"separator",
")",
"+",
"r'\\\\]|\\\\.)+)'",
")"
] | Utility function to create regexp for matching escaped separators
in strings. | [
"Utility",
"function",
"to",
"create",
"regexp",
"for",
"matching",
"escaped",
"separators",
"in",
"strings",
"."
] | 66bb05de7098777c0a383410c287bf48433cde87 | https://github.com/Cadasta/django-tutelary/blob/66bb05de7098777c0a383410c287bf48433cde87/tutelary/engine.py#L309-L315 | train | 56,161 |
Cadasta/django-tutelary | tutelary/engine.py | strip_comments | def strip_comments(text):
"""Comment stripper for JSON.
"""
regex = r'\s*(#|\/{2}).*$'
regex_inline = r'(:?(?:\s)*([A-Za-z\d\.{}]*)|((?<=\").*\"),?)(?:\s)*(((#|(\/{2})).*)|)$' # noqa
lines = text.split('\n')
for index, line in enumerate(lines):
if re.search(regex, line):
i... | python | def strip_comments(text):
"""Comment stripper for JSON.
"""
regex = r'\s*(#|\/{2}).*$'
regex_inline = r'(:?(?:\s)*([A-Za-z\d\.{}]*)|((?<=\").*\"),?)(?:\s)*(((#|(\/{2})).*)|)$' # noqa
lines = text.split('\n')
for index, line in enumerate(lines):
if re.search(regex, line):
i... | [
"def",
"strip_comments",
"(",
"text",
")",
":",
"regex",
"=",
"r'\\s*(#|\\/{2}).*$'",
"regex_inline",
"=",
"r'(:?(?:\\s)*([A-Za-z\\d\\.{}]*)|((?<=\\\").*\\\"),?)(?:\\s)*(((#|(\\/{2})).*)|)$'",
"# noqa",
"lines",
"=",
"text",
".",
"split",
"(",
"'\\n'",
")",
"for",
"index"... | Comment stripper for JSON. | [
"Comment",
"stripper",
"for",
"JSON",
"."
] | 66bb05de7098777c0a383410c287bf48433cde87 | https://github.com/Cadasta/django-tutelary/blob/66bb05de7098777c0a383410c287bf48433cde87/tutelary/engine.py#L332-L347 | train | 56,162 |
Cadasta/django-tutelary | tutelary/engine.py | Action.register | def register(action):
"""Action registration is used to support generating lists of
permitted actions from a permission set and an object pattern.
Only registered actions will be returned by such queries.
"""
if isinstance(action, str):
Action.register(Action(action)... | python | def register(action):
"""Action registration is used to support generating lists of
permitted actions from a permission set and an object pattern.
Only registered actions will be returned by such queries.
"""
if isinstance(action, str):
Action.register(Action(action)... | [
"def",
"register",
"(",
"action",
")",
":",
"if",
"isinstance",
"(",
"action",
",",
"str",
")",
":",
"Action",
".",
"register",
"(",
"Action",
"(",
"action",
")",
")",
"elif",
"isinstance",
"(",
"action",
",",
"Action",
")",
":",
"Action",
".",
"regi... | Action registration is used to support generating lists of
permitted actions from a permission set and an object pattern.
Only registered actions will be returned by such queries. | [
"Action",
"registration",
"is",
"used",
"to",
"support",
"generating",
"lists",
"of",
"permitted",
"actions",
"from",
"a",
"permission",
"set",
"and",
"an",
"object",
"pattern",
".",
"Only",
"registered",
"actions",
"will",
"be",
"returned",
"by",
"such",
"que... | 66bb05de7098777c0a383410c287bf48433cde87 | https://github.com/Cadasta/django-tutelary/blob/66bb05de7098777c0a383410c287bf48433cde87/tutelary/engine.py#L108-L120 | train | 56,163 |
Cadasta/django-tutelary | tutelary/engine.py | PermissionTree.allow | def allow(self, act, obj=None):
"""Determine where a given action on a given object is allowed.
"""
objc = obj.components if obj is not None else []
try:
return self.tree[act.components + objc] == 'allow'
except KeyError:
return False | python | def allow(self, act, obj=None):
"""Determine where a given action on a given object is allowed.
"""
objc = obj.components if obj is not None else []
try:
return self.tree[act.components + objc] == 'allow'
except KeyError:
return False | [
"def",
"allow",
"(",
"self",
",",
"act",
",",
"obj",
"=",
"None",
")",
":",
"objc",
"=",
"obj",
".",
"components",
"if",
"obj",
"is",
"not",
"None",
"else",
"[",
"]",
"try",
":",
"return",
"self",
".",
"tree",
"[",
"act",
".",
"components",
"+",
... | Determine where a given action on a given object is allowed. | [
"Determine",
"where",
"a",
"given",
"action",
"on",
"a",
"given",
"object",
"is",
"allowed",
"."
] | 66bb05de7098777c0a383410c287bf48433cde87 | https://github.com/Cadasta/django-tutelary/blob/66bb05de7098777c0a383410c287bf48433cde87/tutelary/engine.py#L286-L294 | train | 56,164 |
Cadasta/django-tutelary | tutelary/engine.py | PermissionTree.permitted_actions | def permitted_actions(self, obj=None):
"""Determine permitted actions for a given object pattern.
"""
return [a for a in Action.registered
if self.allow(a, obj(str(a)) if obj is not None else None)] | python | def permitted_actions(self, obj=None):
"""Determine permitted actions for a given object pattern.
"""
return [a for a in Action.registered
if self.allow(a, obj(str(a)) if obj is not None else None)] | [
"def",
"permitted_actions",
"(",
"self",
",",
"obj",
"=",
"None",
")",
":",
"return",
"[",
"a",
"for",
"a",
"in",
"Action",
".",
"registered",
"if",
"self",
".",
"allow",
"(",
"a",
",",
"obj",
"(",
"str",
"(",
"a",
")",
")",
"if",
"obj",
"is",
... | Determine permitted actions for a given object pattern. | [
"Determine",
"permitted",
"actions",
"for",
"a",
"given",
"object",
"pattern",
"."
] | 66bb05de7098777c0a383410c287bf48433cde87 | https://github.com/Cadasta/django-tutelary/blob/66bb05de7098777c0a383410c287bf48433cde87/tutelary/engine.py#L296-L301 | train | 56,165 |
debugloop/saltobserver | saltobserver/websockets.py | subscribe | def subscribe(ws):
"""WebSocket endpoint, used for liveupdates"""
while ws is not None:
gevent.sleep(0.1)
try:
message = ws.receive() # expect function name to subscribe to
if message:
stream.register(ws, message)
except WebSocketError:
... | python | def subscribe(ws):
"""WebSocket endpoint, used for liveupdates"""
while ws is not None:
gevent.sleep(0.1)
try:
message = ws.receive() # expect function name to subscribe to
if message:
stream.register(ws, message)
except WebSocketError:
... | [
"def",
"subscribe",
"(",
"ws",
")",
":",
"while",
"ws",
"is",
"not",
"None",
":",
"gevent",
".",
"sleep",
"(",
"0.1",
")",
"try",
":",
"message",
"=",
"ws",
".",
"receive",
"(",
")",
"# expect function name to subscribe to",
"if",
"message",
":",
"stream... | WebSocket endpoint, used for liveupdates | [
"WebSocket",
"endpoint",
"used",
"for",
"liveupdates"
] | 55ff20aa2d2504fb85fa2f63cc9b52934245b849 | https://github.com/debugloop/saltobserver/blob/55ff20aa2d2504fb85fa2f63cc9b52934245b849/saltobserver/websockets.py#L11-L20 | train | 56,166 |
botstory/botstory | botstory/ast/story_context/__init__.py | StoryContext.could_scope_out | def could_scope_out(self):
"""
could bubble up from current scope
:return:
"""
return not self.waiting_for or \
isinstance(self.waiting_for, callable.EndOfStory) or \
self.is_breaking_a_loop() | python | def could_scope_out(self):
"""
could bubble up from current scope
:return:
"""
return not self.waiting_for or \
isinstance(self.waiting_for, callable.EndOfStory) or \
self.is_breaking_a_loop() | [
"def",
"could_scope_out",
"(",
"self",
")",
":",
"return",
"not",
"self",
".",
"waiting_for",
"or",
"isinstance",
"(",
"self",
".",
"waiting_for",
",",
"callable",
".",
"EndOfStory",
")",
"or",
"self",
".",
"is_breaking_a_loop",
"(",
")"
] | could bubble up from current scope
:return: | [
"could",
"bubble",
"up",
"from",
"current",
"scope"
] | 9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3 | https://github.com/botstory/botstory/blob/9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3/botstory/ast/story_context/__init__.py#L41-L49 | train | 56,167 |
rogerhil/thegamesdb | thegamesdb/item.py | BaseItem.alias | def alias(self):
""" If the _alias cache is None, just build the alias from the item
name.
"""
if self._alias is None:
if self.name in self.aliases_fix:
self._alias = self.aliases_fix[self.name]
else:
self._alias = self.name.lower()... | python | def alias(self):
""" If the _alias cache is None, just build the alias from the item
name.
"""
if self._alias is None:
if self.name in self.aliases_fix:
self._alias = self.aliases_fix[self.name]
else:
self._alias = self.name.lower()... | [
"def",
"alias",
"(",
"self",
")",
":",
"if",
"self",
".",
"_alias",
"is",
"None",
":",
"if",
"self",
".",
"name",
"in",
"self",
".",
"aliases_fix",
":",
"self",
".",
"_alias",
"=",
"self",
".",
"aliases_fix",
"[",
"self",
".",
"name",
"]",
"else",
... | If the _alias cache is None, just build the alias from the item
name. | [
"If",
"the",
"_alias",
"cache",
"is",
"None",
"just",
"build",
"the",
"alias",
"from",
"the",
"item",
"name",
"."
] | 795314215f9ee73697c7520dea4ddecfb23ca8e6 | https://github.com/rogerhil/thegamesdb/blob/795314215f9ee73697c7520dea4ddecfb23ca8e6/thegamesdb/item.py#L99-L111 | train | 56,168 |
xtream1101/cutil | cutil/config.py | Config.load_configs | def load_configs(self, conf_file):
"""
Assumes that the config file does not have any sections, so throw it all in global
"""
with open(conf_file) as stream:
lines = itertools.chain(("[global]",), stream)
self._config.read_file(lines)
return self._config['... | python | def load_configs(self, conf_file):
"""
Assumes that the config file does not have any sections, so throw it all in global
"""
with open(conf_file) as stream:
lines = itertools.chain(("[global]",), stream)
self._config.read_file(lines)
return self._config['... | [
"def",
"load_configs",
"(",
"self",
",",
"conf_file",
")",
":",
"with",
"open",
"(",
"conf_file",
")",
"as",
"stream",
":",
"lines",
"=",
"itertools",
".",
"chain",
"(",
"(",
"\"[global]\"",
",",
")",
",",
"stream",
")",
"self",
".",
"_config",
".",
... | Assumes that the config file does not have any sections, so throw it all in global | [
"Assumes",
"that",
"the",
"config",
"file",
"does",
"not",
"have",
"any",
"sections",
"so",
"throw",
"it",
"all",
"in",
"global"
] | 2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8 | https://github.com/xtream1101/cutil/blob/2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8/cutil/config.py#L12-L19 | train | 56,169 |
xtream1101/cutil | cutil/config.py | Config.remove_quotes | def remove_quotes(self, configs):
"""
Because some values are wraped in single quotes
"""
for key in configs:
value = configs[key]
if value[0] == "'" and value[-1] == "'":
configs[key] = value[1:-1]
return configs | python | def remove_quotes(self, configs):
"""
Because some values are wraped in single quotes
"""
for key in configs:
value = configs[key]
if value[0] == "'" and value[-1] == "'":
configs[key] = value[1:-1]
return configs | [
"def",
"remove_quotes",
"(",
"self",
",",
"configs",
")",
":",
"for",
"key",
"in",
"configs",
":",
"value",
"=",
"configs",
"[",
"key",
"]",
"if",
"value",
"[",
"0",
"]",
"==",
"\"'\"",
"and",
"value",
"[",
"-",
"1",
"]",
"==",
"\"'\"",
":",
"con... | Because some values are wraped in single quotes | [
"Because",
"some",
"values",
"are",
"wraped",
"in",
"single",
"quotes"
] | 2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8 | https://github.com/xtream1101/cutil/blob/2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8/cutil/config.py#L21-L29 | train | 56,170 |
xtream1101/cutil | cutil/__init__.py | chunks_of | def chunks_of(max_chunk_size, list_to_chunk):
"""
Yields the list with a max size of max_chunk_size
"""
for i in range(0, len(list_to_chunk), max_chunk_size):
yield list_to_chunk[i:i + max_chunk_size] | python | def chunks_of(max_chunk_size, list_to_chunk):
"""
Yields the list with a max size of max_chunk_size
"""
for i in range(0, len(list_to_chunk), max_chunk_size):
yield list_to_chunk[i:i + max_chunk_size] | [
"def",
"chunks_of",
"(",
"max_chunk_size",
",",
"list_to_chunk",
")",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"list_to_chunk",
")",
",",
"max_chunk_size",
")",
":",
"yield",
"list_to_chunk",
"[",
"i",
":",
"i",
"+",
"max_chunk_size",
"... | Yields the list with a max size of max_chunk_size | [
"Yields",
"the",
"list",
"with",
"a",
"max",
"size",
"of",
"max_chunk_size"
] | 2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8 | https://github.com/xtream1101/cutil/blob/2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8/cutil/__init__.py#L216-L221 | train | 56,171 |
xtream1101/cutil | cutil/__init__.py | split_into | def split_into(max_num_chunks, list_to_chunk):
"""
Yields the list with a max total size of max_num_chunks
"""
max_chunk_size = math.ceil(len(list_to_chunk) / max_num_chunks)
return chunks_of(max_chunk_size, list_to_chunk) | python | def split_into(max_num_chunks, list_to_chunk):
"""
Yields the list with a max total size of max_num_chunks
"""
max_chunk_size = math.ceil(len(list_to_chunk) / max_num_chunks)
return chunks_of(max_chunk_size, list_to_chunk) | [
"def",
"split_into",
"(",
"max_num_chunks",
",",
"list_to_chunk",
")",
":",
"max_chunk_size",
"=",
"math",
".",
"ceil",
"(",
"len",
"(",
"list_to_chunk",
")",
"/",
"max_num_chunks",
")",
"return",
"chunks_of",
"(",
"max_chunk_size",
",",
"list_to_chunk",
")"
] | Yields the list with a max total size of max_num_chunks | [
"Yields",
"the",
"list",
"with",
"a",
"max",
"total",
"size",
"of",
"max_num_chunks"
] | 2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8 | https://github.com/xtream1101/cutil/blob/2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8/cutil/__init__.py#L224-L229 | train | 56,172 |
xtream1101/cutil | cutil/__init__.py | get_proxy_parts | def get_proxy_parts(proxy):
"""
Take a proxy url and break it up to its parts
"""
proxy_parts = {'schema': None,
'user': None,
'password': None,
'host': None,
'port': None,
}
# Find parts
results = re.... | python | def get_proxy_parts(proxy):
"""
Take a proxy url and break it up to its parts
"""
proxy_parts = {'schema': None,
'user': None,
'password': None,
'host': None,
'port': None,
}
# Find parts
results = re.... | [
"def",
"get_proxy_parts",
"(",
"proxy",
")",
":",
"proxy_parts",
"=",
"{",
"'schema'",
":",
"None",
",",
"'user'",
":",
"None",
",",
"'password'",
":",
"None",
",",
"'host'",
":",
"None",
",",
"'port'",
":",
"None",
",",
"}",
"# Find parts",
"results",
... | Take a proxy url and break it up to its parts | [
"Take",
"a",
"proxy",
"url",
"and",
"break",
"it",
"up",
"to",
"its",
"parts"
] | 2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8 | https://github.com/xtream1101/cutil/blob/2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8/cutil/__init__.py#L501-L524 | train | 56,173 |
xtream1101/cutil | cutil/__init__.py | remove_html_tag | def remove_html_tag(input_str='', tag=None):
"""
Returns a string with the html tag and all its contents from a string
"""
result = input_str
if tag is not None:
pattern = re.compile('<{tag}[\s\S]+?/{tag}>'.format(tag=tag))
result = re.sub(pattern, '', str(input_str))
return res... | python | def remove_html_tag(input_str='', tag=None):
"""
Returns a string with the html tag and all its contents from a string
"""
result = input_str
if tag is not None:
pattern = re.compile('<{tag}[\s\S]+?/{tag}>'.format(tag=tag))
result = re.sub(pattern, '', str(input_str))
return res... | [
"def",
"remove_html_tag",
"(",
"input_str",
"=",
"''",
",",
"tag",
"=",
"None",
")",
":",
"result",
"=",
"input_str",
"if",
"tag",
"is",
"not",
"None",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"'<{tag}[\\s\\S]+?/{tag}>'",
".",
"format",
"(",
"tag"... | Returns a string with the html tag and all its contents from a string | [
"Returns",
"a",
"string",
"with",
"the",
"html",
"tag",
"and",
"all",
"its",
"contents",
"from",
"a",
"string"
] | 2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8 | https://github.com/xtream1101/cutil/blob/2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8/cutil/__init__.py#L527-L536 | train | 56,174 |
yolothreat/utilitybelt | utilitybelt/utilitybelt.py | ip_between | def ip_between(ip, start, finish):
"""Checks to see if IP is between start and finish"""
if is_IPv4Address(ip) and is_IPv4Address(start) and is_IPv4Address(finish):
return IPAddress(ip) in IPRange(start, finish)
else:
return False | python | def ip_between(ip, start, finish):
"""Checks to see if IP is between start and finish"""
if is_IPv4Address(ip) and is_IPv4Address(start) and is_IPv4Address(finish):
return IPAddress(ip) in IPRange(start, finish)
else:
return False | [
"def",
"ip_between",
"(",
"ip",
",",
"start",
",",
"finish",
")",
":",
"if",
"is_IPv4Address",
"(",
"ip",
")",
"and",
"is_IPv4Address",
"(",
"start",
")",
"and",
"is_IPv4Address",
"(",
"finish",
")",
":",
"return",
"IPAddress",
"(",
"ip",
")",
"in",
"I... | Checks to see if IP is between start and finish | [
"Checks",
"to",
"see",
"if",
"IP",
"is",
"between",
"start",
"and",
"finish"
] | 55ac6c31f87963d5e97be0402a4343c84846d118 | https://github.com/yolothreat/utilitybelt/blob/55ac6c31f87963d5e97be0402a4343c84846d118/utilitybelt/utilitybelt.py#L75-L81 | train | 56,175 |
yolothreat/utilitybelt | utilitybelt/utilitybelt.py | is_rfc1918 | def is_rfc1918(ip):
"""Checks to see if an IP address is used for local communications within
a private network as specified by RFC 1918
"""
if ip_between(ip, "10.0.0.0", "10.255.255.255"):
return True
elif ip_between(ip, "172.16.0.0", "172.31.255.255"):
return True
elif ip_betwe... | python | def is_rfc1918(ip):
"""Checks to see if an IP address is used for local communications within
a private network as specified by RFC 1918
"""
if ip_between(ip, "10.0.0.0", "10.255.255.255"):
return True
elif ip_between(ip, "172.16.0.0", "172.31.255.255"):
return True
elif ip_betwe... | [
"def",
"is_rfc1918",
"(",
"ip",
")",
":",
"if",
"ip_between",
"(",
"ip",
",",
"\"10.0.0.0\"",
",",
"\"10.255.255.255\"",
")",
":",
"return",
"True",
"elif",
"ip_between",
"(",
"ip",
",",
"\"172.16.0.0\"",
",",
"\"172.31.255.255\"",
")",
":",
"return",
"True"... | Checks to see if an IP address is used for local communications within
a private network as specified by RFC 1918 | [
"Checks",
"to",
"see",
"if",
"an",
"IP",
"address",
"is",
"used",
"for",
"local",
"communications",
"within",
"a",
"private",
"network",
"as",
"specified",
"by",
"RFC",
"1918"
] | 55ac6c31f87963d5e97be0402a4343c84846d118 | https://github.com/yolothreat/utilitybelt/blob/55ac6c31f87963d5e97be0402a4343c84846d118/utilitybelt/utilitybelt.py#L84-L95 | train | 56,176 |
yolothreat/utilitybelt | utilitybelt/utilitybelt.py | is_reserved | def is_reserved(ip):
"""Checks to see if an IP address is reserved for special purposes. This includes
all of the RFC 1918 addresses as well as other blocks that are reserved by
IETF, and IANA for various reasons.
https://en.wikipedia.org/wiki/Reserved_IP_addresses
"""
if ip_between(ip, "0.0.0.... | python | def is_reserved(ip):
"""Checks to see if an IP address is reserved for special purposes. This includes
all of the RFC 1918 addresses as well as other blocks that are reserved by
IETF, and IANA for various reasons.
https://en.wikipedia.org/wiki/Reserved_IP_addresses
"""
if ip_between(ip, "0.0.0.... | [
"def",
"is_reserved",
"(",
"ip",
")",
":",
"if",
"ip_between",
"(",
"ip",
",",
"\"0.0.0.0\"",
",",
"\"0.255.255.255\"",
")",
":",
"return",
"True",
"elif",
"ip_between",
"(",
"ip",
",",
"\"10.0.0.0\"",
",",
"\"10.255.255.255\"",
")",
":",
"return",
"True",
... | Checks to see if an IP address is reserved for special purposes. This includes
all of the RFC 1918 addresses as well as other blocks that are reserved by
IETF, and IANA for various reasons.
https://en.wikipedia.org/wiki/Reserved_IP_addresses | [
"Checks",
"to",
"see",
"if",
"an",
"IP",
"address",
"is",
"reserved",
"for",
"special",
"purposes",
".",
"This",
"includes",
"all",
"of",
"the",
"RFC",
"1918",
"addresses",
"as",
"well",
"as",
"other",
"blocks",
"that",
"are",
"reserved",
"by",
"IETF",
"... | 55ac6c31f87963d5e97be0402a4343c84846d118 | https://github.com/yolothreat/utilitybelt/blob/55ac6c31f87963d5e97be0402a4343c84846d118/utilitybelt/utilitybelt.py#L98-L134 | train | 56,177 |
yolothreat/utilitybelt | utilitybelt/utilitybelt.py | is_hash | def is_hash(fhash):
"""Returns true for valid hashes, false for invalid."""
# Intentionally doing if/else statement for ease of testing and reading
if re.match(re_md5, fhash):
return True
elif re.match(re_sha1, fhash):
return True
elif re.match(re_sha256, fhash):
return True... | python | def is_hash(fhash):
"""Returns true for valid hashes, false for invalid."""
# Intentionally doing if/else statement for ease of testing and reading
if re.match(re_md5, fhash):
return True
elif re.match(re_sha1, fhash):
return True
elif re.match(re_sha256, fhash):
return True... | [
"def",
"is_hash",
"(",
"fhash",
")",
":",
"# Intentionally doing if/else statement for ease of testing and reading",
"if",
"re",
".",
"match",
"(",
"re_md5",
",",
"fhash",
")",
":",
"return",
"True",
"elif",
"re",
".",
"match",
"(",
"re_sha1",
",",
"fhash",
")",... | Returns true for valid hashes, false for invalid. | [
"Returns",
"true",
"for",
"valid",
"hashes",
"false",
"for",
"invalid",
"."
] | 55ac6c31f87963d5e97be0402a4343c84846d118 | https://github.com/yolothreat/utilitybelt/blob/55ac6c31f87963d5e97be0402a4343c84846d118/utilitybelt/utilitybelt.py#L172-L187 | train | 56,178 |
yolothreat/utilitybelt | utilitybelt/utilitybelt.py | reverse_dns_sna | def reverse_dns_sna(ipaddress):
"""Returns a list of the dns names that point to a given ipaddress using StatDNS API"""
r = requests.get("http://api.statdns.com/x/%s" % ipaddress)
if r.status_code == 200:
names = []
for item in r.json()['answer']:
name = str(item['rdata']).str... | python | def reverse_dns_sna(ipaddress):
"""Returns a list of the dns names that point to a given ipaddress using StatDNS API"""
r = requests.get("http://api.statdns.com/x/%s" % ipaddress)
if r.status_code == 200:
names = []
for item in r.json()['answer']:
name = str(item['rdata']).str... | [
"def",
"reverse_dns_sna",
"(",
"ipaddress",
")",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"\"http://api.statdns.com/x/%s\"",
"%",
"ipaddress",
")",
"if",
"r",
".",
"status_code",
"==",
"200",
":",
"names",
"=",
"[",
"]",
"for",
"item",
"in",
"r",
".",... | Returns a list of the dns names that point to a given ipaddress using StatDNS API | [
"Returns",
"a",
"list",
"of",
"the",
"dns",
"names",
"that",
"point",
"to",
"a",
"given",
"ipaddress",
"using",
"StatDNS",
"API"
] | 55ac6c31f87963d5e97be0402a4343c84846d118 | https://github.com/yolothreat/utilitybelt/blob/55ac6c31f87963d5e97be0402a4343c84846d118/utilitybelt/utilitybelt.py#L259-L274 | train | 56,179 |
yolothreat/utilitybelt | utilitybelt/utilitybelt.py | vt_ip_check | def vt_ip_check(ip, vt_api):
"""Checks VirusTotal for occurrences of an IP address"""
if not is_IPv4Address(ip):
return None
url = 'https://www.virustotal.com/vtapi/v2/ip-address/report'
parameters = {'ip': ip, 'apikey': vt_api}
response = requests.get(url, params=parameters)
try:
... | python | def vt_ip_check(ip, vt_api):
"""Checks VirusTotal for occurrences of an IP address"""
if not is_IPv4Address(ip):
return None
url = 'https://www.virustotal.com/vtapi/v2/ip-address/report'
parameters = {'ip': ip, 'apikey': vt_api}
response = requests.get(url, params=parameters)
try:
... | [
"def",
"vt_ip_check",
"(",
"ip",
",",
"vt_api",
")",
":",
"if",
"not",
"is_IPv4Address",
"(",
"ip",
")",
":",
"return",
"None",
"url",
"=",
"'https://www.virustotal.com/vtapi/v2/ip-address/report'",
"parameters",
"=",
"{",
"'ip'",
":",
"ip",
",",
"'apikey'",
"... | Checks VirusTotal for occurrences of an IP address | [
"Checks",
"VirusTotal",
"for",
"occurrences",
"of",
"an",
"IP",
"address"
] | 55ac6c31f87963d5e97be0402a4343c84846d118 | https://github.com/yolothreat/utilitybelt/blob/55ac6c31f87963d5e97be0402a4343c84846d118/utilitybelt/utilitybelt.py#L284-L295 | train | 56,180 |
yolothreat/utilitybelt | utilitybelt/utilitybelt.py | vt_name_check | def vt_name_check(domain, vt_api):
"""Checks VirusTotal for occurrences of a domain name"""
if not is_fqdn(domain):
return None
url = 'https://www.virustotal.com/vtapi/v2/domain/report'
parameters = {'domain': domain, 'apikey': vt_api}
response = requests.get(url, params=parameters)
try... | python | def vt_name_check(domain, vt_api):
"""Checks VirusTotal for occurrences of a domain name"""
if not is_fqdn(domain):
return None
url = 'https://www.virustotal.com/vtapi/v2/domain/report'
parameters = {'domain': domain, 'apikey': vt_api}
response = requests.get(url, params=parameters)
try... | [
"def",
"vt_name_check",
"(",
"domain",
",",
"vt_api",
")",
":",
"if",
"not",
"is_fqdn",
"(",
"domain",
")",
":",
"return",
"None",
"url",
"=",
"'https://www.virustotal.com/vtapi/v2/domain/report'",
"parameters",
"=",
"{",
"'domain'",
":",
"domain",
",",
"'apikey... | Checks VirusTotal for occurrences of a domain name | [
"Checks",
"VirusTotal",
"for",
"occurrences",
"of",
"a",
"domain",
"name"
] | 55ac6c31f87963d5e97be0402a4343c84846d118 | https://github.com/yolothreat/utilitybelt/blob/55ac6c31f87963d5e97be0402a4343c84846d118/utilitybelt/utilitybelt.py#L298-L309 | train | 56,181 |
yolothreat/utilitybelt | utilitybelt/utilitybelt.py | vt_hash_check | def vt_hash_check(fhash, vt_api):
"""Checks VirusTotal for occurrences of a file hash"""
if not is_hash(fhash):
return None
url = 'https://www.virustotal.com/vtapi/v2/file/report'
parameters = {'resource': fhash, 'apikey': vt_api}
response = requests.get(url, params=parameters)
try:
... | python | def vt_hash_check(fhash, vt_api):
"""Checks VirusTotal for occurrences of a file hash"""
if not is_hash(fhash):
return None
url = 'https://www.virustotal.com/vtapi/v2/file/report'
parameters = {'resource': fhash, 'apikey': vt_api}
response = requests.get(url, params=parameters)
try:
... | [
"def",
"vt_hash_check",
"(",
"fhash",
",",
"vt_api",
")",
":",
"if",
"not",
"is_hash",
"(",
"fhash",
")",
":",
"return",
"None",
"url",
"=",
"'https://www.virustotal.com/vtapi/v2/file/report'",
"parameters",
"=",
"{",
"'resource'",
":",
"fhash",
",",
"'apikey'",... | Checks VirusTotal for occurrences of a file hash | [
"Checks",
"VirusTotal",
"for",
"occurrences",
"of",
"a",
"file",
"hash"
] | 55ac6c31f87963d5e97be0402a4343c84846d118 | https://github.com/yolothreat/utilitybelt/blob/55ac6c31f87963d5e97be0402a4343c84846d118/utilitybelt/utilitybelt.py#L312-L323 | train | 56,182 |
yolothreat/utilitybelt | utilitybelt/utilitybelt.py | ipinfo_ip_check | def ipinfo_ip_check(ip):
"""Checks ipinfo.io for basic WHOIS-type data on an IP address"""
if not is_IPv4Address(ip):
return None
response = requests.get('http://ipinfo.io/%s/json' % ip)
return response.json() | python | def ipinfo_ip_check(ip):
"""Checks ipinfo.io for basic WHOIS-type data on an IP address"""
if not is_IPv4Address(ip):
return None
response = requests.get('http://ipinfo.io/%s/json' % ip)
return response.json() | [
"def",
"ipinfo_ip_check",
"(",
"ip",
")",
":",
"if",
"not",
"is_IPv4Address",
"(",
"ip",
")",
":",
"return",
"None",
"response",
"=",
"requests",
".",
"get",
"(",
"'http://ipinfo.io/%s/json'",
"%",
"ip",
")",
"return",
"response",
".",
"json",
"(",
")"
] | Checks ipinfo.io for basic WHOIS-type data on an IP address | [
"Checks",
"ipinfo",
".",
"io",
"for",
"basic",
"WHOIS",
"-",
"type",
"data",
"on",
"an",
"IP",
"address"
] | 55ac6c31f87963d5e97be0402a4343c84846d118 | https://github.com/yolothreat/utilitybelt/blob/55ac6c31f87963d5e97be0402a4343c84846d118/utilitybelt/utilitybelt.py#L326-L332 | train | 56,183 |
yolothreat/utilitybelt | utilitybelt/utilitybelt.py | dshield_ip_check | def dshield_ip_check(ip):
"""Checks dshield for info on an IP address"""
if not is_IPv4Address(ip):
return None
headers = {'User-Agent': useragent}
url = 'https://isc.sans.edu/api/ip/'
response = requests.get('{0}{1}?json'.format(url, ip), headers=headers)
return response.json() | python | def dshield_ip_check(ip):
"""Checks dshield for info on an IP address"""
if not is_IPv4Address(ip):
return None
headers = {'User-Agent': useragent}
url = 'https://isc.sans.edu/api/ip/'
response = requests.get('{0}{1}?json'.format(url, ip), headers=headers)
return response.json() | [
"def",
"dshield_ip_check",
"(",
"ip",
")",
":",
"if",
"not",
"is_IPv4Address",
"(",
"ip",
")",
":",
"return",
"None",
"headers",
"=",
"{",
"'User-Agent'",
":",
"useragent",
"}",
"url",
"=",
"'https://isc.sans.edu/api/ip/'",
"response",
"=",
"requests",
".",
... | Checks dshield for info on an IP address | [
"Checks",
"dshield",
"for",
"info",
"on",
"an",
"IP",
"address"
] | 55ac6c31f87963d5e97be0402a4343c84846d118 | https://github.com/yolothreat/utilitybelt/blob/55ac6c31f87963d5e97be0402a4343c84846d118/utilitybelt/utilitybelt.py#L394-L402 | train | 56,184 |
e7dal/bubble3 | bubble3/commands/cmd_push.py | cli | def cli(ctx,
amount,
index,
stage):
"""Push data to Target Service Client"""
if not ctx.bubble:
ctx.say_yellow('There is no bubble present, will not push')
raise click.Abort()
TGT = None
transformed = True
STAGE = None
if stage in STAGES and stage in ... | python | def cli(ctx,
amount,
index,
stage):
"""Push data to Target Service Client"""
if not ctx.bubble:
ctx.say_yellow('There is no bubble present, will not push')
raise click.Abort()
TGT = None
transformed = True
STAGE = None
if stage in STAGES and stage in ... | [
"def",
"cli",
"(",
"ctx",
",",
"amount",
",",
"index",
",",
"stage",
")",
":",
"if",
"not",
"ctx",
".",
"bubble",
":",
"ctx",
".",
"say_yellow",
"(",
"'There is no bubble present, will not push'",
")",
"raise",
"click",
".",
"Abort",
"(",
")",
"TGT",
"="... | Push data to Target Service Client | [
"Push",
"data",
"to",
"Target",
"Service",
"Client"
] | 59c735281a95b44f6263a25f4d6ce24fca520082 | https://github.com/e7dal/bubble3/blob/59c735281a95b44f6263a25f4d6ce24fca520082/bubble3/commands/cmd_push.py#L48-L132 | train | 56,185 |
davgeo/clear | clear/util.py | RemoveEmptyDirectoryTree | def RemoveEmptyDirectoryTree(path, silent = False, recursion = 0):
"""
Delete tree of empty directories.
Parameters
----------
path : string
Path to root of directory tree.
silent : boolean [optional: default = False]
Turn off log output.
recursion : int [optional: default = 0]
... | python | def RemoveEmptyDirectoryTree(path, silent = False, recursion = 0):
"""
Delete tree of empty directories.
Parameters
----------
path : string
Path to root of directory tree.
silent : boolean [optional: default = False]
Turn off log output.
recursion : int [optional: default = 0]
... | [
"def",
"RemoveEmptyDirectoryTree",
"(",
"path",
",",
"silent",
"=",
"False",
",",
"recursion",
"=",
"0",
")",
":",
"if",
"not",
"silent",
"and",
"recursion",
"is",
"0",
":",
"goodlogging",
".",
"Log",
".",
"Info",
"(",
"\"UTIL\"",
",",
"\"Starting removal ... | Delete tree of empty directories.
Parameters
----------
path : string
Path to root of directory tree.
silent : boolean [optional: default = False]
Turn off log output.
recursion : int [optional: default = 0]
Indicates level of recursion. | [
"Delete",
"tree",
"of",
"empty",
"directories",
"."
] | 5ec85d27efd28afddfcd4c3f44df17f0115a77aa | https://github.com/davgeo/clear/blob/5ec85d27efd28afddfcd4c3f44df17f0115a77aa/clear/util.py#L17-L43 | train | 56,186 |
davgeo/clear | clear/util.py | ValidUserResponse | def ValidUserResponse(response, validList):
"""
Check if user response is in a list of valid entires.
If an invalid response is given re-prompt user to enter
one of the valid options. Do not proceed until a valid entry
is given.
Parameters
----------
response : string
Response string to check.
... | python | def ValidUserResponse(response, validList):
"""
Check if user response is in a list of valid entires.
If an invalid response is given re-prompt user to enter
one of the valid options. Do not proceed until a valid entry
is given.
Parameters
----------
response : string
Response string to check.
... | [
"def",
"ValidUserResponse",
"(",
"response",
",",
"validList",
")",
":",
"if",
"response",
"in",
"validList",
":",
"return",
"response",
"else",
":",
"prompt",
"=",
"\"Unknown response given - please reenter one of [{0}]: \"",
".",
"format",
"(",
"'/'",
".",
"join",... | Check if user response is in a list of valid entires.
If an invalid response is given re-prompt user to enter
one of the valid options. Do not proceed until a valid entry
is given.
Parameters
----------
response : string
Response string to check.
validList : list
A list of valid response... | [
"Check",
"if",
"user",
"response",
"is",
"in",
"a",
"list",
"of",
"valid",
"entires",
".",
"If",
"an",
"invalid",
"response",
"is",
"given",
"re",
"-",
"prompt",
"user",
"to",
"enter",
"one",
"of",
"the",
"valid",
"options",
".",
"Do",
"not",
"proceed"... | 5ec85d27efd28afddfcd4c3f44df17f0115a77aa | https://github.com/davgeo/clear/blob/5ec85d27efd28afddfcd4c3f44df17f0115a77aa/clear/util.py#L132-L157 | train | 56,187 |
davgeo/clear | clear/util.py | UserAcceptance | def UserAcceptance(
matchList,
recursiveLookup = True,
promptComment = None,
promptOnly = False,
xStrOverride = "to skip this selection"
):
"""
Prompt user to select a entry from a given match list or to enter a new
string to look up. If the match list is empty user must enter a new string
or exit.
... | python | def UserAcceptance(
matchList,
recursiveLookup = True,
promptComment = None,
promptOnly = False,
xStrOverride = "to skip this selection"
):
"""
Prompt user to select a entry from a given match list or to enter a new
string to look up. If the match list is empty user must enter a new string
or exit.
... | [
"def",
"UserAcceptance",
"(",
"matchList",
",",
"recursiveLookup",
"=",
"True",
",",
"promptComment",
"=",
"None",
",",
"promptOnly",
"=",
"False",
",",
"xStrOverride",
"=",
"\"to skip this selection\"",
")",
":",
"matchString",
"=",
"', '",
".",
"join",
"(",
... | Prompt user to select a entry from a given match list or to enter a new
string to look up. If the match list is empty user must enter a new string
or exit.
Parameters
----------
matchList : list
A list of entries which the user can select a valid match from.
recursiveLookup : boolean [optional: ... | [
"Prompt",
"user",
"to",
"select",
"a",
"entry",
"from",
"a",
"given",
"match",
"list",
"or",
"to",
"enter",
"a",
"new",
"string",
"to",
"look",
"up",
".",
"If",
"the",
"match",
"list",
"is",
"empty",
"user",
"must",
"enter",
"a",
"new",
"string",
"or... | 5ec85d27efd28afddfcd4c3f44df17f0115a77aa | https://github.com/davgeo/clear/blob/5ec85d27efd28afddfcd4c3f44df17f0115a77aa/clear/util.py#L162-L240 | train | 56,188 |
davgeo/clear | clear/util.py | GetBestMatch | def GetBestMatch(target, matchList):
"""
Finds the elements of matchList which best match the target string.
Note that this searches substrings so "abc" will have a 100% match in
both "this is the abc", "abcde" and "abc".
The return from this function is a list of potention matches which shared
the same h... | python | def GetBestMatch(target, matchList):
"""
Finds the elements of matchList which best match the target string.
Note that this searches substrings so "abc" will have a 100% match in
both "this is the abc", "abcde" and "abc".
The return from this function is a list of potention matches which shared
the same h... | [
"def",
"GetBestMatch",
"(",
"target",
",",
"matchList",
")",
":",
"bestMatchList",
"=",
"[",
"]",
"if",
"len",
"(",
"matchList",
")",
">",
"0",
":",
"ratioMatch",
"=",
"[",
"]",
"for",
"item",
"in",
"matchList",
":",
"ratioMatch",
".",
"append",
"(",
... | Finds the elements of matchList which best match the target string.
Note that this searches substrings so "abc" will have a 100% match in
both "this is the abc", "abcde" and "abc".
The return from this function is a list of potention matches which shared
the same highest match score. If any exact match is fou... | [
"Finds",
"the",
"elements",
"of",
"matchList",
"which",
"best",
"match",
"the",
"target",
"string",
"."
] | 5ec85d27efd28afddfcd4c3f44df17f0115a77aa | https://github.com/davgeo/clear/blob/5ec85d27efd28afddfcd4c3f44df17f0115a77aa/clear/util.py#L245-L288 | train | 56,189 |
davgeo/clear | clear/util.py | GetBestStringMatchValue | def GetBestStringMatchValue(string1, string2):
"""
Return the value of the highest matching substrings between two strings.
Parameters
----------
string1 : string
First string.
string2 : string
Second string.
Returns
----------
int
Integer value representing the best match f... | python | def GetBestStringMatchValue(string1, string2):
"""
Return the value of the highest matching substrings between two strings.
Parameters
----------
string1 : string
First string.
string2 : string
Second string.
Returns
----------
int
Integer value representing the best match f... | [
"def",
"GetBestStringMatchValue",
"(",
"string1",
",",
"string2",
")",
":",
"# Ignore case",
"string1",
"=",
"string1",
".",
"lower",
"(",
")",
"string2",
"=",
"string2",
".",
"lower",
"(",
")",
"# Ignore non-alphanumeric characters",
"string1",
"=",
"''",
".",
... | Return the value of the highest matching substrings between two strings.
Parameters
----------
string1 : string
First string.
string2 : string
Second string.
Returns
----------
int
Integer value representing the best match found
between string1 and string2. | [
"Return",
"the",
"value",
"of",
"the",
"highest",
"matching",
"substrings",
"between",
"two",
"strings",
"."
] | 5ec85d27efd28afddfcd4c3f44df17f0115a77aa | https://github.com/davgeo/clear/blob/5ec85d27efd28afddfcd4c3f44df17f0115a77aa/clear/util.py#L293-L342 | train | 56,190 |
davgeo/clear | clear/util.py | WebLookup | def WebLookup(url, urlQuery=None, utf8=True):
"""
Look up webpage at given url with optional query string
Parameters
----------
url : string
Web url.
urlQuery : dictionary [optional: default = None]
Parameter to be passed to GET method of requests module
utf8 : boolean [optional: defa... | python | def WebLookup(url, urlQuery=None, utf8=True):
"""
Look up webpage at given url with optional query string
Parameters
----------
url : string
Web url.
urlQuery : dictionary [optional: default = None]
Parameter to be passed to GET method of requests module
utf8 : boolean [optional: defa... | [
"def",
"WebLookup",
"(",
"url",
",",
"urlQuery",
"=",
"None",
",",
"utf8",
"=",
"True",
")",
":",
"goodlogging",
".",
"Log",
".",
"Info",
"(",
"\"UTIL\"",
",",
"\"Looking up info from URL:{0} with QUERY:{1})\"",
".",
"format",
"(",
"url",
",",
"urlQuery",
")... | Look up webpage at given url with optional query string
Parameters
----------
url : string
Web url.
urlQuery : dictionary [optional: default = None]
Parameter to be passed to GET method of requests module
utf8 : boolean [optional: default = True]
Set response encoding
Returns
-... | [
"Look",
"up",
"webpage",
"at",
"given",
"url",
"with",
"optional",
"query",
"string"
] | 5ec85d27efd28afddfcd4c3f44df17f0115a77aa | https://github.com/davgeo/clear/blob/5ec85d27efd28afddfcd4c3f44df17f0115a77aa/clear/util.py#L347-L376 | train | 56,191 |
davgeo/clear | clear/util.py | ArchiveProcessedFile | def ArchiveProcessedFile(filePath, archiveDir):
"""
Move file from given file path to archive directory. Note the archive
directory is relative to the file path directory.
Parameters
----------
filePath : string
File path
archiveDir : string
Name of archive directory
"""
targetDir = ... | python | def ArchiveProcessedFile(filePath, archiveDir):
"""
Move file from given file path to archive directory. Note the archive
directory is relative to the file path directory.
Parameters
----------
filePath : string
File path
archiveDir : string
Name of archive directory
"""
targetDir = ... | [
"def",
"ArchiveProcessedFile",
"(",
"filePath",
",",
"archiveDir",
")",
":",
"targetDir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"filePath",
")",
",",
"archiveDir",
")",
"goodlogging",
".",
"Log",
".",
"Info",
... | Move file from given file path to archive directory. Note the archive
directory is relative to the file path directory.
Parameters
----------
filePath : string
File path
archiveDir : string
Name of archive directory | [
"Move",
"file",
"from",
"given",
"file",
"path",
"to",
"archive",
"directory",
".",
"Note",
"the",
"archive",
"directory",
"is",
"relative",
"to",
"the",
"file",
"path",
"directory",
"."
] | 5ec85d27efd28afddfcd4c3f44df17f0115a77aa | https://github.com/davgeo/clear/blob/5ec85d27efd28afddfcd4c3f44df17f0115a77aa/clear/util.py#L382-L406 | train | 56,192 |
shblythe/python2-pilite | pilite.py | PiLite.send_wait | def send_wait(self,text):
"""Send a string to the PiLite, sleep until the message has been
displayed (based on an estimate of the speed of the display.
Due to the font not being monotype, this will wait too long in most
cases"""
self.send(text)
time.sleep(len(text)*PiLite.COLS_PER_CHAR*self.speed/1000.0) | python | def send_wait(self,text):
"""Send a string to the PiLite, sleep until the message has been
displayed (based on an estimate of the speed of the display.
Due to the font not being monotype, this will wait too long in most
cases"""
self.send(text)
time.sleep(len(text)*PiLite.COLS_PER_CHAR*self.speed/1000.0) | [
"def",
"send_wait",
"(",
"self",
",",
"text",
")",
":",
"self",
".",
"send",
"(",
"text",
")",
"time",
".",
"sleep",
"(",
"len",
"(",
"text",
")",
"*",
"PiLite",
".",
"COLS_PER_CHAR",
"*",
"self",
".",
"speed",
"/",
"1000.0",
")"
] | Send a string to the PiLite, sleep until the message has been
displayed (based on an estimate of the speed of the display.
Due to the font not being monotype, this will wait too long in most
cases | [
"Send",
"a",
"string",
"to",
"the",
"PiLite",
"sleep",
"until",
"the",
"message",
"has",
"been",
"displayed",
"(",
"based",
"on",
"an",
"estimate",
"of",
"the",
"speed",
"of",
"the",
"display",
".",
"Due",
"to",
"the",
"font",
"not",
"being",
"monotype",... | 6ce5b8920c472077e81a9ebaff7dec1e15d2516c | https://github.com/shblythe/python2-pilite/blob/6ce5b8920c472077e81a9ebaff7dec1e15d2516c/pilite.py#L48-L54 | train | 56,193 |
shblythe/python2-pilite | pilite.py | PiLite.set_speed | def set_speed(self,speed):
"""Set the display speed. The parameters is the number of milliseconds
between each column scrolling off the display"""
self.speed=speed
self.send_cmd("SPEED"+str(speed)) | python | def set_speed(self,speed):
"""Set the display speed. The parameters is the number of milliseconds
between each column scrolling off the display"""
self.speed=speed
self.send_cmd("SPEED"+str(speed)) | [
"def",
"set_speed",
"(",
"self",
",",
"speed",
")",
":",
"self",
".",
"speed",
"=",
"speed",
"self",
".",
"send_cmd",
"(",
"\"SPEED\"",
"+",
"str",
"(",
"speed",
")",
")"
] | Set the display speed. The parameters is the number of milliseconds
between each column scrolling off the display | [
"Set",
"the",
"display",
"speed",
".",
"The",
"parameters",
"is",
"the",
"number",
"of",
"milliseconds",
"between",
"each",
"column",
"scrolling",
"off",
"the",
"display"
] | 6ce5b8920c472077e81a9ebaff7dec1e15d2516c | https://github.com/shblythe/python2-pilite/blob/6ce5b8920c472077e81a9ebaff7dec1e15d2516c/pilite.py#L69-L73 | train | 56,194 |
shblythe/python2-pilite | pilite.py | PiLite.set_fb_random | def set_fb_random(self):
"""Set the "frame buffer" to a random pattern"""
pattern=''.join([random.choice(['0','1']) for i in xrange(14*9)])
self.set_fb(pattern) | python | def set_fb_random(self):
"""Set the "frame buffer" to a random pattern"""
pattern=''.join([random.choice(['0','1']) for i in xrange(14*9)])
self.set_fb(pattern) | [
"def",
"set_fb_random",
"(",
"self",
")",
":",
"pattern",
"=",
"''",
".",
"join",
"(",
"[",
"random",
".",
"choice",
"(",
"[",
"'0'",
",",
"'1'",
"]",
")",
"for",
"i",
"in",
"xrange",
"(",
"14",
"*",
"9",
")",
"]",
")",
"self",
".",
"set_fb",
... | Set the "frame buffer" to a random pattern | [
"Set",
"the",
"frame",
"buffer",
"to",
"a",
"random",
"pattern"
] | 6ce5b8920c472077e81a9ebaff7dec1e15d2516c | https://github.com/shblythe/python2-pilite/blob/6ce5b8920c472077e81a9ebaff7dec1e15d2516c/pilite.py#L95-L98 | train | 56,195 |
shblythe/python2-pilite | pilite.py | PiLite.set_pixel | def set_pixel(self,x,y,state):
"""Set pixel at "x,y" to "state" where state can be one of "ON", "OFF"
or "TOGGLE"
"""
self.send_cmd("P"+str(x+1)+","+str(y+1)+","+state) | python | def set_pixel(self,x,y,state):
"""Set pixel at "x,y" to "state" where state can be one of "ON", "OFF"
or "TOGGLE"
"""
self.send_cmd("P"+str(x+1)+","+str(y+1)+","+state) | [
"def",
"set_pixel",
"(",
"self",
",",
"x",
",",
"y",
",",
"state",
")",
":",
"self",
".",
"send_cmd",
"(",
"\"P\"",
"+",
"str",
"(",
"x",
"+",
"1",
")",
"+",
"\",\"",
"+",
"str",
"(",
"y",
"+",
"1",
")",
"+",
"\",\"",
"+",
"state",
")"
] | Set pixel at "x,y" to "state" where state can be one of "ON", "OFF"
or "TOGGLE" | [
"Set",
"pixel",
"at",
"x",
"y",
"to",
"state",
"where",
"state",
"can",
"be",
"one",
"of",
"ON",
"OFF",
"or",
"TOGGLE"
] | 6ce5b8920c472077e81a9ebaff7dec1e15d2516c | https://github.com/shblythe/python2-pilite/blob/6ce5b8920c472077e81a9ebaff7dec1e15d2516c/pilite.py#L115-L119 | train | 56,196 |
shblythe/python2-pilite | pilite.py | PiLite.display_char | def display_char(self,x,y,char):
"""Display character "char" with its top left at "x,y"
"""
self.send_cmd("T"+str(x+1)+","+str(y+1)+","+char) | python | def display_char(self,x,y,char):
"""Display character "char" with its top left at "x,y"
"""
self.send_cmd("T"+str(x+1)+","+str(y+1)+","+char) | [
"def",
"display_char",
"(",
"self",
",",
"x",
",",
"y",
",",
"char",
")",
":",
"self",
".",
"send_cmd",
"(",
"\"T\"",
"+",
"str",
"(",
"x",
"+",
"1",
")",
"+",
"\",\"",
"+",
"str",
"(",
"y",
"+",
"1",
")",
"+",
"\",\"",
"+",
"char",
")"
] | Display character "char" with its top left at "x,y" | [
"Display",
"character",
"char",
"with",
"its",
"top",
"left",
"at",
"x",
"y"
] | 6ce5b8920c472077e81a9ebaff7dec1e15d2516c | https://github.com/shblythe/python2-pilite/blob/6ce5b8920c472077e81a9ebaff7dec1e15d2516c/pilite.py#L152-L155 | train | 56,197 |
hollenstein/maspy | maspy_resources/peptide_mapping.py | the_magic_mapping_function | def the_magic_mapping_function(peptides, fastaPath, importAttributes=None,
ignoreUnmapped=True):
"""Returns a dictionary mapping peptides to protein group leading proteins.
:param peptides: a set of peptide sequences
:param fastaPath: FASTA file path
:param importAttributes: dict, can be used t... | python | def the_magic_mapping_function(peptides, fastaPath, importAttributes=None,
ignoreUnmapped=True):
"""Returns a dictionary mapping peptides to protein group leading proteins.
:param peptides: a set of peptide sequences
:param fastaPath: FASTA file path
:param importAttributes: dict, can be used t... | [
"def",
"the_magic_mapping_function",
"(",
"peptides",
",",
"fastaPath",
",",
"importAttributes",
"=",
"None",
",",
"ignoreUnmapped",
"=",
"True",
")",
":",
"missedCleavage",
"=",
"max",
"(",
"[",
"p",
".",
"count",
"(",
"'K'",
")",
"+",
"p",
".",
"count",
... | Returns a dictionary mapping peptides to protein group leading proteins.
:param peptides: a set of peptide sequences
:param fastaPath: FASTA file path
:param importAttributes: dict, can be used to override default parameters
passed to the function maspy.proteindb.importProteinDatabase().
De... | [
"Returns",
"a",
"dictionary",
"mapping",
"peptides",
"to",
"protein",
"group",
"leading",
"proteins",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy_resources/peptide_mapping.py#L38-L98 | train | 56,198 |
bitesofcode/projex | projex/text.py | truncate | def truncate(text, length=50, ellipsis='...'):
"""
Returns a truncated version of the inputted text.
:param text | <str>
length | <int>
ellipsis | <str>
:return <str>
"""
text = nativestring(text)
return text[:length] + (text[length:] and ellipsis) | python | def truncate(text, length=50, ellipsis='...'):
"""
Returns a truncated version of the inputted text.
:param text | <str>
length | <int>
ellipsis | <str>
:return <str>
"""
text = nativestring(text)
return text[:length] + (text[length:] and ellipsis) | [
"def",
"truncate",
"(",
"text",
",",
"length",
"=",
"50",
",",
"ellipsis",
"=",
"'...'",
")",
":",
"text",
"=",
"nativestring",
"(",
"text",
")",
"return",
"text",
"[",
":",
"length",
"]",
"+",
"(",
"text",
"[",
"length",
":",
"]",
"and",
"ellipsis... | Returns a truncated version of the inputted text.
:param text | <str>
length | <int>
ellipsis | <str>
:return <str> | [
"Returns",
"a",
"truncated",
"version",
"of",
"the",
"inputted",
"text",
"."
] | d31743ec456a41428709968ab11a2cf6c6c76247 | https://github.com/bitesofcode/projex/blob/d31743ec456a41428709968ab11a2cf6c6c76247/projex/text.py#L707-L718 | train | 56,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.