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
blockstack-packages/blockstack-gpg
blockstack_gpg/gpg.py
gpg_sign
def gpg_sign( path_to_sign, sender_key_info, config_dir=None, passphrase=None ): """ Sign a file on disk. @sender_key_info should be a dict with { 'key_id': ... 'key_data': ... 'app_name': ... } Return {'status': True, 'sig': ...} on success Return {'error': ...} on e...
python
def gpg_sign( path_to_sign, sender_key_info, config_dir=None, passphrase=None ): """ Sign a file on disk. @sender_key_info should be a dict with { 'key_id': ... 'key_data': ... 'app_name': ... } Return {'status': True, 'sig': ...} on success Return {'error': ...} on e...
[ "def", "gpg_sign", "(", "path_to_sign", ",", "sender_key_info", ",", "config_dir", "=", "None", ",", "passphrase", "=", "None", ")", ":", "if", "config_dir", "is", "None", ":", "config_dir", "=", "get_config_dir", "(", ")", "# ingest keys ", "tmpdir", "=", "...
Sign a file on disk. @sender_key_info should be a dict with { 'key_id': ... 'key_data': ... 'app_name': ... } Return {'status': True, 'sig': ...} on success Return {'error': ...} on error
[ "Sign", "a", "file", "on", "disk", "." ]
e4d51e4e51678d9b946596ca9dec53e2d78c8710
https://github.com/blockstack-packages/blockstack-gpg/blob/e4d51e4e51678d9b946596ca9dec53e2d78c8710/blockstack_gpg/gpg.py#L905-L950
train
58,500
blockstack-packages/blockstack-gpg
blockstack_gpg/gpg.py
gpg_verify
def gpg_verify( path_to_verify, sigdata, sender_key_info, config_dir=None ): """ Verify a file on disk was signed by the given sender. @sender_key_info should be a dict with { 'key_id': ... 'key_data': ... 'app_name'; ... } Return {'status': True} on success Return {'...
python
def gpg_verify( path_to_verify, sigdata, sender_key_info, config_dir=None ): """ Verify a file on disk was signed by the given sender. @sender_key_info should be a dict with { 'key_id': ... 'key_data': ... 'app_name'; ... } Return {'status': True} on success Return {'...
[ "def", "gpg_verify", "(", "path_to_verify", ",", "sigdata", ",", "sender_key_info", ",", "config_dir", "=", "None", ")", ":", "if", "config_dir", "is", "None", ":", "config_dir", "=", "get_config_dir", "(", ")", "# ingest keys ", "tmpdir", "=", "make_gpg_tmphome...
Verify a file on disk was signed by the given sender. @sender_key_info should be a dict with { 'key_id': ... 'key_data': ... 'app_name'; ... } Return {'status': True} on success Return {'error': ...} on error
[ "Verify", "a", "file", "on", "disk", "was", "signed", "by", "the", "given", "sender", "." ]
e4d51e4e51678d9b946596ca9dec53e2d78c8710
https://github.com/blockstack-packages/blockstack-gpg/blob/e4d51e4e51678d9b946596ca9dec53e2d78c8710/blockstack_gpg/gpg.py#L953-L1001
train
58,501
blockstack-packages/blockstack-gpg
blockstack_gpg/gpg.py
gpg_encrypt
def gpg_encrypt( fd_in, path_out, sender_key_info, recipient_key_infos, passphrase=None, config_dir=None ): """ Encrypt a stream of data for a set of keys. @sender_key_info should be a dict with { 'key_id': ... 'key_data': ... 'app_name'; ... } Return {'status': True} on ...
python
def gpg_encrypt( fd_in, path_out, sender_key_info, recipient_key_infos, passphrase=None, config_dir=None ): """ Encrypt a stream of data for a set of keys. @sender_key_info should be a dict with { 'key_id': ... 'key_data': ... 'app_name'; ... } Return {'status': True} on ...
[ "def", "gpg_encrypt", "(", "fd_in", ",", "path_out", ",", "sender_key_info", ",", "recipient_key_infos", ",", "passphrase", "=", "None", ",", "config_dir", "=", "None", ")", ":", "if", "config_dir", "is", "None", ":", "config_dir", "=", "get_config_dir", "(", ...
Encrypt a stream of data for a set of keys. @sender_key_info should be a dict with { 'key_id': ... 'key_data': ... 'app_name'; ... } Return {'status': True} on success Return {'error': ...} on error
[ "Encrypt", "a", "stream", "of", "data", "for", "a", "set", "of", "keys", "." ]
e4d51e4e51678d9b946596ca9dec53e2d78c8710
https://github.com/blockstack-packages/blockstack-gpg/blob/e4d51e4e51678d9b946596ca9dec53e2d78c8710/blockstack_gpg/gpg.py#L1004-L1054
train
58,502
blockstack-packages/blockstack-gpg
blockstack_gpg/gpg.py
gpg_decrypt
def gpg_decrypt( fd_in, path_out, sender_key_info, my_key_info, passphrase=None, config_dir=None ): """ Decrypt a stream of data using key info for a private key we own. @my_key_info and @sender_key_info should be data returned by gpg_app_get_key { 'key_id': ... 'key_data': ... ...
python
def gpg_decrypt( fd_in, path_out, sender_key_info, my_key_info, passphrase=None, config_dir=None ): """ Decrypt a stream of data using key info for a private key we own. @my_key_info and @sender_key_info should be data returned by gpg_app_get_key { 'key_id': ... 'key_data': ... ...
[ "def", "gpg_decrypt", "(", "fd_in", ",", "path_out", ",", "sender_key_info", ",", "my_key_info", ",", "passphrase", "=", "None", ",", "config_dir", "=", "None", ")", ":", "if", "config_dir", "is", "None", ":", "config_dir", "=", "get_config_dir", "(", ")", ...
Decrypt a stream of data using key info for a private key we own. @my_key_info and @sender_key_info should be data returned by gpg_app_get_key { 'key_id': ... 'key_data': ... 'app_name': ... } Return {'status': True, 'sig': ...} on success Return {'status': True} on succ...
[ "Decrypt", "a", "stream", "of", "data", "using", "key", "info", "for", "a", "private", "key", "we", "own", "." ]
e4d51e4e51678d9b946596ca9dec53e2d78c8710
https://github.com/blockstack-packages/blockstack-gpg/blob/e4d51e4e51678d9b946596ca9dec53e2d78c8710/blockstack_gpg/gpg.py#L1057-L1103
train
58,503
contains-io/rcli
rcli/usage.py
get_primary_command_usage
def get_primary_command_usage(message=''): # type: (str) -> str """Return the usage string for the primary command.""" if not settings.merge_primary_command and None in settings.subcommands: return format_usage(settings.subcommands[None].__doc__) if not message: message = '\n{}\n'.format...
python
def get_primary_command_usage(message=''): # type: (str) -> str """Return the usage string for the primary command.""" if not settings.merge_primary_command and None in settings.subcommands: return format_usage(settings.subcommands[None].__doc__) if not message: message = '\n{}\n'.format...
[ "def", "get_primary_command_usage", "(", "message", "=", "''", ")", ":", "# type: (str) -> str", "if", "not", "settings", ".", "merge_primary_command", "and", "None", "in", "settings", ".", "subcommands", ":", "return", "format_usage", "(", "settings", ".", "subco...
Return the usage string for the primary command.
[ "Return", "the", "usage", "string", "for", "the", "primary", "command", "." ]
cdd6191a0e0a19bc767f84921650835d099349cf
https://github.com/contains-io/rcli/blob/cdd6191a0e0a19bc767f84921650835d099349cf/rcli/usage.py#L54-L64
train
58,504
contains-io/rcli
rcli/usage.py
get_help_usage
def get_help_usage(command): # type: (str) -> None """Print out a help message and exit the program. Args: command: If a command value is supplied then print the help message for the command module if available. If the command is '-a' or '--all', then print the standard help...
python
def get_help_usage(command): # type: (str) -> None """Print out a help message and exit the program. Args: command: If a command value is supplied then print the help message for the command module if available. If the command is '-a' or '--all', then print the standard help...
[ "def", "get_help_usage", "(", "command", ")", ":", "# type: (str) -> None", "if", "not", "command", ":", "doc", "=", "get_primary_command_usage", "(", ")", "elif", "command", "in", "(", "'-a'", ",", "'--all'", ")", ":", "subcommands", "=", "[", "k", "for", ...
Print out a help message and exit the program. Args: command: If a command value is supplied then print the help message for the command module if available. If the command is '-a' or '--all', then print the standard help message but with a full list of available command...
[ "Print", "out", "a", "help", "message", "and", "exit", "the", "program", "." ]
cdd6191a0e0a19bc767f84921650835d099349cf
https://github.com/contains-io/rcli/blob/cdd6191a0e0a19bc767f84921650835d099349cf/rcli/usage.py#L67-L94
train
58,505
contains-io/rcli
rcli/usage.py
format_usage
def format_usage(doc, width=None): # type: (str, Optional[int]) -> str """Format the docstring for display to the user. Args: doc: The docstring to reformat for display. Returns: The docstring formatted to parse and display to the user. This includes dedenting, rewrapping, and ...
python
def format_usage(doc, width=None): # type: (str, Optional[int]) -> str """Format the docstring for display to the user. Args: doc: The docstring to reformat for display. Returns: The docstring formatted to parse and display to the user. This includes dedenting, rewrapping, and ...
[ "def", "format_usage", "(", "doc", ",", "width", "=", "None", ")", ":", "# type: (str, Optional[int]) -> str", "sections", "=", "doc", ".", "replace", "(", "'\\r'", ",", "''", ")", ".", "split", "(", "'\\n\\n'", ")", "width", "=", "width", "or", "get_termi...
Format the docstring for display to the user. Args: doc: The docstring to reformat for display. Returns: The docstring formatted to parse and display to the user. This includes dedenting, rewrapping, and translating the docstring if necessary.
[ "Format", "the", "docstring", "for", "display", "to", "the", "user", "." ]
cdd6191a0e0a19bc767f84921650835d099349cf
https://github.com/contains-io/rcli/blob/cdd6191a0e0a19bc767f84921650835d099349cf/rcli/usage.py#L97-L110
train
58,506
contains-io/rcli
rcli/usage.py
parse_commands
def parse_commands(docstring): # type: (str) -> Generator[Tuple[List[str], List[str]], None, None] """Parse a docopt-style string for commands and subcommands. Args: docstring: A docopt-style string to parse. If the string is not a valid docopt-style string, it will not yield and values...
python
def parse_commands(docstring): # type: (str) -> Generator[Tuple[List[str], List[str]], None, None] """Parse a docopt-style string for commands and subcommands. Args: docstring: A docopt-style string to parse. If the string is not a valid docopt-style string, it will not yield and values...
[ "def", "parse_commands", "(", "docstring", ")", ":", "# type: (str) -> Generator[Tuple[List[str], List[str]], None, None]", "try", ":", "docopt", ".", "docopt", "(", "docstring", ",", "argv", "=", "(", ")", ")", "except", "(", "TypeError", ",", "docopt", ".", "Doc...
Parse a docopt-style string for commands and subcommands. Args: docstring: A docopt-style string to parse. If the string is not a valid docopt-style string, it will not yield and values. Yields: All tuples of commands and subcommands found in the docopt docstring.
[ "Parse", "a", "docopt", "-", "style", "string", "for", "commands", "and", "subcommands", "." ]
cdd6191a0e0a19bc767f84921650835d099349cf
https://github.com/contains-io/rcli/blob/cdd6191a0e0a19bc767f84921650835d099349cf/rcli/usage.py#L113-L139
train
58,507
contains-io/rcli
rcli/usage.py
_merge_doc
def _merge_doc(original, to_merge): # type: (str, str) -> str """Merge two usage strings together. Args: original: The source of headers and initial section lines. to_merge: The source for the additional section lines to append. Returns: A new usage string that contains informa...
python
def _merge_doc(original, to_merge): # type: (str, str) -> str """Merge two usage strings together. Args: original: The source of headers and initial section lines. to_merge: The source for the additional section lines to append. Returns: A new usage string that contains informa...
[ "def", "_merge_doc", "(", "original", ",", "to_merge", ")", ":", "# type: (str, str) -> str", "if", "not", "original", ":", "return", "to_merge", "or", "''", "if", "not", "to_merge", ":", "return", "original", "or", "''", "sections", "=", "[", "]", "for", ...
Merge two usage strings together. Args: original: The source of headers and initial section lines. to_merge: The source for the additional section lines to append. Returns: A new usage string that contains information from both usage strings.
[ "Merge", "two", "usage", "strings", "together", "." ]
cdd6191a0e0a19bc767f84921650835d099349cf
https://github.com/contains-io/rcli/blob/cdd6191a0e0a19bc767f84921650835d099349cf/rcli/usage.py#L142-L163
train
58,508
contains-io/rcli
rcli/usage.py
_merge_section
def _merge_section(original, to_merge): # type: (str, str) -> str """Merge two sections together. Args: original: The source of header and initial section lines. to_merge: The source for the additional section lines to append. Returns: A new section string that uses the header ...
python
def _merge_section(original, to_merge): # type: (str, str) -> str """Merge two sections together. Args: original: The source of header and initial section lines. to_merge: The source for the additional section lines to append. Returns: A new section string that uses the header ...
[ "def", "_merge_section", "(", "original", ",", "to_merge", ")", ":", "# type: (str, str) -> str", "if", "not", "original", ":", "return", "to_merge", "or", "''", "if", "not", "to_merge", ":", "return", "original", "or", "''", "try", ":", "index", "=", "origi...
Merge two sections together. Args: original: The source of header and initial section lines. to_merge: The source for the additional section lines to append. Returns: A new section string that uses the header of the original argument and the section lines from both.
[ "Merge", "two", "sections", "together", "." ]
cdd6191a0e0a19bc767f84921650835d099349cf
https://github.com/contains-io/rcli/blob/cdd6191a0e0a19bc767f84921650835d099349cf/rcli/usage.py#L166-L190
train
58,509
contains-io/rcli
rcli/usage.py
_get_section
def _get_section(name, source): # type: (str, str) -> Optional[str] """Extract the named section from the source. Args: name: The name of the section to extract (e.g. "Usage"). source: The usage string to parse. Returns: A string containing only the requested section. If the se...
python
def _get_section(name, source): # type: (str, str) -> Optional[str] """Extract the named section from the source. Args: name: The name of the section to extract (e.g. "Usage"). source: The usage string to parse. Returns: A string containing only the requested section. If the se...
[ "def", "_get_section", "(", "name", ",", "source", ")", ":", "# type: (str, str) -> Optional[str]", "pattern", "=", "re", ".", "compile", "(", "'^([^\\n]*{name}[^\\n]*\\n?(?:[ \\t].*?(?:\\n|$))*)'", ".", "format", "(", "name", "=", "name", ")", ",", "re", ".", "IG...
Extract the named section from the source. Args: name: The name of the section to extract (e.g. "Usage"). source: The usage string to parse. Returns: A string containing only the requested section. If the section appears multiple times, each instance will be merged into a singl...
[ "Extract", "the", "named", "section", "from", "the", "source", "." ]
cdd6191a0e0a19bc767f84921650835d099349cf
https://github.com/contains-io/rcli/blob/cdd6191a0e0a19bc767f84921650835d099349cf/rcli/usage.py#L193-L211
train
58,510
contains-io/rcli
rcli/usage.py
_wrap_section
def _wrap_section(source, width): # type: (str, int) -> str """Wrap the given section string to the current terminal size. Intelligently wraps the section string to the given width. When wrapping section lines, it auto-adjusts the spacing between terms and definitions. It also adjusts commands the ...
python
def _wrap_section(source, width): # type: (str, int) -> str """Wrap the given section string to the current terminal size. Intelligently wraps the section string to the given width. When wrapping section lines, it auto-adjusts the spacing between terms and definitions. It also adjusts commands the ...
[ "def", "_wrap_section", "(", "source", ",", "width", ")", ":", "# type: (str, int) -> str", "if", "_get_section", "(", "'usage'", ",", "source", ")", ":", "return", "_wrap_usage_section", "(", "source", ",", "width", ")", "if", "_is_definition_section", "(", "so...
Wrap the given section string to the current terminal size. Intelligently wraps the section string to the given width. When wrapping section lines, it auto-adjusts the spacing between terms and definitions. It also adjusts commands the fit the correct length for the arguments. Args: source: Th...
[ "Wrap", "the", "given", "section", "string", "to", "the", "current", "terminal", "size", "." ]
cdd6191a0e0a19bc767f84921650835d099349cf
https://github.com/contains-io/rcli/blob/cdd6191a0e0a19bc767f84921650835d099349cf/rcli/usage.py#L214-L235
train
58,511
contains-io/rcli
rcli/usage.py
_is_definition_section
def _is_definition_section(source): """Determine if the source is a definition section. Args: source: The usage string source that may be a section. Returns: True if the source describes a definition section; otherwise, False. """ try: definitions = textwrap.dedent(source)....
python
def _is_definition_section(source): """Determine if the source is a definition section. Args: source: The usage string source that may be a section. Returns: True if the source describes a definition section; otherwise, False. """ try: definitions = textwrap.dedent(source)....
[ "def", "_is_definition_section", "(", "source", ")", ":", "try", ":", "definitions", "=", "textwrap", ".", "dedent", "(", "source", ")", ".", "split", "(", "'\\n'", ",", "1", ")", "[", "1", "]", ".", "splitlines", "(", ")", "return", "all", "(", "re"...
Determine if the source is a definition section. Args: source: The usage string source that may be a section. Returns: True if the source describes a definition section; otherwise, False.
[ "Determine", "if", "the", "source", "is", "a", "definition", "section", "." ]
cdd6191a0e0a19bc767f84921650835d099349cf
https://github.com/contains-io/rcli/blob/cdd6191a0e0a19bc767f84921650835d099349cf/rcli/usage.py#L238-L252
train
58,512
contains-io/rcli
rcli/usage.py
_wrap_usage_section
def _wrap_usage_section(source, width): # type: (str, int) -> str """Wrap the given usage section string to the current terminal size. Note: Commands arguments are wrapped to the column that the arguments began on the first line of the command. Args: source: The section string ...
python
def _wrap_usage_section(source, width): # type: (str, int) -> str """Wrap the given usage section string to the current terminal size. Note: Commands arguments are wrapped to the column that the arguments began on the first line of the command. Args: source: The section string ...
[ "def", "_wrap_usage_section", "(", "source", ",", "width", ")", ":", "# type: (str, int) -> str", "if", "not", "any", "(", "len", "(", "line", ")", ">", "width", "for", "line", "in", "source", ".", "splitlines", "(", ")", ")", ":", "return", "source", "s...
Wrap the given usage section string to the current terminal size. Note: Commands arguments are wrapped to the column that the arguments began on the first line of the command. Args: source: The section string to wrap. Returns: The wrapped section string.
[ "Wrap", "the", "given", "usage", "section", "string", "to", "the", "current", "terminal", "size", "." ]
cdd6191a0e0a19bc767f84921650835d099349cf
https://github.com/contains-io/rcli/blob/cdd6191a0e0a19bc767f84921650835d099349cf/rcli/usage.py#L255-L280
train
58,513
contains-io/rcli
rcli/usage.py
_wrap_definition_section
def _wrap_definition_section(source, width): # type: (str, int) -> str """Wrap the given definition section string to the current terminal size. Note: Auto-adjusts the spacing between terms and definitions. Args: source: The section string to wrap. Returns: The wrapped sec...
python
def _wrap_definition_section(source, width): # type: (str, int) -> str """Wrap the given definition section string to the current terminal size. Note: Auto-adjusts the spacing between terms and definitions. Args: source: The section string to wrap. Returns: The wrapped sec...
[ "def", "_wrap_definition_section", "(", "source", ",", "width", ")", ":", "# type: (str, int) -> str", "index", "=", "source", ".", "index", "(", "'\\n'", ")", "+", "1", "definitions", ",", "max_len", "=", "_get_definitions", "(", "source", "[", "index", ":", ...
Wrap the given definition section string to the current terminal size. Note: Auto-adjusts the spacing between terms and definitions. Args: source: The section string to wrap. Returns: The wrapped section string.
[ "Wrap", "the", "given", "definition", "section", "string", "to", "the", "current", "terminal", "size", "." ]
cdd6191a0e0a19bc767f84921650835d099349cf
https://github.com/contains-io/rcli/blob/cdd6191a0e0a19bc767f84921650835d099349cf/rcli/usage.py#L283-L307
train
58,514
contains-io/rcli
rcli/usage.py
_get_definitions
def _get_definitions(source): # type: (str) -> Tuple[Dict[str, str], int] """Extract a dictionary of arguments and definitions. Args: source: The source for a section of a usage string that contains definitions. Returns: A two-tuple containing a dictionary of all arguments ...
python
def _get_definitions(source): # type: (str) -> Tuple[Dict[str, str], int] """Extract a dictionary of arguments and definitions. Args: source: The source for a section of a usage string that contains definitions. Returns: A two-tuple containing a dictionary of all arguments ...
[ "def", "_get_definitions", "(", "source", ")", ":", "# type: (str) -> Tuple[Dict[str, str], int]", "max_len", "=", "0", "descs", "=", "collections", ".", "OrderedDict", "(", ")", "# type: Dict[str, str]", "lines", "=", "(", "s", ".", "strip", "(", ")", "for", "s...
Extract a dictionary of arguments and definitions. Args: source: The source for a section of a usage string that contains definitions. Returns: A two-tuple containing a dictionary of all arguments and definitions as well as the length of the longest argument.
[ "Extract", "a", "dictionary", "of", "arguments", "and", "definitions", "." ]
cdd6191a0e0a19bc767f84921650835d099349cf
https://github.com/contains-io/rcli/blob/cdd6191a0e0a19bc767f84921650835d099349cf/rcli/usage.py#L310-L333
train
58,515
contains-io/rcli
rcli/usage.py
_parse_section
def _parse_section(name, source): # type: (str, str) -> List[str] """Yield each section line. Note: Depending on how it is wrapped, a section line can take up more than one physical line. Args: name: The name of the section to extract (e.g. "Usage"). source: The usage s...
python
def _parse_section(name, source): # type: (str, str) -> List[str] """Yield each section line. Note: Depending on how it is wrapped, a section line can take up more than one physical line. Args: name: The name of the section to extract (e.g. "Usage"). source: The usage s...
[ "def", "_parse_section", "(", "name", ",", "source", ")", ":", "# type: (str, str) -> List[str]", "section", "=", "textwrap", ".", "dedent", "(", "_get_section", "(", "name", ",", "source", ")", "[", "7", ":", "]", ")", "commands", "=", "[", "]", "# type: ...
Yield each section line. Note: Depending on how it is wrapped, a section line can take up more than one physical line. Args: name: The name of the section to extract (e.g. "Usage"). source: The usage string to parse. Returns: A list containing each line, de-wrapped...
[ "Yield", "each", "section", "line", "." ]
cdd6191a0e0a19bc767f84921650835d099349cf
https://github.com/contains-io/rcli/blob/cdd6191a0e0a19bc767f84921650835d099349cf/rcli/usage.py#L336-L361
train
58,516
asascience-open/paegan-transport
paegan/transport/models/behaviors/lifestage.py
DeadLifeStage.move
def move(self, particle, u, v, w, modelTimestep, **kwargs): """ I'm dead, so no behaviors should act on me """ # Kill the particle if it isn't settled and isn't already dead. if not particle.settled and not particle.dead: particle.die() # Still save the temperature and sali...
python
def move(self, particle, u, v, w, modelTimestep, **kwargs): """ I'm dead, so no behaviors should act on me """ # Kill the particle if it isn't settled and isn't already dead. if not particle.settled and not particle.dead: particle.die() # Still save the temperature and sali...
[ "def", "move", "(", "self", ",", "particle", ",", "u", ",", "v", ",", "w", ",", "modelTimestep", ",", "*", "*", "kwargs", ")", ":", "# Kill the particle if it isn't settled and isn't already dead.", "if", "not", "particle", ".", "settled", "and", "not", "parti...
I'm dead, so no behaviors should act on me
[ "I", "m", "dead", "so", "no", "behaviors", "should", "act", "on", "me" ]
99a7f4ea24f0f42d9b34d1fb0e87ab2c49315bd3
https://github.com/asascience-open/paegan-transport/blob/99a7f4ea24f0f42d9b34d1fb0e87ab2c49315bd3/paegan/transport/models/behaviors/lifestage.py#L141-L168
train
58,517
SeattleTestbed/seash
pyreadline/lineeditor/history.py
LineHistory.read_history_file
def read_history_file(self, filename=None): u'''Load a readline history file.''' if filename is None: filename = self.history_filename try: for line in open(filename, u'r'): self.add_history(lineobj.ReadLineTextBuffer(ensure_unicode(line.rstrip())))...
python
def read_history_file(self, filename=None): u'''Load a readline history file.''' if filename is None: filename = self.history_filename try: for line in open(filename, u'r'): self.add_history(lineobj.ReadLineTextBuffer(ensure_unicode(line.rstrip())))...
[ "def", "read_history_file", "(", "self", ",", "filename", "=", "None", ")", ":", "if", "filename", "is", "None", ":", "filename", "=", "self", ".", "history_filename", "try", ":", "for", "line", "in", "open", "(", "filename", ",", "u'r'", ")", ":", "se...
u'''Load a readline history file.
[ "u", "Load", "a", "readline", "history", "file", "." ]
40f9d2285662ff8b61e0468b4196acee089b273b
https://github.com/SeattleTestbed/seash/blob/40f9d2285662ff8b61e0468b4196acee089b273b/pyreadline/lineeditor/history.py#L78-L87
train
58,518
SeattleTestbed/seash
pyreadline/lineeditor/history.py
LineHistory.write_history_file
def write_history_file(self, filename = None): u'''Save a readline history file.''' if filename is None: filename = self.history_filename fp = open(filename, u'wb') for line in self.history[-self.history_length:]: fp.write(ensure_str(line.get_line_text())) ...
python
def write_history_file(self, filename = None): u'''Save a readline history file.''' if filename is None: filename = self.history_filename fp = open(filename, u'wb') for line in self.history[-self.history_length:]: fp.write(ensure_str(line.get_line_text())) ...
[ "def", "write_history_file", "(", "self", ",", "filename", "=", "None", ")", ":", "if", "filename", "is", "None", ":", "filename", "=", "self", ".", "history_filename", "fp", "=", "open", "(", "filename", ",", "u'wb'", ")", "for", "line", "in", "self", ...
u'''Save a readline history file.
[ "u", "Save", "a", "readline", "history", "file", "." ]
40f9d2285662ff8b61e0468b4196acee089b273b
https://github.com/SeattleTestbed/seash/blob/40f9d2285662ff8b61e0468b4196acee089b273b/pyreadline/lineeditor/history.py#L89-L97
train
58,519
SeattleTestbed/seash
pyreadline/lineeditor/history.py
LineHistory.add_history
def add_history(self, line): u'''Append a line to the history buffer, as if it was the last line typed.''' if not hasattr(line, "get_line_text"): line = lineobj.ReadLineTextBuffer(line) if not line.get_line_text(): pass elif len(self.history) > 0 and self.hi...
python
def add_history(self, line): u'''Append a line to the history buffer, as if it was the last line typed.''' if not hasattr(line, "get_line_text"): line = lineobj.ReadLineTextBuffer(line) if not line.get_line_text(): pass elif len(self.history) > 0 and self.hi...
[ "def", "add_history", "(", "self", ",", "line", ")", ":", "if", "not", "hasattr", "(", "line", ",", "\"get_line_text\"", ")", ":", "line", "=", "lineobj", ".", "ReadLineTextBuffer", "(", "line", ")", "if", "not", "line", ".", "get_line_text", "(", ")", ...
u'''Append a line to the history buffer, as if it was the last line typed.
[ "u", "Append", "a", "line", "to", "the", "history", "buffer", "as", "if", "it", "was", "the", "last", "line", "typed", "." ]
40f9d2285662ff8b61e0468b4196acee089b273b
https://github.com/SeattleTestbed/seash/blob/40f9d2285662ff8b61e0468b4196acee089b273b/pyreadline/lineeditor/history.py#L100-L110
train
58,520
SeattleTestbed/seash
pyreadline/lineeditor/history.py
LineHistory.beginning_of_history
def beginning_of_history(self): # (M-<) u'''Move to the first line in the history.''' self.history_cursor = 0 if len(self.history) > 0: self.l_buffer = self.history[0]
python
def beginning_of_history(self): # (M-<) u'''Move to the first line in the history.''' self.history_cursor = 0 if len(self.history) > 0: self.l_buffer = self.history[0]
[ "def", "beginning_of_history", "(", "self", ")", ":", "# (M-<)\r", "self", ".", "history_cursor", "=", "0", "if", "len", "(", "self", ".", "history", ")", ">", "0", ":", "self", ".", "l_buffer", "=", "self", ".", "history", "[", "0", "]" ]
u'''Move to the first line in the history.
[ "u", "Move", "to", "the", "first", "line", "in", "the", "history", "." ]
40f9d2285662ff8b61e0468b4196acee089b273b
https://github.com/SeattleTestbed/seash/blob/40f9d2285662ff8b61e0468b4196acee089b273b/pyreadline/lineeditor/history.py#L128-L132
train
58,521
asascience-open/paegan-transport
paegan/transport/utils/asatransport.py
AsaTransport.get_time_objects_from_model_timesteps
def get_time_objects_from_model_timesteps(cls, times, start): """ Calculate the datetimes of the model timesteps times should start at 0 and be in seconds """ modelTimestep = [] newtimes = [] for i in xrange(0, len(times)): try: mode...
python
def get_time_objects_from_model_timesteps(cls, times, start): """ Calculate the datetimes of the model timesteps times should start at 0 and be in seconds """ modelTimestep = [] newtimes = [] for i in xrange(0, len(times)): try: mode...
[ "def", "get_time_objects_from_model_timesteps", "(", "cls", ",", "times", ",", "start", ")", ":", "modelTimestep", "=", "[", "]", "newtimes", "=", "[", "]", "for", "i", "in", "xrange", "(", "0", ",", "len", "(", "times", ")", ")", ":", "try", ":", "m...
Calculate the datetimes of the model timesteps times should start at 0 and be in seconds
[ "Calculate", "the", "datetimes", "of", "the", "model", "timesteps" ]
99a7f4ea24f0f42d9b34d1fb0e87ab2c49315bd3
https://github.com/asascience-open/paegan-transport/blob/99a7f4ea24f0f42d9b34d1fb0e87ab2c49315bd3/paegan/transport/utils/asatransport.py#L14-L31
train
58,522
asascience-open/paegan-transport
paegan/transport/utils/asatransport.py
AsaTransport.fill_polygon_with_points
def fill_polygon_with_points(cls, goal=None, polygon=None): """ Fill a shapely polygon with X number of points """ if goal is None: raise ValueError("Must specify the number of points (goal) to fill the polygon with") if polygon is None or (not isinstance(polygon...
python
def fill_polygon_with_points(cls, goal=None, polygon=None): """ Fill a shapely polygon with X number of points """ if goal is None: raise ValueError("Must specify the number of points (goal) to fill the polygon with") if polygon is None or (not isinstance(polygon...
[ "def", "fill_polygon_with_points", "(", "cls", ",", "goal", "=", "None", ",", "polygon", "=", "None", ")", ":", "if", "goal", "is", "None", ":", "raise", "ValueError", "(", "\"Must specify the number of points (goal) to fill the polygon with\"", ")", "if", "polygon"...
Fill a shapely polygon with X number of points
[ "Fill", "a", "shapely", "polygon", "with", "X", "number", "of", "points" ]
99a7f4ea24f0f42d9b34d1fb0e87ab2c49315bd3
https://github.com/asascience-open/paegan-transport/blob/99a7f4ea24f0f42d9b34d1fb0e87ab2c49315bd3/paegan/transport/utils/asatransport.py#L34-L60
train
58,523
asascience-open/paegan-transport
paegan/transport/utils/asatransport.py
AsaTransport.distance_from_location_using_u_v_w
def distance_from_location_using_u_v_w(cls, u=None, v=None, w=None, timestep=None, location=None): """ Calculate the greate distance from a location using u, v, and w. u, v, and w must be in the same units as the timestep. Stick with seconds. """ # Move horizontally ...
python
def distance_from_location_using_u_v_w(cls, u=None, v=None, w=None, timestep=None, location=None): """ Calculate the greate distance from a location using u, v, and w. u, v, and w must be in the same units as the timestep. Stick with seconds. """ # Move horizontally ...
[ "def", "distance_from_location_using_u_v_w", "(", "cls", ",", "u", "=", "None", ",", "v", "=", "None", ",", "w", "=", "None", ",", "timestep", "=", "None", ",", "location", "=", "None", ")", ":", "# Move horizontally", "distance_horiz", "=", "0", "azimuth"...
Calculate the greate distance from a location using u, v, and w. u, v, and w must be in the same units as the timestep. Stick with seconds.
[ "Calculate", "the", "greate", "distance", "from", "a", "location", "using", "u", "v", "and", "w", "." ]
99a7f4ea24f0f42d9b34d1fb0e87ab2c49315bd3
https://github.com/asascience-open/paegan-transport/blob/99a7f4ea24f0f42d9b34d1fb0e87ab2c49315bd3/paegan/transport/utils/asatransport.py#L63-L113
train
58,524
CMUSTRUDEL/strudel.utils
stutils/mapreduce.py
ThreadPool.shutdown
def shutdown(self): """Wait for all threads to complete""" # cleanup self.started = False try: # nice way of doing things - let's wait until all items # in the queue are processed for t in self._threads: t.join() finally: ...
python
def shutdown(self): """Wait for all threads to complete""" # cleanup self.started = False try: # nice way of doing things - let's wait until all items # in the queue are processed for t in self._threads: t.join() finally: ...
[ "def", "shutdown", "(", "self", ")", ":", "# cleanup", "self", ".", "started", "=", "False", "try", ":", "# nice way of doing things - let's wait until all items", "# in the queue are processed", "for", "t", "in", "self", ".", "_threads", ":", "t", ".", "join", "(...
Wait for all threads to complete
[ "Wait", "for", "all", "threads", "to", "complete" ]
888ef72fcdb851b5873092bc9c4d6958733691f2
https://github.com/CMUSTRUDEL/strudel.utils/blob/888ef72fcdb851b5873092bc9c4d6958733691f2/stutils/mapreduce.py#L119-L131
train
58,525
tr00st/insult_generator
insultgenerator/phrases.py
_unpack_bytes
def _unpack_bytes(bytes): """ Unpack a set of bytes into an integer. First pads to 4 bytes. Little endian. """ if bytes == b'': return 0 int_length = 4 len_diff = int_length - len(bytes) bytes = bytes + len_diff * b'\x00' return struct.unpack("<L", bytes)[0]
python
def _unpack_bytes(bytes): """ Unpack a set of bytes into an integer. First pads to 4 bytes. Little endian. """ if bytes == b'': return 0 int_length = 4 len_diff = int_length - len(bytes) bytes = bytes + len_diff * b'\x00' return struct.unpack("<L", bytes)[0]
[ "def", "_unpack_bytes", "(", "bytes", ")", ":", "if", "bytes", "==", "b''", ":", "return", "0", "int_length", "=", "4", "len_diff", "=", "int_length", "-", "len", "(", "bytes", ")", "bytes", "=", "bytes", "+", "len_diff", "*", "b'\\x00'", "return", "st...
Unpack a set of bytes into an integer. First pads to 4 bytes. Little endian.
[ "Unpack", "a", "set", "of", "bytes", "into", "an", "integer", ".", "First", "pads", "to", "4", "bytes", ".", "Little", "endian", "." ]
a4496b29ea4beae6b82a4119e8dfbd871be75dbb
https://github.com/tr00st/insult_generator/blob/a4496b29ea4beae6b82a4119e8dfbd871be75dbb/insultgenerator/phrases.py#L4-L14
train
58,526
bitlabstudio/django-rapid-prototyping
rapid_prototyping/context/utils.py
get_sprints
def get_sprints(): """ Returns all sprints, enriched with their assigned tasks. The project should only have one ``sprints.py`` module. We will define it's path via the ``RAPID_PROTOTYPING_SPRINTS_MODULE`` setting. The setting should be the fully qualified name of the ``sprints.py`` module (i.e. ...
python
def get_sprints(): """ Returns all sprints, enriched with their assigned tasks. The project should only have one ``sprints.py`` module. We will define it's path via the ``RAPID_PROTOTYPING_SPRINTS_MODULE`` setting. The setting should be the fully qualified name of the ``sprints.py`` module (i.e. ...
[ "def", "get_sprints", "(", ")", ":", "sprints", "=", "load_member_from_setting", "(", "'RAPID_PROTOTYPING_SPRINTS_MODULE'", ")", "all_tasks", "=", "[", "]", "# TODO The onerror parameter is basically a workaround to ignore errors", "# The reason for that being, that in my case, the G...
Returns all sprints, enriched with their assigned tasks. The project should only have one ``sprints.py`` module. We will define it's path via the ``RAPID_PROTOTYPING_SPRINTS_MODULE`` setting. The setting should be the fully qualified name of the ``sprints.py`` module (i.e. ``projectname.context.sprints...
[ "Returns", "all", "sprints", "enriched", "with", "their", "assigned", "tasks", "." ]
fd14ab5453bd7a0c2d5b973e8d96148963b03ab0
https://github.com/bitlabstudio/django-rapid-prototyping/blob/fd14ab5453bd7a0c2d5b973e8d96148963b03ab0/rapid_prototyping/context/utils.py#L10-L58
train
58,527
bitlabstudio/django-rapid-prototyping
rapid_prototyping/context/utils.py
append_overhead_costs
def append_overhead_costs(costs, new_id, overhead_percentage=0.15): """ Adds 15% overhead costs to the list of costs. Usage:: from rapid_prototyping.context.utils import append_overhead_costs costs = [ .... ] costs = append_overhead_costs(costs, MAIN_ID + get_co...
python
def append_overhead_costs(costs, new_id, overhead_percentage=0.15): """ Adds 15% overhead costs to the list of costs. Usage:: from rapid_prototyping.context.utils import append_overhead_costs costs = [ .... ] costs = append_overhead_costs(costs, MAIN_ID + get_co...
[ "def", "append_overhead_costs", "(", "costs", ",", "new_id", ",", "overhead_percentage", "=", "0.15", ")", ":", "total_time", "=", "0", "for", "item", "in", "costs", ":", "total_time", "+=", "item", "[", "'time'", "]", "costs", ".", "append", "(", "{", "...
Adds 15% overhead costs to the list of costs. Usage:: from rapid_prototyping.context.utils import append_overhead_costs costs = [ .... ] costs = append_overhead_costs(costs, MAIN_ID + get_counter(counter)[0]) :param costs: Your final list of costs. :param new_i...
[ "Adds", "15%", "overhead", "costs", "to", "the", "list", "of", "costs", "." ]
fd14ab5453bd7a0c2d5b973e8d96148963b03ab0
https://github.com/bitlabstudio/django-rapid-prototyping/blob/fd14ab5453bd7a0c2d5b973e8d96148963b03ab0/rapid_prototyping/context/utils.py#L84-L109
train
58,528
ponty/confduino
confduino/__init__.py
arduino_default_path
def arduino_default_path(): """platform specific default root path.""" if sys.platform == 'darwin': s = path('/Applications/Arduino.app/Contents/Resources/Java') elif sys.platform == 'win32': s = None else: s = path('/usr/share/arduino/') return s
python
def arduino_default_path(): """platform specific default root path.""" if sys.platform == 'darwin': s = path('/Applications/Arduino.app/Contents/Resources/Java') elif sys.platform == 'win32': s = None else: s = path('/usr/share/arduino/') return s
[ "def", "arduino_default_path", "(", ")", ":", "if", "sys", ".", "platform", "==", "'darwin'", ":", "s", "=", "path", "(", "'/Applications/Arduino.app/Contents/Resources/Java'", ")", "elif", "sys", ".", "platform", "==", "'win32'", ":", "s", "=", "None", "else"...
platform specific default root path.
[ "platform", "specific", "default", "root", "path", "." ]
f4c261e5e84997f145a8bdd001f471db74c9054b
https://github.com/ponty/confduino/blob/f4c261e5e84997f145a8bdd001f471db74c9054b/confduino/__init__.py#L16-L24
train
58,529
agrc/agrc.python
agrc/update.py
checkForChanges
def checkForChanges(f, sde, isTable): """ returns False if there are no changes """ # try simple feature count first fCount = int(arcpy.GetCount_management(f).getOutput(0)) sdeCount = int(arcpy.GetCount_management(sde).getOutput(0)) if fCount != sdeCount: return True fields = [...
python
def checkForChanges(f, sde, isTable): """ returns False if there are no changes """ # try simple feature count first fCount = int(arcpy.GetCount_management(f).getOutput(0)) sdeCount = int(arcpy.GetCount_management(sde).getOutput(0)) if fCount != sdeCount: return True fields = [...
[ "def", "checkForChanges", "(", "f", ",", "sde", ",", "isTable", ")", ":", "# try simple feature count first", "fCount", "=", "int", "(", "arcpy", ".", "GetCount_management", "(", "f", ")", ".", "getOutput", "(", "0", ")", ")", "sdeCount", "=", "int", "(", ...
returns False if there are no changes
[ "returns", "False", "if", "there", "are", "no", "changes" ]
be427e919bd4cdd6f19524b7f7fe18882429c25b
https://github.com/agrc/agrc.python/blob/be427e919bd4cdd6f19524b7f7fe18882429c25b/agrc/update.py#L164-L248
train
58,530
ponty/confduino
confduino/examples/metaboard.py
install_metaboard
def install_metaboard( replace_existing=False, ): """install metaboard. http://metalab.at/wiki/Metaboard """ metaboard = AutoBunch() metaboard.name = 'Metaboard' metaboard.upload.protocol = 'usbasp' metaboard.upload.maximum_size = '14336' metaboard.upload.speed = '19200' meta...
python
def install_metaboard( replace_existing=False, ): """install metaboard. http://metalab.at/wiki/Metaboard """ metaboard = AutoBunch() metaboard.name = 'Metaboard' metaboard.upload.protocol = 'usbasp' metaboard.upload.maximum_size = '14336' metaboard.upload.speed = '19200' meta...
[ "def", "install_metaboard", "(", "replace_existing", "=", "False", ",", ")", ":", "metaboard", "=", "AutoBunch", "(", ")", "metaboard", ".", "name", "=", "'Metaboard'", "metaboard", ".", "upload", ".", "protocol", "=", "'usbasp'", "metaboard", ".", "upload", ...
install metaboard. http://metalab.at/wiki/Metaboard
[ "install", "metaboard", "." ]
f4c261e5e84997f145a8bdd001f471db74c9054b
https://github.com/ponty/confduino/blob/f4c261e5e84997f145a8bdd001f471db74c9054b/confduino/examples/metaboard.py#L7-L30
train
58,531
AtomHash/evernode
evernode/classes/paginate.py
Paginate.__total_pages
def __total_pages(self) -> int: """ Return max pages created by limit """ row_count = self.model.query.count() if isinstance(row_count, int): return int(row_count / self.limit) return None
python
def __total_pages(self) -> int: """ Return max pages created by limit """ row_count = self.model.query.count() if isinstance(row_count, int): return int(row_count / self.limit) return None
[ "def", "__total_pages", "(", "self", ")", "->", "int", ":", "row_count", "=", "self", ".", "model", ".", "query", ".", "count", "(", ")", "if", "isinstance", "(", "row_count", ",", "int", ")", ":", "return", "int", "(", "row_count", "/", "self", ".",...
Return max pages created by limit
[ "Return", "max", "pages", "created", "by", "limit" ]
b2fb91555fb937a3f3eba41db56dee26f9b034be
https://github.com/AtomHash/evernode/blob/b2fb91555fb937a3f3eba41db56dee26f9b034be/evernode/classes/paginate.py#L22-L27
train
58,532
AtomHash/evernode
evernode/classes/paginate.py
Paginate.links
def links(self, base_link, current_page) -> dict: """ Return JSON paginate links """ max_pages = self.max_pages - 1 if \ self.max_pages > 0 else self.max_pages base_link = '/%s' % (base_link.strip("/")) self_page = current_page prev = current_page - 1 if current...
python
def links(self, base_link, current_page) -> dict: """ Return JSON paginate links """ max_pages = self.max_pages - 1 if \ self.max_pages > 0 else self.max_pages base_link = '/%s' % (base_link.strip("/")) self_page = current_page prev = current_page - 1 if current...
[ "def", "links", "(", "self", ",", "base_link", ",", "current_page", ")", "->", "dict", ":", "max_pages", "=", "self", ".", "max_pages", "-", "1", "if", "self", ".", "max_pages", ">", "0", "else", "self", ".", "max_pages", "base_link", "=", "'/%s'", "%"...
Return JSON paginate links
[ "Return", "JSON", "paginate", "links" ]
b2fb91555fb937a3f3eba41db56dee26f9b034be
https://github.com/AtomHash/evernode/blob/b2fb91555fb937a3f3eba41db56dee26f9b034be/evernode/classes/paginate.py#L83-L103
train
58,533
AtomHash/evernode
evernode/classes/paginate.py
Paginate.json_paginate
def json_paginate(self, base_url, page_number): """ Return a dict for a JSON paginate """ data = self.page(page_number) first_id = None last_id = None if data: first_id = data[0].id last_id = data[-1].id return { 'meta': { ...
python
def json_paginate(self, base_url, page_number): """ Return a dict for a JSON paginate """ data = self.page(page_number) first_id = None last_id = None if data: first_id = data[0].id last_id = data[-1].id return { 'meta': { ...
[ "def", "json_paginate", "(", "self", ",", "base_url", ",", "page_number", ")", ":", "data", "=", "self", ".", "page", "(", "page_number", ")", "first_id", "=", "None", "last_id", "=", "None", "if", "data", ":", "first_id", "=", "data", "[", "0", "]", ...
Return a dict for a JSON paginate
[ "Return", "a", "dict", "for", "a", "JSON", "paginate" ]
b2fb91555fb937a3f3eba41db56dee26f9b034be
https://github.com/AtomHash/evernode/blob/b2fb91555fb937a3f3eba41db56dee26f9b034be/evernode/classes/paginate.py#L105-L122
train
58,534
jaraco/jaraco.logging
jaraco/logging.py
add_arguments
def add_arguments(parser, default_level=logging.INFO): """ Add arguments to an ArgumentParser or OptionParser for purposes of grabbing a logging level. """ adder = ( getattr(parser, 'add_argument', None) or getattr(parser, 'add_option') ) adder( '-l', '--log-level', default=default_level, type=lo...
python
def add_arguments(parser, default_level=logging.INFO): """ Add arguments to an ArgumentParser or OptionParser for purposes of grabbing a logging level. """ adder = ( getattr(parser, 'add_argument', None) or getattr(parser, 'add_option') ) adder( '-l', '--log-level', default=default_level, type=lo...
[ "def", "add_arguments", "(", "parser", ",", "default_level", "=", "logging", ".", "INFO", ")", ":", "adder", "=", "(", "getattr", "(", "parser", ",", "'add_argument'", ",", "None", ")", "or", "getattr", "(", "parser", ",", "'add_option'", ")", ")", "adde...
Add arguments to an ArgumentParser or OptionParser for purposes of grabbing a logging level.
[ "Add", "arguments", "to", "an", "ArgumentParser", "or", "OptionParser", "for", "purposes", "of", "grabbing", "a", "logging", "level", "." ]
202d0d3b7c16503f9b8de83b6054f1306ae61930
https://github.com/jaraco/jaraco.logging/blob/202d0d3b7c16503f9b8de83b6054f1306ae61930/jaraco/logging.py#L28-L39
train
58,535
jaraco/jaraco.logging
jaraco/logging.py
setup
def setup(options, **kwargs): """ Setup logging with options or arguments from an OptionParser or ArgumentParser. Also pass any keyword arguments to the basicConfig call. """ params = dict(kwargs) params.update(level=options.log_level) logging.basicConfig(**params)
python
def setup(options, **kwargs): """ Setup logging with options or arguments from an OptionParser or ArgumentParser. Also pass any keyword arguments to the basicConfig call. """ params = dict(kwargs) params.update(level=options.log_level) logging.basicConfig(**params)
[ "def", "setup", "(", "options", ",", "*", "*", "kwargs", ")", ":", "params", "=", "dict", "(", "kwargs", ")", "params", ".", "update", "(", "level", "=", "options", ".", "log_level", ")", "logging", ".", "basicConfig", "(", "*", "*", "params", ")" ]
Setup logging with options or arguments from an OptionParser or ArgumentParser. Also pass any keyword arguments to the basicConfig call.
[ "Setup", "logging", "with", "options", "or", "arguments", "from", "an", "OptionParser", "or", "ArgumentParser", ".", "Also", "pass", "any", "keyword", "arguments", "to", "the", "basicConfig", "call", "." ]
202d0d3b7c16503f9b8de83b6054f1306ae61930
https://github.com/jaraco/jaraco.logging/blob/202d0d3b7c16503f9b8de83b6054f1306ae61930/jaraco/logging.py#L42-L50
train
58,536
jaraco/jaraco.logging
jaraco/logging.py
setup_requests_logging
def setup_requests_logging(level): """ Setup logging for 'requests' such that it logs details about the connection, headers, etc. """ requests_log = logging.getLogger("requests.packages.urllib3") requests_log.setLevel(level) requests_log.propagate = True # enable debugging at httplib level http_clie...
python
def setup_requests_logging(level): """ Setup logging for 'requests' such that it logs details about the connection, headers, etc. """ requests_log = logging.getLogger("requests.packages.urllib3") requests_log.setLevel(level) requests_log.propagate = True # enable debugging at httplib level http_clie...
[ "def", "setup_requests_logging", "(", "level", ")", ":", "requests_log", "=", "logging", ".", "getLogger", "(", "\"requests.packages.urllib3\"", ")", "requests_log", ".", "setLevel", "(", "level", ")", "requests_log", ".", "propagate", "=", "True", "# enable debuggi...
Setup logging for 'requests' such that it logs details about the connection, headers, etc.
[ "Setup", "logging", "for", "requests", "such", "that", "it", "logs", "details", "about", "the", "connection", "headers", "etc", "." ]
202d0d3b7c16503f9b8de83b6054f1306ae61930
https://github.com/jaraco/jaraco.logging/blob/202d0d3b7c16503f9b8de83b6054f1306ae61930/jaraco/logging.py#L53-L63
train
58,537
jaraco/jaraco.logging
jaraco/logging.py
TimestampFileHandler._set_period
def _set_period(self, period): """ Set the period for the timestamp. If period is 0 or None, no period will be used. """ self._period = period if period: self._period_seconds = tempora.get_period_seconds(self._period) self._date_format = tempora.get_date_format_string( self._period_secon...
python
def _set_period(self, period): """ Set the period for the timestamp. If period is 0 or None, no period will be used. """ self._period = period if period: self._period_seconds = tempora.get_period_seconds(self._period) self._date_format = tempora.get_date_format_string( self._period_secon...
[ "def", "_set_period", "(", "self", ",", "period", ")", ":", "self", ".", "_period", "=", "period", "if", "period", ":", "self", ".", "_period_seconds", "=", "tempora", ".", "get_period_seconds", "(", "self", ".", "_period", ")", "self", ".", "_date_format"...
Set the period for the timestamp. If period is 0 or None, no period will be used.
[ "Set", "the", "period", "for", "the", "timestamp", ".", "If", "period", "is", "0", "or", "None", "no", "period", "will", "be", "used", "." ]
202d0d3b7c16503f9b8de83b6054f1306ae61930
https://github.com/jaraco/jaraco.logging/blob/202d0d3b7c16503f9b8de83b6054f1306ae61930/jaraco/logging.py#L83-L95
train
58,538
jaraco/jaraco.logging
jaraco/logging.py
TimestampFileHandler.get_filename
def get_filename(self, t): """ Return the appropriate filename for the given time based on the defined period. """ root, ext = os.path.splitext(self.base_filename) # remove seconds not significant to the period if self._period_seconds: t -= t % self._period_seconds # convert it to a datetime...
python
def get_filename(self, t): """ Return the appropriate filename for the given time based on the defined period. """ root, ext = os.path.splitext(self.base_filename) # remove seconds not significant to the period if self._period_seconds: t -= t % self._period_seconds # convert it to a datetime...
[ "def", "get_filename", "(", "self", ",", "t", ")", ":", "root", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "self", ".", "base_filename", ")", "# remove seconds not significant to the period\r", "if", "self", ".", "_period_seconds", ":", "t", "...
Return the appropriate filename for the given time based on the defined period.
[ "Return", "the", "appropriate", "filename", "for", "the", "given", "time", "based", "on", "the", "defined", "period", "." ]
202d0d3b7c16503f9b8de83b6054f1306ae61930
https://github.com/jaraco/jaraco.logging/blob/202d0d3b7c16503f9b8de83b6054f1306ae61930/jaraco/logging.py#L110-L133
train
58,539
jaraco/jaraco.logging
jaraco/logging.py
TimestampFileHandler.emit
def emit(self, record): """ Emit a record. Output the record to the file, ensuring that the currently- opened file has the correct date. """ now = time.time() current_name = self.get_filename(now) try: if not self.stream.name == current_name: self._use_file(current_name) except Att...
python
def emit(self, record): """ Emit a record. Output the record to the file, ensuring that the currently- opened file has the correct date. """ now = time.time() current_name = self.get_filename(now) try: if not self.stream.name == current_name: self._use_file(current_name) except Att...
[ "def", "emit", "(", "self", ",", "record", ")", ":", "now", "=", "time", ".", "time", "(", ")", "current_name", "=", "self", ".", "get_filename", "(", "now", ")", "try", ":", "if", "not", "self", ".", "stream", ".", "name", "==", "current_name", ":...
Emit a record. Output the record to the file, ensuring that the currently- opened file has the correct date.
[ "Emit", "a", "record", ".", "Output", "the", "record", "to", "the", "file", "ensuring", "that", "the", "currently", "-", "opened", "file", "has", "the", "correct", "date", "." ]
202d0d3b7c16503f9b8de83b6054f1306ae61930
https://github.com/jaraco/jaraco.logging/blob/202d0d3b7c16503f9b8de83b6054f1306ae61930/jaraco/logging.py#L135-L150
train
58,540
silver-castle/mach9
mach9/static.py
register
def register(app, uri, file_or_directory, pattern, use_modified_since, use_content_range): # TODO: Though mach9 is not a file server, I feel like we should at least # make a good effort here. Modified-since is nice, but we could # also look into etags, expires, and caching """ ...
python
def register(app, uri, file_or_directory, pattern, use_modified_since, use_content_range): # TODO: Though mach9 is not a file server, I feel like we should at least # make a good effort here. Modified-since is nice, but we could # also look into etags, expires, and caching """ ...
[ "def", "register", "(", "app", ",", "uri", ",", "file_or_directory", ",", "pattern", ",", "use_modified_since", ",", "use_content_range", ")", ":", "# TODO: Though mach9 is not a file server, I feel like we should at least", "# make a good effort here. Modified-since is nice...
Register a static directory handler with Mach9 by adding a route to the router and registering a handler. :param app: Mach9 :param file_or_directory: File or directory path to serve from :param uri: URL to serve from :param pattern: regular expression used to match files in the URL :param use_m...
[ "Register", "a", "static", "directory", "handler", "with", "Mach9", "by", "adding", "a", "route", "to", "the", "router", "and", "registering", "a", "handler", "." ]
7a623aab3c70d89d36ade6901b6307e115400c5e
https://github.com/silver-castle/mach9/blob/7a623aab3c70d89d36ade6901b6307e115400c5e/mach9/static.py#L19-L104
train
58,541
pyQode/pyqode-uic
pyqode_uic.py
fix_imports
def fix_imports(script): """ Replace "from PyQt5 import" by "from pyqode.qt import". :param script: script path """ with open(script, 'r') as f_script: lines = f_script.read().splitlines() new_lines = [] for l in lines: if l.startswith("import "): l = "from . " +...
python
def fix_imports(script): """ Replace "from PyQt5 import" by "from pyqode.qt import". :param script: script path """ with open(script, 'r') as f_script: lines = f_script.read().splitlines() new_lines = [] for l in lines: if l.startswith("import "): l = "from . " +...
[ "def", "fix_imports", "(", "script", ")", ":", "with", "open", "(", "script", ",", "'r'", ")", "as", "f_script", ":", "lines", "=", "f_script", ".", "read", "(", ")", ".", "splitlines", "(", ")", "new_lines", "=", "[", "]", "for", "l", "in", "lines...
Replace "from PyQt5 import" by "from pyqode.qt import". :param script: script path
[ "Replace", "from", "PyQt5", "import", "by", "from", "pyqode", ".", "qt", "import", "." ]
e8b7a1e275dbb5d76031f197d93ede1ea505fdcb
https://github.com/pyQode/pyqode-uic/blob/e8b7a1e275dbb5d76031f197d93ede1ea505fdcb/pyqode_uic.py#L17-L33
train
58,542
expert360/cfn-params
cfnparams/params.py
PythonParams.eval_py
def eval_py(self, _globals, _locals): """ Evaluates a file containing a Python params dictionary. """ try: params = eval(self.script, _globals, _locals) except NameError as e: raise Exception( 'Failed to evaluate parameters: {}' ...
python
def eval_py(self, _globals, _locals): """ Evaluates a file containing a Python params dictionary. """ try: params = eval(self.script, _globals, _locals) except NameError as e: raise Exception( 'Failed to evaluate parameters: {}' ...
[ "def", "eval_py", "(", "self", ",", "_globals", ",", "_locals", ")", ":", "try", ":", "params", "=", "eval", "(", "self", ".", "script", ",", "_globals", ",", "_locals", ")", "except", "NameError", "as", "e", ":", "raise", "Exception", "(", "'Failed to...
Evaluates a file containing a Python params dictionary.
[ "Evaluates", "a", "file", "containing", "a", "Python", "params", "dictionary", "." ]
f6d9d796b8ce346e9fd916e26ed08958e5356e31
https://github.com/expert360/cfn-params/blob/f6d9d796b8ce346e9fd916e26ed08958e5356e31/cfnparams/params.py#L66-L80
train
58,543
expert360/cfn-params
cfnparams/params.py
ParamsFactory.new
def new(cls, arg): """ Creates a new Parameter object from the given ParameterArgument. """ content = None if arg.kind == 'file': if os.path.exists(arg.value): with open(arg.value, 'r') as f: content = f.read() else: ...
python
def new(cls, arg): """ Creates a new Parameter object from the given ParameterArgument. """ content = None if arg.kind == 'file': if os.path.exists(arg.value): with open(arg.value, 'r') as f: content = f.read() else: ...
[ "def", "new", "(", "cls", ",", "arg", ")", ":", "content", "=", "None", "if", "arg", ".", "kind", "==", "'file'", ":", "if", "os", ".", "path", ".", "exists", "(", "arg", ".", "value", ")", ":", "with", "open", "(", "arg", ".", "value", ",", ...
Creates a new Parameter object from the given ParameterArgument.
[ "Creates", "a", "new", "Parameter", "object", "from", "the", "given", "ParameterArgument", "." ]
f6d9d796b8ce346e9fd916e26ed08958e5356e31
https://github.com/expert360/cfn-params/blob/f6d9d796b8ce346e9fd916e26ed08958e5356e31/cfnparams/params.py#L91-L111
train
58,544
cstatz/maui
maui/mesh/rectilinear.py
RectilinearMesh.minimum_pitch
def minimum_pitch(self): """ Returns the minimal pitch between two neighboring nodes of the mesh in each direction. :return: Minimal pitch in each direction. """ pitch = self.pitch minimal_pitch = [] for p in pitch: minimal_pitch.append(min(p)) retu...
python
def minimum_pitch(self): """ Returns the minimal pitch between two neighboring nodes of the mesh in each direction. :return: Minimal pitch in each direction. """ pitch = self.pitch minimal_pitch = [] for p in pitch: minimal_pitch.append(min(p)) retu...
[ "def", "minimum_pitch", "(", "self", ")", ":", "pitch", "=", "self", ".", "pitch", "minimal_pitch", "=", "[", "]", "for", "p", "in", "pitch", ":", "minimal_pitch", ".", "append", "(", "min", "(", "p", ")", ")", "return", "min", "(", "minimal_pitch", ...
Returns the minimal pitch between two neighboring nodes of the mesh in each direction. :return: Minimal pitch in each direction.
[ "Returns", "the", "minimal", "pitch", "between", "two", "neighboring", "nodes", "of", "the", "mesh", "in", "each", "direction", "." ]
db99986e93699ee20c5cffdd5b4ee446f8607c5d
https://github.com/cstatz/maui/blob/db99986e93699ee20c5cffdd5b4ee446f8607c5d/maui/mesh/rectilinear.py#L154-L165
train
58,545
cstatz/maui
maui/mesh/rectilinear.py
RectilinearMesh.surrounding_nodes
def surrounding_nodes(self, position): """ Returns nearest node indices and direction of opposite node. :param position: Position inside the mesh to search nearest node for as (x,y,z) :return: Nearest node indices and direction of opposite node. """ n_node_index, n_node_positio...
python
def surrounding_nodes(self, position): """ Returns nearest node indices and direction of opposite node. :param position: Position inside the mesh to search nearest node for as (x,y,z) :return: Nearest node indices and direction of opposite node. """ n_node_index, n_node_positio...
[ "def", "surrounding_nodes", "(", "self", ",", "position", ")", ":", "n_node_index", ",", "n_node_position", ",", "n_node_error", "=", "self", ".", "nearest_node", "(", "position", ")", "if", "n_node_error", "==", "0.0", ":", "index_mod", "=", "[", "]", "for"...
Returns nearest node indices and direction of opposite node. :param position: Position inside the mesh to search nearest node for as (x,y,z) :return: Nearest node indices and direction of opposite node.
[ "Returns", "nearest", "node", "indices", "and", "direction", "of", "opposite", "node", "." ]
db99986e93699ee20c5cffdd5b4ee446f8607c5d
https://github.com/cstatz/maui/blob/db99986e93699ee20c5cffdd5b4ee446f8607c5d/maui/mesh/rectilinear.py#L181-L216
train
58,546
MisanthropicBit/colorise
colorise/ColorFormatParser.py
ColorFormatParser.tokenize
def tokenize(self, string): """Tokenize a string and return an iterator over its tokens.""" it = colorise.compat.ifilter(None, self._pattern.finditer(string)) try: t = colorise.compat.next(it) except StopIteration: yield string, False return ...
python
def tokenize(self, string): """Tokenize a string and return an iterator over its tokens.""" it = colorise.compat.ifilter(None, self._pattern.finditer(string)) try: t = colorise.compat.next(it) except StopIteration: yield string, False return ...
[ "def", "tokenize", "(", "self", ",", "string", ")", ":", "it", "=", "colorise", ".", "compat", ".", "ifilter", "(", "None", ",", "self", ".", "_pattern", ".", "finditer", "(", "string", ")", ")", "try", ":", "t", "=", "colorise", ".", "compat", "."...
Tokenize a string and return an iterator over its tokens.
[ "Tokenize", "a", "string", "and", "return", "an", "iterator", "over", "its", "tokens", "." ]
e630df74b8b27680a43c370ddbe98766be50158c
https://github.com/MisanthropicBit/colorise/blob/e630df74b8b27680a43c370ddbe98766be50158c/colorise/ColorFormatParser.py#L35-L83
train
58,547
MisanthropicBit/colorise
colorise/ColorFormatParser.py
ColorFormatParser.parse
def parse(self, format_string): """Parse color syntax from a formatted string.""" txt, state = '', 0 colorstack = [(None, None)] itokens = self.tokenize(format_string) for token, escaped in itokens: if token == self._START_TOKEN and not escaped: if tx...
python
def parse(self, format_string): """Parse color syntax from a formatted string.""" txt, state = '', 0 colorstack = [(None, None)] itokens = self.tokenize(format_string) for token, escaped in itokens: if token == self._START_TOKEN and not escaped: if tx...
[ "def", "parse", "(", "self", ",", "format_string", ")", ":", "txt", ",", "state", "=", "''", ",", "0", "colorstack", "=", "[", "(", "None", ",", "None", ")", "]", "itokens", "=", "self", ".", "tokenize", "(", "format_string", ")", "for", "token", "...
Parse color syntax from a formatted string.
[ "Parse", "color", "syntax", "from", "a", "formatted", "string", "." ]
e630df74b8b27680a43c370ddbe98766be50158c
https://github.com/MisanthropicBit/colorise/blob/e630df74b8b27680a43c370ddbe98766be50158c/colorise/ColorFormatParser.py#L85-L130
train
58,548
sherlocke/pywatson
pywatson/answer/evidence.py
Evidence.from_mapping
def from_mapping(cls, evidence_mapping): """Create an Evidence instance from the given mapping :param evidence_mapping: a mapping (e.g. dict) of values provided by Watson :return: a new Evidence """ return cls(metadata_map=MetadataMap.from_mapping(evidence_mapping['metadataMap']...
python
def from_mapping(cls, evidence_mapping): """Create an Evidence instance from the given mapping :param evidence_mapping: a mapping (e.g. dict) of values provided by Watson :return: a new Evidence """ return cls(metadata_map=MetadataMap.from_mapping(evidence_mapping['metadataMap']...
[ "def", "from_mapping", "(", "cls", ",", "evidence_mapping", ")", ":", "return", "cls", "(", "metadata_map", "=", "MetadataMap", ".", "from_mapping", "(", "evidence_mapping", "[", "'metadataMap'", "]", ")", ",", "copyright", "=", "evidence_mapping", "[", "'copyri...
Create an Evidence instance from the given mapping :param evidence_mapping: a mapping (e.g. dict) of values provided by Watson :return: a new Evidence
[ "Create", "an", "Evidence", "instance", "from", "the", "given", "mapping" ]
ab15d1ca3c01a185136b420d443f712dfa865485
https://github.com/sherlocke/pywatson/blob/ab15d1ca3c01a185136b420d443f712dfa865485/pywatson/answer/evidence.py#L17-L30
train
58,549
letuananh/puchikarui
puchikarui/puchikarui.py
to_obj
def to_obj(cls, obj_data=None, *fields, **field_map): ''' prioritize obj_dict when there are conficts ''' obj_dict = obj_data.__dict__ if hasattr(obj_data, '__dict__') else obj_data if not fields: fields = obj_dict.keys() obj = cls() update_obj(obj_dict, obj, *fields, **field_map) return...
python
def to_obj(cls, obj_data=None, *fields, **field_map): ''' prioritize obj_dict when there are conficts ''' obj_dict = obj_data.__dict__ if hasattr(obj_data, '__dict__') else obj_data if not fields: fields = obj_dict.keys() obj = cls() update_obj(obj_dict, obj, *fields, **field_map) return...
[ "def", "to_obj", "(", "cls", ",", "obj_data", "=", "None", ",", "*", "fields", ",", "*", "*", "field_map", ")", ":", "obj_dict", "=", "obj_data", ".", "__dict__", "if", "hasattr", "(", "obj_data", ",", "'__dict__'", ")", "else", "obj_data", "if", "not"...
prioritize obj_dict when there are conficts
[ "prioritize", "obj_dict", "when", "there", "are", "conficts" ]
f6dcc5e353354aab6cb24701910ee2ee5368c9cd
https://github.com/letuananh/puchikarui/blob/f6dcc5e353354aab6cb24701910ee2ee5368c9cd/puchikarui/puchikarui.py#L62-L69
train
58,550
letuananh/puchikarui
puchikarui/puchikarui.py
with_ctx
def with_ctx(func=None): ''' Auto create a new context if not available ''' if not func: return functools.partial(with_ctx) @functools.wraps(func) def func_with_context(_obj, *args, **kwargs): if 'ctx' not in kwargs or kwargs['ctx'] is None: # if context is empty, ensure con...
python
def with_ctx(func=None): ''' Auto create a new context if not available ''' if not func: return functools.partial(with_ctx) @functools.wraps(func) def func_with_context(_obj, *args, **kwargs): if 'ctx' not in kwargs or kwargs['ctx'] is None: # if context is empty, ensure con...
[ "def", "with_ctx", "(", "func", "=", "None", ")", ":", "if", "not", "func", ":", "return", "functools", ".", "partial", "(", "with_ctx", ")", "@", "functools", ".", "wraps", "(", "func", ")", "def", "func_with_context", "(", "_obj", ",", "*", "args", ...
Auto create a new context if not available
[ "Auto", "create", "a", "new", "context", "if", "not", "available" ]
f6dcc5e353354aab6cb24701910ee2ee5368c9cd
https://github.com/letuananh/puchikarui/blob/f6dcc5e353354aab6cb24701910ee2ee5368c9cd/puchikarui/puchikarui.py#L581-L597
train
58,551
letuananh/puchikarui
puchikarui/puchikarui.py
DataSource.open
def open(self, auto_commit=None, schema=None): ''' Create a context to execute queries ''' if schema is None: schema = self.schema ac = auto_commit if auto_commit is not None else schema.auto_commit exe = ExecutionContext(self.path, schema=schema, auto_commit=ac) # se...
python
def open(self, auto_commit=None, schema=None): ''' Create a context to execute queries ''' if schema is None: schema = self.schema ac = auto_commit if auto_commit is not None else schema.auto_commit exe = ExecutionContext(self.path, schema=schema, auto_commit=ac) # se...
[ "def", "open", "(", "self", ",", "auto_commit", "=", "None", ",", "schema", "=", "None", ")", ":", "if", "schema", "is", "None", ":", "schema", "=", "self", ".", "schema", "ac", "=", "auto_commit", "if", "auto_commit", "is", "not", "None", "else", "s...
Create a context to execute queries
[ "Create", "a", "context", "to", "execute", "queries" ]
f6dcc5e353354aab6cb24701910ee2ee5368c9cd
https://github.com/letuananh/puchikarui/blob/f6dcc5e353354aab6cb24701910ee2ee5368c9cd/puchikarui/puchikarui.py#L254-L272
train
58,552
letuananh/puchikarui
puchikarui/puchikarui.py
QueryBuilder.build_insert
def build_insert(self, table, values, columns=None): ''' Insert an active record into DB and return lastrowid if available ''' if not columns: columns = table.columns if len(values) < len(columns): column_names = ','.join(columns[-len(values):]) else: ...
python
def build_insert(self, table, values, columns=None): ''' Insert an active record into DB and return lastrowid if available ''' if not columns: columns = table.columns if len(values) < len(columns): column_names = ','.join(columns[-len(values):]) else: ...
[ "def", "build_insert", "(", "self", ",", "table", ",", "values", ",", "columns", "=", "None", ")", ":", "if", "not", "columns", ":", "columns", "=", "table", ".", "columns", "if", "len", "(", "values", ")", "<", "len", "(", "columns", ")", ":", "co...
Insert an active record into DB and return lastrowid if available
[ "Insert", "an", "active", "record", "into", "DB", "and", "return", "lastrowid", "if", "available" ]
f6dcc5e353354aab6cb24701910ee2ee5368c9cd
https://github.com/letuananh/puchikarui/blob/f6dcc5e353354aab6cb24701910ee2ee5368c9cd/puchikarui/puchikarui.py#L325-L334
train
58,553
letuananh/puchikarui
puchikarui/puchikarui.py
ExecutionContext.select_record
def select_record(self, table, where=None, values=None, orderby=None, limit=None, columns=None): ''' Support these keywords where, values, orderby, limit and columns''' query = self.schema.query_builder.build_select(table, where, orderby, limit, columns) return table.to_table(self.execute(query,...
python
def select_record(self, table, where=None, values=None, orderby=None, limit=None, columns=None): ''' Support these keywords where, values, orderby, limit and columns''' query = self.schema.query_builder.build_select(table, where, orderby, limit, columns) return table.to_table(self.execute(query,...
[ "def", "select_record", "(", "self", ",", "table", ",", "where", "=", "None", ",", "values", "=", "None", ",", "orderby", "=", "None", ",", "limit", "=", "None", ",", "columns", "=", "None", ")", ":", "query", "=", "self", ".", "schema", ".", "quer...
Support these keywords where, values, orderby, limit and columns
[ "Support", "these", "keywords", "where", "values", "orderby", "limit", "and", "columns" ]
f6dcc5e353354aab6cb24701910ee2ee5368c9cd
https://github.com/letuananh/puchikarui/blob/f6dcc5e353354aab6cb24701910ee2ee5368c9cd/puchikarui/puchikarui.py#L422-L425
train
58,554
israel-lugo/capidup
capidup/finddups.py
should_be_excluded
def should_be_excluded(name, exclude_patterns): """Check if a name should be excluded. Returns True if name matches at least one of the exclude patterns in the exclude_patterns list. """ for pattern in exclude_patterns: if fnmatch.fnmatch(name, pattern): return True return ...
python
def should_be_excluded(name, exclude_patterns): """Check if a name should be excluded. Returns True if name matches at least one of the exclude patterns in the exclude_patterns list. """ for pattern in exclude_patterns: if fnmatch.fnmatch(name, pattern): return True return ...
[ "def", "should_be_excluded", "(", "name", ",", "exclude_patterns", ")", ":", "for", "pattern", "in", "exclude_patterns", ":", "if", "fnmatch", ".", "fnmatch", "(", "name", ",", "pattern", ")", ":", "return", "True", "return", "False" ]
Check if a name should be excluded. Returns True if name matches at least one of the exclude patterns in the exclude_patterns list.
[ "Check", "if", "a", "name", "should", "be", "excluded", "." ]
7524d04f6c7ca1e32b695e62d9894db2dc0e8705
https://github.com/israel-lugo/capidup/blob/7524d04f6c7ca1e32b695e62d9894db2dc0e8705/capidup/finddups.py#L85-L95
train
58,555
israel-lugo/capidup
capidup/finddups.py
filter_visited
def filter_visited(curr_dir, subdirs, already_visited, follow_dirlinks, on_error): """Filter subdirs that have already been visited. This is used to avoid loops in the search performed by os.walk() in index_files_by_size. curr_dir is the path of the current directory, as returned by os.walk(). su...
python
def filter_visited(curr_dir, subdirs, already_visited, follow_dirlinks, on_error): """Filter subdirs that have already been visited. This is used to avoid loops in the search performed by os.walk() in index_files_by_size. curr_dir is the path of the current directory, as returned by os.walk(). su...
[ "def", "filter_visited", "(", "curr_dir", ",", "subdirs", ",", "already_visited", ",", "follow_dirlinks", ",", "on_error", ")", ":", "filtered", "=", "[", "]", "to_visit", "=", "set", "(", ")", "_already_visited", "=", "already_visited", ".", "copy", "(", ")...
Filter subdirs that have already been visited. This is used to avoid loops in the search performed by os.walk() in index_files_by_size. curr_dir is the path of the current directory, as returned by os.walk(). subdirs is the list of subdirectories for the current directory, as returned by os.walk(...
[ "Filter", "subdirs", "that", "have", "already", "been", "visited", "." ]
7524d04f6c7ca1e32b695e62d9894db2dc0e8705
https://github.com/israel-lugo/capidup/blob/7524d04f6c7ca1e32b695e62d9894db2dc0e8705/capidup/finddups.py#L113-L165
train
58,556
israel-lugo/capidup
capidup/finddups.py
index_files_by_size
def index_files_by_size(root, files_by_size, exclude_dirs, exclude_files, follow_dirlinks): """Recursively index files under a root directory. Each regular file is added *in-place* to the files_by_size dictionary, according to the file size. This is a (possibly empty) dictionary of lists of fil...
python
def index_files_by_size(root, files_by_size, exclude_dirs, exclude_files, follow_dirlinks): """Recursively index files under a root directory. Each regular file is added *in-place* to the files_by_size dictionary, according to the file size. This is a (possibly empty) dictionary of lists of fil...
[ "def", "index_files_by_size", "(", "root", ",", "files_by_size", ",", "exclude_dirs", ",", "exclude_files", ",", "follow_dirlinks", ")", ":", "# encapsulate the value in a list, so we can modify it by reference", "# inside the auxiliary function", "errors", "=", "[", "]", "al...
Recursively index files under a root directory. Each regular file is added *in-place* to the files_by_size dictionary, according to the file size. This is a (possibly empty) dictionary of lists of filenames, indexed by file size. exclude_dirs is a list of glob patterns to exclude directories. excl...
[ "Recursively", "index", "files", "under", "a", "root", "directory", "." ]
7524d04f6c7ca1e32b695e62d9894db2dc0e8705
https://github.com/israel-lugo/capidup/blob/7524d04f6c7ca1e32b695e62d9894db2dc0e8705/capidup/finddups.py#L168-L245
train
58,557
israel-lugo/capidup
capidup/finddups.py
calculate_md5
def calculate_md5(filename, length): """Calculate the MD5 hash of a file, up to length bytes. Returns the MD5 in its binary form, as an 8-byte string. Raises IOError or OSError in case of error. """ assert length >= 0 # shortcut: MD5 of an empty string is 'd41d8cd98f00b204e9800998ecf8427e', ...
python
def calculate_md5(filename, length): """Calculate the MD5 hash of a file, up to length bytes. Returns the MD5 in its binary form, as an 8-byte string. Raises IOError or OSError in case of error. """ assert length >= 0 # shortcut: MD5 of an empty string is 'd41d8cd98f00b204e9800998ecf8427e', ...
[ "def", "calculate_md5", "(", "filename", ",", "length", ")", ":", "assert", "length", ">=", "0", "# shortcut: MD5 of an empty string is 'd41d8cd98f00b204e9800998ecf8427e',", "# represented here in binary", "if", "length", "==", "0", ":", "return", "'\\xd4\\x1d\\x8c\\xd9\\x8f\...
Calculate the MD5 hash of a file, up to length bytes. Returns the MD5 in its binary form, as an 8-byte string. Raises IOError or OSError in case of error.
[ "Calculate", "the", "MD5", "hash", "of", "a", "file", "up", "to", "length", "bytes", "." ]
7524d04f6c7ca1e32b695e62d9894db2dc0e8705
https://github.com/israel-lugo/capidup/blob/7524d04f6c7ca1e32b695e62d9894db2dc0e8705/capidup/finddups.py#L249-L289
train
58,558
israel-lugo/capidup
capidup/finddups.py
find_duplicates
def find_duplicates(filenames, max_size): """Find duplicates in a list of files, comparing up to `max_size` bytes. Returns a 2-tuple of two values: ``(duplicate_groups, errors)``. `duplicate_groups` is a (possibly empty) list of lists: the names of files that have at least two copies, grouped together...
python
def find_duplicates(filenames, max_size): """Find duplicates in a list of files, comparing up to `max_size` bytes. Returns a 2-tuple of two values: ``(duplicate_groups, errors)``. `duplicate_groups` is a (possibly empty) list of lists: the names of files that have at least two copies, grouped together...
[ "def", "find_duplicates", "(", "filenames", ",", "max_size", ")", ":", "errors", "=", "[", "]", "# shortcut: can't have duplicates if there aren't at least 2 files", "if", "len", "(", "filenames", ")", "<", "2", ":", "return", "[", "]", ",", "errors", "# shortcut:...
Find duplicates in a list of files, comparing up to `max_size` bytes. Returns a 2-tuple of two values: ``(duplicate_groups, errors)``. `duplicate_groups` is a (possibly empty) list of lists: the names of files that have at least two copies, grouped together. `errors` is a list of error messages that ...
[ "Find", "duplicates", "in", "a", "list", "of", "files", "comparing", "up", "to", "max_size", "bytes", "." ]
7524d04f6c7ca1e32b695e62d9894db2dc0e8705
https://github.com/israel-lugo/capidup/blob/7524d04f6c7ca1e32b695e62d9894db2dc0e8705/capidup/finddups.py#L293-L350
train
58,559
israel-lugo/capidup
capidup/finddups.py
find_duplicates_in_dirs
def find_duplicates_in_dirs(directories, exclude_dirs=None, exclude_files=None, follow_dirlinks=False): """Recursively scan a list of directories, looking for duplicate files. `exclude_dirs`, if provided, should be a list of glob patterns. Subdirectories whose names match these patterns are exclude...
python
def find_duplicates_in_dirs(directories, exclude_dirs=None, exclude_files=None, follow_dirlinks=False): """Recursively scan a list of directories, looking for duplicate files. `exclude_dirs`, if provided, should be a list of glob patterns. Subdirectories whose names match these patterns are exclude...
[ "def", "find_duplicates_in_dirs", "(", "directories", ",", "exclude_dirs", "=", "None", ",", "exclude_files", "=", "None", ",", "follow_dirlinks", "=", "False", ")", ":", "if", "exclude_dirs", "is", "None", ":", "exclude_dirs", "=", "[", "]", "if", "exclude_fi...
Recursively scan a list of directories, looking for duplicate files. `exclude_dirs`, if provided, should be a list of glob patterns. Subdirectories whose names match these patterns are excluded from the scan. `exclude_files`, if provided, should be a list of glob patterns. Files whose names match ...
[ "Recursively", "scan", "a", "list", "of", "directories", "looking", "for", "duplicate", "files", "." ]
7524d04f6c7ca1e32b695e62d9894db2dc0e8705
https://github.com/israel-lugo/capidup/blob/7524d04f6c7ca1e32b695e62d9894db2dc0e8705/capidup/finddups.py#L355-L438
train
58,560
timothydmorton/orbitutils
orbitutils/utils.py
semimajor
def semimajor(P,M): """P, M can be ``Quantity`` objects; otherwise default to day, M_sun """ if type(P) != Quantity: P = P*u.day if type(M) != Quantity: M = M*u.M_sun a = ((P/2/np.pi)**2*const.G*M)**(1./3) return a.to(u.AU)
python
def semimajor(P,M): """P, M can be ``Quantity`` objects; otherwise default to day, M_sun """ if type(P) != Quantity: P = P*u.day if type(M) != Quantity: M = M*u.M_sun a = ((P/2/np.pi)**2*const.G*M)**(1./3) return a.to(u.AU)
[ "def", "semimajor", "(", "P", ",", "M", ")", ":", "if", "type", "(", "P", ")", "!=", "Quantity", ":", "P", "=", "P", "*", "u", ".", "day", "if", "type", "(", "M", ")", "!=", "Quantity", ":", "M", "=", "M", "*", "u", ".", "M_sun", "a", "="...
P, M can be ``Quantity`` objects; otherwise default to day, M_sun
[ "P", "M", "can", "be", "Quantity", "objects", ";", "otherwise", "default", "to", "day", "M_sun" ]
949c6b901e519458d80b8d7427916c0698e4013e
https://github.com/timothydmorton/orbitutils/blob/949c6b901e519458d80b8d7427916c0698e4013e/orbitutils/utils.py#L15-L23
train
58,561
timothydmorton/orbitutils
orbitutils/utils.py
random_spherepos
def random_spherepos(n): """returns SkyCoord object with n positions randomly oriented on the unit sphere Parameters ---------- n : int number of positions desired Returns ------- c : ``SkyCoord`` object with random positions """ signs = np.sign(rand.uniform(-1,1,size=n)) ...
python
def random_spherepos(n): """returns SkyCoord object with n positions randomly oriented on the unit sphere Parameters ---------- n : int number of positions desired Returns ------- c : ``SkyCoord`` object with random positions """ signs = np.sign(rand.uniform(-1,1,size=n)) ...
[ "def", "random_spherepos", "(", "n", ")", ":", "signs", "=", "np", ".", "sign", "(", "rand", ".", "uniform", "(", "-", "1", ",", "1", ",", "size", "=", "n", ")", ")", "thetas", "=", "Angle", "(", "np", ".", "arccos", "(", "rand", ".", "uniform"...
returns SkyCoord object with n positions randomly oriented on the unit sphere Parameters ---------- n : int number of positions desired Returns ------- c : ``SkyCoord`` object with random positions
[ "returns", "SkyCoord", "object", "with", "n", "positions", "randomly", "oriented", "on", "the", "unit", "sphere" ]
949c6b901e519458d80b8d7427916c0698e4013e
https://github.com/timothydmorton/orbitutils/blob/949c6b901e519458d80b8d7427916c0698e4013e/orbitutils/utils.py#L25-L41
train
58,562
sherlocke/pywatson
pywatson/util/dictable.py
Dictable.to_dict
def to_dict(self): """ Return a dict of all instance variables with truthy values, with key names camelized """ return { inflection.camelize(k, False): v for k, v in self.__dict__.items() if v }
python
def to_dict(self): """ Return a dict of all instance variables with truthy values, with key names camelized """ return { inflection.camelize(k, False): v for k, v in self.__dict__.items() if v }
[ "def", "to_dict", "(", "self", ")", ":", "return", "{", "inflection", ".", "camelize", "(", "k", ",", "False", ")", ":", "v", "for", "k", ",", "v", "in", "self", ".", "__dict__", ".", "items", "(", ")", "if", "v", "}" ]
Return a dict of all instance variables with truthy values, with key names camelized
[ "Return", "a", "dict", "of", "all", "instance", "variables", "with", "truthy", "values", "with", "key", "names", "camelized" ]
ab15d1ca3c01a185136b420d443f712dfa865485
https://github.com/sherlocke/pywatson/blob/ab15d1ca3c01a185136b420d443f712dfa865485/pywatson/util/dictable.py#L7-L16
train
58,563
hyde/fswrap
fswrap.py
FS.depth
def depth(self): """ Returns the number of ancestors of this directory. """ return len(self.path.rstrip(os.sep).split(os.sep))
python
def depth(self): """ Returns the number of ancestors of this directory. """ return len(self.path.rstrip(os.sep).split(os.sep))
[ "def", "depth", "(", "self", ")", ":", "return", "len", "(", "self", ".", "path", ".", "rstrip", "(", "os", ".", "sep", ")", ".", "split", "(", "os", ".", "sep", ")", ")" ]
Returns the number of ancestors of this directory.
[ "Returns", "the", "number", "of", "ancestors", "of", "this", "directory", "." ]
41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2
https://github.com/hyde/fswrap/blob/41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2/fswrap.py#L101-L105
train
58,564
hyde/fswrap
fswrap.py
FS.ancestors
def ancestors(self, stop=None): """ Generates the parents until stop or the absolute root directory is reached. """ folder = self while folder.parent != stop: if folder.parent == folder: return yield folder.parent folder...
python
def ancestors(self, stop=None): """ Generates the parents until stop or the absolute root directory is reached. """ folder = self while folder.parent != stop: if folder.parent == folder: return yield folder.parent folder...
[ "def", "ancestors", "(", "self", ",", "stop", "=", "None", ")", ":", "folder", "=", "self", "while", "folder", ".", "parent", "!=", "stop", ":", "if", "folder", ".", "parent", "==", "folder", ":", "return", "yield", "folder", ".", "parent", "folder", ...
Generates the parents until stop or the absolute root directory is reached.
[ "Generates", "the", "parents", "until", "stop", "or", "the", "absolute", "root", "directory", "is", "reached", "." ]
41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2
https://github.com/hyde/fswrap/blob/41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2/fswrap.py#L107-L117
train
58,565
hyde/fswrap
fswrap.py
FS.is_descendant_of
def is_descendant_of(self, ancestor): """ Checks if this folder is inside the given ancestor. """ stop = Folder(ancestor) for folder in self.ancestors(): if folder == stop: return True if stop.depth > folder.depth: return Fa...
python
def is_descendant_of(self, ancestor): """ Checks if this folder is inside the given ancestor. """ stop = Folder(ancestor) for folder in self.ancestors(): if folder == stop: return True if stop.depth > folder.depth: return Fa...
[ "def", "is_descendant_of", "(", "self", ",", "ancestor", ")", ":", "stop", "=", "Folder", "(", "ancestor", ")", "for", "folder", "in", "self", ".", "ancestors", "(", ")", ":", "if", "folder", "==", "stop", ":", "return", "True", "if", "stop", ".", "d...
Checks if this folder is inside the given ancestor.
[ "Checks", "if", "this", "folder", "is", "inside", "the", "given", "ancestor", "." ]
41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2
https://github.com/hyde/fswrap/blob/41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2/fswrap.py#L119-L129
train
58,566
hyde/fswrap
fswrap.py
FS.get_relative_path
def get_relative_path(self, root): """ Gets the fragment of the current path starting at root. """ if self.path == root: return '' ancestors = self.ancestors(stop=root) return functools.reduce(lambda f, p: Folder(p.name).child(f), ...
python
def get_relative_path(self, root): """ Gets the fragment of the current path starting at root. """ if self.path == root: return '' ancestors = self.ancestors(stop=root) return functools.reduce(lambda f, p: Folder(p.name).child(f), ...
[ "def", "get_relative_path", "(", "self", ",", "root", ")", ":", "if", "self", ".", "path", "==", "root", ":", "return", "''", "ancestors", "=", "self", ".", "ancestors", "(", "stop", "=", "root", ")", "return", "functools", ".", "reduce", "(", "lambda"...
Gets the fragment of the current path starting at root.
[ "Gets", "the", "fragment", "of", "the", "current", "path", "starting", "at", "root", "." ]
41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2
https://github.com/hyde/fswrap/blob/41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2/fswrap.py#L131-L140
train
58,567
hyde/fswrap
fswrap.py
FS.get_mirror
def get_mirror(self, target_root, source_root=None): """ Returns a File or Folder object that reperesents if the entire fragment of this directory starting with `source_root` were copied to `target_root`. >>> Folder('/usr/local/hyde/stuff').get_mirror('/usr/tmp', ...
python
def get_mirror(self, target_root, source_root=None): """ Returns a File or Folder object that reperesents if the entire fragment of this directory starting with `source_root` were copied to `target_root`. >>> Folder('/usr/local/hyde/stuff').get_mirror('/usr/tmp', ...
[ "def", "get_mirror", "(", "self", ",", "target_root", ",", "source_root", "=", "None", ")", ":", "fragment", "=", "self", ".", "get_relative_path", "(", "source_root", "if", "source_root", "else", "self", ".", "parent", ")", "return", "Folder", "(", "target_...
Returns a File or Folder object that reperesents if the entire fragment of this directory starting with `source_root` were copied to `target_root`. >>> Folder('/usr/local/hyde/stuff').get_mirror('/usr/tmp', source_root='/usr/local/hyde') F...
[ "Returns", "a", "File", "or", "Folder", "object", "that", "reperesents", "if", "the", "entire", "fragment", "of", "this", "directory", "starting", "with", "source_root", "were", "copied", "to", "target_root", "." ]
41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2
https://github.com/hyde/fswrap/blob/41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2/fswrap.py#L142-L154
train
58,568
hyde/fswrap
fswrap.py
FS.file_or_folder
def file_or_folder(path): """ Returns a File or Folder object that would represent the given path. """ target = unicode(path) return Folder(target) if os.path.isdir(target) else File(target)
python
def file_or_folder(path): """ Returns a File or Folder object that would represent the given path. """ target = unicode(path) return Folder(target) if os.path.isdir(target) else File(target)
[ "def", "file_or_folder", "(", "path", ")", ":", "target", "=", "unicode", "(", "path", ")", "return", "Folder", "(", "target", ")", "if", "os", ".", "path", ".", "isdir", "(", "target", ")", "else", "File", "(", "target", ")" ]
Returns a File or Folder object that would represent the given path.
[ "Returns", "a", "File", "or", "Folder", "object", "that", "would", "represent", "the", "given", "path", "." ]
41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2
https://github.com/hyde/fswrap/blob/41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2/fswrap.py#L157-L162
train
58,569
hyde/fswrap
fswrap.py
File.is_binary
def is_binary(self): """Return true if this is a binary file.""" with open(self.path, 'rb') as fin: CHUNKSIZE = 1024 while 1: chunk = fin.read(CHUNKSIZE) if b'\0' in chunk: return True if len(chunk) < CHUNKSIZE: ...
python
def is_binary(self): """Return true if this is a binary file.""" with open(self.path, 'rb') as fin: CHUNKSIZE = 1024 while 1: chunk = fin.read(CHUNKSIZE) if b'\0' in chunk: return True if len(chunk) < CHUNKSIZE: ...
[ "def", "is_binary", "(", "self", ")", ":", "with", "open", "(", "self", ".", "path", ",", "'rb'", ")", "as", "fin", ":", "CHUNKSIZE", "=", "1024", "while", "1", ":", "chunk", "=", "fin", ".", "read", "(", "CHUNKSIZE", ")", "if", "b'\\0'", "in", "...
Return true if this is a binary file.
[ "Return", "true", "if", "this", "is", "a", "binary", "file", "." ]
41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2
https://github.com/hyde/fswrap/blob/41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2/fswrap.py#L224-L234
train
58,570
hyde/fswrap
fswrap.py
File.make_temp
def make_temp(text): """ Creates a temprorary file and writes the `text` into it """ import tempfile (handle, path) = tempfile.mkstemp(text=True) os.close(handle) afile = File(path) afile.write(text) return afile
python
def make_temp(text): """ Creates a temprorary file and writes the `text` into it """ import tempfile (handle, path) = tempfile.mkstemp(text=True) os.close(handle) afile = File(path) afile.write(text) return afile
[ "def", "make_temp", "(", "text", ")", ":", "import", "tempfile", "(", "handle", ",", "path", ")", "=", "tempfile", ".", "mkstemp", "(", "text", "=", "True", ")", "os", ".", "close", "(", "handle", ")", "afile", "=", "File", "(", "path", ")", "afile...
Creates a temprorary file and writes the `text` into it
[ "Creates", "a", "temprorary", "file", "and", "writes", "the", "text", "into", "it" ]
41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2
https://github.com/hyde/fswrap/blob/41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2/fswrap.py#L271-L280
train
58,571
hyde/fswrap
fswrap.py
File.read_all
def read_all(self, encoding='utf-8'): """ Reads from the file and returns the content as a string. """ logger.info("Reading everything from %s" % self) with codecs.open(self.path, 'r', encoding) as fin: read_text = fin.read() return read_text
python
def read_all(self, encoding='utf-8'): """ Reads from the file and returns the content as a string. """ logger.info("Reading everything from %s" % self) with codecs.open(self.path, 'r', encoding) as fin: read_text = fin.read() return read_text
[ "def", "read_all", "(", "self", ",", "encoding", "=", "'utf-8'", ")", ":", "logger", ".", "info", "(", "\"Reading everything from %s\"", "%", "self", ")", "with", "codecs", ".", "open", "(", "self", ".", "path", ",", "'r'", ",", "encoding", ")", "as", ...
Reads from the file and returns the content as a string.
[ "Reads", "from", "the", "file", "and", "returns", "the", "content", "as", "a", "string", "." ]
41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2
https://github.com/hyde/fswrap/blob/41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2/fswrap.py#L282-L289
train
58,572
hyde/fswrap
fswrap.py
File.write
def write(self, text, encoding="utf-8"): """ Writes the given text to the file using the given encoding. """ logger.info("Writing to %s" % self) with codecs.open(self.path, 'w', encoding) as fout: fout.write(text)
python
def write(self, text, encoding="utf-8"): """ Writes the given text to the file using the given encoding. """ logger.info("Writing to %s" % self) with codecs.open(self.path, 'w', encoding) as fout: fout.write(text)
[ "def", "write", "(", "self", ",", "text", ",", "encoding", "=", "\"utf-8\"", ")", ":", "logger", ".", "info", "(", "\"Writing to %s\"", "%", "self", ")", "with", "codecs", ".", "open", "(", "self", ".", "path", ",", "'w'", ",", "encoding", ")", "as",...
Writes the given text to the file using the given encoding.
[ "Writes", "the", "given", "text", "to", "the", "file", "using", "the", "given", "encoding", "." ]
41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2
https://github.com/hyde/fswrap/blob/41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2/fswrap.py#L291-L297
train
58,573
hyde/fswrap
fswrap.py
File.copy_to
def copy_to(self, destination): """ Copies the file to the given destination. Returns a File object that represents the target file. `destination` must be a File or Folder object. """ target = self.__get_destination__(destination) logger.info("Copying %s to %s" % ...
python
def copy_to(self, destination): """ Copies the file to the given destination. Returns a File object that represents the target file. `destination` must be a File or Folder object. """ target = self.__get_destination__(destination) logger.info("Copying %s to %s" % ...
[ "def", "copy_to", "(", "self", ",", "destination", ")", ":", "target", "=", "self", ".", "__get_destination__", "(", "destination", ")", "logger", ".", "info", "(", "\"Copying %s to %s\"", "%", "(", "self", ",", "target", ")", ")", "shutil", ".", "copy", ...
Copies the file to the given destination. Returns a File object that represents the target file. `destination` must be a File or Folder object.
[ "Copies", "the", "file", "to", "the", "given", "destination", ".", "Returns", "a", "File", "object", "that", "represents", "the", "target", "file", ".", "destination", "must", "be", "a", "File", "or", "Folder", "object", "." ]
41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2
https://github.com/hyde/fswrap/blob/41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2/fswrap.py#L299-L308
train
58,574
hyde/fswrap
fswrap.py
File.etag
def etag(self): """ Generates etag from file contents. """ CHUNKSIZE = 1024 * 64 from hashlib import md5 hash = md5() with open(self.path) as fin: chunk = fin.read(CHUNKSIZE) while chunk: hash_update(hash, chunk) ...
python
def etag(self): """ Generates etag from file contents. """ CHUNKSIZE = 1024 * 64 from hashlib import md5 hash = md5() with open(self.path) as fin: chunk = fin.read(CHUNKSIZE) while chunk: hash_update(hash, chunk) ...
[ "def", "etag", "(", "self", ")", ":", "CHUNKSIZE", "=", "1024", "*", "64", "from", "hashlib", "import", "md5", "hash", "=", "md5", "(", ")", "with", "open", "(", "self", ".", "path", ")", "as", "fin", ":", "chunk", "=", "fin", ".", "read", "(", ...
Generates etag from file contents.
[ "Generates", "etag", "from", "file", "contents", "." ]
41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2
https://github.com/hyde/fswrap/blob/41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2/fswrap.py#L318-L330
train
58,575
hyde/fswrap
fswrap.py
Folder.child_folder
def child_folder(self, fragment): """ Returns a folder object by combining the fragment to this folder's path """ return Folder(os.path.join(self.path, Folder(fragment).path))
python
def child_folder(self, fragment): """ Returns a folder object by combining the fragment to this folder's path """ return Folder(os.path.join(self.path, Folder(fragment).path))
[ "def", "child_folder", "(", "self", ",", "fragment", ")", ":", "return", "Folder", "(", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "Folder", "(", "fragment", ")", ".", "path", ")", ")" ]
Returns a folder object by combining the fragment to this folder's path
[ "Returns", "a", "folder", "object", "by", "combining", "the", "fragment", "to", "this", "folder", "s", "path" ]
41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2
https://github.com/hyde/fswrap/blob/41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2/fswrap.py#L531-L535
train
58,576
hyde/fswrap
fswrap.py
Folder.child
def child(self, fragment): """ Returns a path of a child item represented by `fragment`. """ return os.path.join(self.path, FS(fragment).path)
python
def child(self, fragment): """ Returns a path of a child item represented by `fragment`. """ return os.path.join(self.path, FS(fragment).path)
[ "def", "child", "(", "self", ",", "fragment", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "FS", "(", "fragment", ")", ".", "path", ")" ]
Returns a path of a child item represented by `fragment`.
[ "Returns", "a", "path", "of", "a", "child", "item", "represented", "by", "fragment", "." ]
41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2
https://github.com/hyde/fswrap/blob/41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2/fswrap.py#L543-L547
train
58,577
hyde/fswrap
fswrap.py
Folder.make
def make(self): """ Creates this directory and any of the missing directories in the path. Any errors that may occur are eaten. """ try: if not self.exists: logger.info("Creating %s" % self.path) os.makedirs(self.path) except os...
python
def make(self): """ Creates this directory and any of the missing directories in the path. Any errors that may occur are eaten. """ try: if not self.exists: logger.info("Creating %s" % self.path) os.makedirs(self.path) except os...
[ "def", "make", "(", "self", ")", ":", "try", ":", "if", "not", "self", ".", "exists", ":", "logger", ".", "info", "(", "\"Creating %s\"", "%", "self", ".", "path", ")", "os", ".", "makedirs", "(", "self", ".", "path", ")", "except", "os", ".", "e...
Creates this directory and any of the missing directories in the path. Any errors that may occur are eaten.
[ "Creates", "this", "directory", "and", "any", "of", "the", "missing", "directories", "in", "the", "path", ".", "Any", "errors", "that", "may", "occur", "are", "eaten", "." ]
41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2
https://github.com/hyde/fswrap/blob/41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2/fswrap.py#L549-L560
train
58,578
hyde/fswrap
fswrap.py
Folder.delete
def delete(self): """ Deletes the directory if it exists. """ if self.exists: logger.info("Deleting %s" % self.path) shutil.rmtree(self.path)
python
def delete(self): """ Deletes the directory if it exists. """ if self.exists: logger.info("Deleting %s" % self.path) shutil.rmtree(self.path)
[ "def", "delete", "(", "self", ")", ":", "if", "self", ".", "exists", ":", "logger", ".", "info", "(", "\"Deleting %s\"", "%", "self", ".", "path", ")", "shutil", ".", "rmtree", "(", "self", ".", "path", ")" ]
Deletes the directory if it exists.
[ "Deletes", "the", "directory", "if", "it", "exists", "." ]
41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2
https://github.com/hyde/fswrap/blob/41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2/fswrap.py#L578-L584
train
58,579
hyde/fswrap
fswrap.py
Folder._create_target_tree
def _create_target_tree(self, target): """ There is a bug in dir_util that makes `copy_tree` crash if a folder in the tree has been deleted before and readded now. To workaround the bug, we first walk the tree and create directories that are needed. """ source = self ...
python
def _create_target_tree(self, target): """ There is a bug in dir_util that makes `copy_tree` crash if a folder in the tree has been deleted before and readded now. To workaround the bug, we first walk the tree and create directories that are needed. """ source = self ...
[ "def", "_create_target_tree", "(", "self", ",", "target", ")", ":", "source", "=", "self", "with", "source", ".", "walker", "as", "walker", ":", "@", "walker", ".", "folder_visitor", "def", "visit_folder", "(", "folder", ")", ":", "\"\"\"\n Crea...
There is a bug in dir_util that makes `copy_tree` crash if a folder in the tree has been deleted before and readded now. To workaround the bug, we first walk the tree and create directories that are needed.
[ "There", "is", "a", "bug", "in", "dir_util", "that", "makes", "copy_tree", "crash", "if", "a", "folder", "in", "the", "tree", "has", "been", "deleted", "before", "and", "readded", "now", ".", "To", "workaround", "the", "bug", "we", "first", "walk", "the"...
41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2
https://github.com/hyde/fswrap/blob/41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2/fswrap.py#L616-L631
train
58,580
hyde/fswrap
fswrap.py
Folder.copy_contents_to
def copy_contents_to(self, destination): """ Copies the contents of this directory to the given destination. Returns a Folder object that represents the moved directory. """ logger.info("Copying contents of %s to %s" % (self, destination)) target = Folder(destination) ...
python
def copy_contents_to(self, destination): """ Copies the contents of this directory to the given destination. Returns a Folder object that represents the moved directory. """ logger.info("Copying contents of %s to %s" % (self, destination)) target = Folder(destination) ...
[ "def", "copy_contents_to", "(", "self", ",", "destination", ")", ":", "logger", ".", "info", "(", "\"Copying contents of %s to %s\"", "%", "(", "self", ",", "destination", ")", ")", "target", "=", "Folder", "(", "destination", ")", "target", ".", "make", "("...
Copies the contents of this directory to the given destination. Returns a Folder object that represents the moved directory.
[ "Copies", "the", "contents", "of", "this", "directory", "to", "the", "given", "destination", ".", "Returns", "a", "Folder", "object", "that", "represents", "the", "moved", "directory", "." ]
41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2
https://github.com/hyde/fswrap/blob/41e4ad6f7e9ba73eabe61bd97847cd284e3edbd2/fswrap.py#L633-L643
train
58,581
AtomHash/evernode
evernode/classes/cron.py
Cron.__start
def __start(self): """ Start a new thread to process Cron """ thread = Thread(target=self.__loop, args=()) thread.daemon = True # daemonize thread thread.start() self.__enabled = True
python
def __start(self): """ Start a new thread to process Cron """ thread = Thread(target=self.__loop, args=()) thread.daemon = True # daemonize thread thread.start() self.__enabled = True
[ "def", "__start", "(", "self", ")", ":", "thread", "=", "Thread", "(", "target", "=", "self", ".", "__loop", ",", "args", "=", "(", ")", ")", "thread", ".", "daemon", "=", "True", "# daemonize thread", "thread", ".", "start", "(", ")", "self", ".", ...
Start a new thread to process Cron
[ "Start", "a", "new", "thread", "to", "process", "Cron" ]
b2fb91555fb937a3f3eba41db56dee26f9b034be
https://github.com/AtomHash/evernode/blob/b2fb91555fb937a3f3eba41db56dee26f9b034be/evernode/classes/cron.py#L39-L44
train
58,582
thomasw/querylist
querylist/dict.py
BetterDict.__dict_to_BetterDict
def __dict_to_BetterDict(self, attr): """Convert the passed attr to a BetterDict if the value is a dict Returns: The new value of the passed attribute.""" if type(self[attr]) == dict: self[attr] = BetterDict(self[attr]) return self[attr]
python
def __dict_to_BetterDict(self, attr): """Convert the passed attr to a BetterDict if the value is a dict Returns: The new value of the passed attribute.""" if type(self[attr]) == dict: self[attr] = BetterDict(self[attr]) return self[attr]
[ "def", "__dict_to_BetterDict", "(", "self", ",", "attr", ")", ":", "if", "type", "(", "self", "[", "attr", "]", ")", "==", "dict", ":", "self", "[", "attr", "]", "=", "BetterDict", "(", "self", "[", "attr", "]", ")", "return", "self", "[", "attr", ...
Convert the passed attr to a BetterDict if the value is a dict Returns: The new value of the passed attribute.
[ "Convert", "the", "passed", "attr", "to", "a", "BetterDict", "if", "the", "value", "is", "a", "dict" ]
4304023ef3330238ef3abccaa530ee97011fba2d
https://github.com/thomasw/querylist/blob/4304023ef3330238ef3abccaa530ee97011fba2d/querylist/dict.py#L8-L15
train
58,583
thomasw/querylist
querylist/dict.py
BetterDict._bd_
def _bd_(self): """Property that allows dot lookups of otherwise hidden attributes.""" if not getattr(self, '__bd__', False): self.__bd = BetterDictLookUp(self) return self.__bd
python
def _bd_(self): """Property that allows dot lookups of otherwise hidden attributes.""" if not getattr(self, '__bd__', False): self.__bd = BetterDictLookUp(self) return self.__bd
[ "def", "_bd_", "(", "self", ")", ":", "if", "not", "getattr", "(", "self", ",", "'__bd__'", ",", "False", ")", ":", "self", ".", "__bd", "=", "BetterDictLookUp", "(", "self", ")", "return", "self", ".", "__bd" ]
Property that allows dot lookups of otherwise hidden attributes.
[ "Property", "that", "allows", "dot", "lookups", "of", "otherwise", "hidden", "attributes", "." ]
4304023ef3330238ef3abccaa530ee97011fba2d
https://github.com/thomasw/querylist/blob/4304023ef3330238ef3abccaa530ee97011fba2d/querylist/dict.py#L27-L32
train
58,584
tBaxter/activity-monitor
activity_monitor/signals.py
create_or_update
def create_or_update(sender, **kwargs): """ Create or update an Activity Monitor item from some instance. """ now = datetime.datetime.now() # I can't explain why this import fails unless it's here. from activity_monitor.models import Activity instance = kwargs['instance'] # Find this o...
python
def create_or_update(sender, **kwargs): """ Create or update an Activity Monitor item from some instance. """ now = datetime.datetime.now() # I can't explain why this import fails unless it's here. from activity_monitor.models import Activity instance = kwargs['instance'] # Find this o...
[ "def", "create_or_update", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "now", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "# I can't explain why this import fails unless it's here.", "from", "activity_monitor", ".", "models", "import", "Activity", ...
Create or update an Activity Monitor item from some instance.
[ "Create", "or", "update", "an", "Activity", "Monitor", "item", "from", "some", "instance", "." ]
be6c6edc7c6b4141923b47376502cde0f785eb68
https://github.com/tBaxter/activity-monitor/blob/be6c6edc7c6b4141923b47376502cde0f785eb68/activity_monitor/signals.py#L7-L119
train
58,585
MisanthropicBit/colorise
examples/highlight_differences.py
highlight_differences
def highlight_differences(s1, s2, color): """Highlight the characters in s2 that differ from those in s1.""" ls1, ls2 = len(s1), len(s2) diff_indices = [i for i, (a, b) in enumerate(zip(s1, s2)) if a != b] print(s1) if ls2 > ls1: colorise.cprint('_' * (ls2-ls1), fg=color) else: ...
python
def highlight_differences(s1, s2, color): """Highlight the characters in s2 that differ from those in s1.""" ls1, ls2 = len(s1), len(s2) diff_indices = [i for i, (a, b) in enumerate(zip(s1, s2)) if a != b] print(s1) if ls2 > ls1: colorise.cprint('_' * (ls2-ls1), fg=color) else: ...
[ "def", "highlight_differences", "(", "s1", ",", "s2", ",", "color", ")", ":", "ls1", ",", "ls2", "=", "len", "(", "s1", ")", ",", "len", "(", "s2", ")", "diff_indices", "=", "[", "i", "for", "i", ",", "(", "a", ",", "b", ")", "in", "enumerate",...
Highlight the characters in s2 that differ from those in s1.
[ "Highlight", "the", "characters", "in", "s2", "that", "differ", "from", "those", "in", "s1", "." ]
e630df74b8b27680a43c370ddbe98766be50158c
https://github.com/MisanthropicBit/colorise/blob/e630df74b8b27680a43c370ddbe98766be50158c/examples/highlight_differences.py#L13-L31
train
58,586
lsst-sqre/lander
lander/renderer.py
create_jinja_env
def create_jinja_env(): """Create a Jinja2 `~jinja2.Environment`. Returns ------- env : `jinja2.Environment` Jinja2 template rendering environment, configured to use templates in ``templates/``. """ template_dir = os.path.join(os.path.dirname(__file__), 'templates') env = ji...
python
def create_jinja_env(): """Create a Jinja2 `~jinja2.Environment`. Returns ------- env : `jinja2.Environment` Jinja2 template rendering environment, configured to use templates in ``templates/``. """ template_dir = os.path.join(os.path.dirname(__file__), 'templates') env = ji...
[ "def", "create_jinja_env", "(", ")", ":", "template_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'templates'", ")", "env", "=", "jinja2", ".", "Environment", "(", "loader", "=", "jinja2"...
Create a Jinja2 `~jinja2.Environment`. Returns ------- env : `jinja2.Environment` Jinja2 template rendering environment, configured to use templates in ``templates/``.
[ "Create", "a", "Jinja2", "~jinja2", ".", "Environment", "." ]
5e4f6123e48b451ba21963724ace0dc59798618e
https://github.com/lsst-sqre/lander/blob/5e4f6123e48b451ba21963724ace0dc59798618e/lander/renderer.py#L9-L25
train
58,587
lsst-sqre/lander
lander/renderer.py
render_homepage
def render_homepage(config, env): """Render the homepage.jinja template.""" template = env.get_template('homepage.jinja') rendered_page = template.render( config=config) return rendered_page
python
def render_homepage(config, env): """Render the homepage.jinja template.""" template = env.get_template('homepage.jinja') rendered_page = template.render( config=config) return rendered_page
[ "def", "render_homepage", "(", "config", ",", "env", ")", ":", "template", "=", "env", ".", "get_template", "(", "'homepage.jinja'", ")", "rendered_page", "=", "template", ".", "render", "(", "config", "=", "config", ")", "return", "rendered_page" ]
Render the homepage.jinja template.
[ "Render", "the", "homepage", ".", "jinja", "template", "." ]
5e4f6123e48b451ba21963724ace0dc59798618e
https://github.com/lsst-sqre/lander/blob/5e4f6123e48b451ba21963724ace0dc59798618e/lander/renderer.py#L28-L33
train
58,588
brews/snakebacon
snakebacon/mcmcbackends/bacon/utils.py
d_cal
def d_cal(calibcurve, rcmean, w2, cutoff=0.0001, normal_distr=False, t_a=3, t_b=4): """Get calendar date probabilities Parameters ---------- calibcurve : CalibCurve Calibration curve. rcmean : scalar Reservoir-adjusted age. w2 : scalar r'$w^2_j(\theta)$' from pg 461 & 46...
python
def d_cal(calibcurve, rcmean, w2, cutoff=0.0001, normal_distr=False, t_a=3, t_b=4): """Get calendar date probabilities Parameters ---------- calibcurve : CalibCurve Calibration curve. rcmean : scalar Reservoir-adjusted age. w2 : scalar r'$w^2_j(\theta)$' from pg 461 & 46...
[ "def", "d_cal", "(", "calibcurve", ",", "rcmean", ",", "w2", ",", "cutoff", "=", "0.0001", ",", "normal_distr", "=", "False", ",", "t_a", "=", "3", ",", "t_b", "=", "4", ")", ":", "assert", "t_b", "-", "1", "==", "t_a", "if", "normal_distr", ":", ...
Get calendar date probabilities Parameters ---------- calibcurve : CalibCurve Calibration curve. rcmean : scalar Reservoir-adjusted age. w2 : scalar r'$w^2_j(\theta)$' from pg 461 & 463 of Blaauw and Christen 2011. cutoff : scalar, optional Unknown. normal_di...
[ "Get", "calendar", "date", "probabilities" ]
f5363d0d1225912adc30031bf2c13b54000de8f2
https://github.com/brews/snakebacon/blob/f5363d0d1225912adc30031bf2c13b54000de8f2/snakebacon/mcmcbackends/bacon/utils.py#L5-L49
train
58,589
brews/snakebacon
snakebacon/mcmcbackends/bacon/utils.py
calibrate_dates
def calibrate_dates(chron, calib_curve, d_r, d_std, cutoff=0.0001, normal_distr=False, t_a=[3], t_b=[4]): """Get density of calendar dates for chron date segment in core Parameters ---------- chron : DatedProxy-like calib_curve : CalibCurve or list of CalibCurves d_r : scalar or ndarray ...
python
def calibrate_dates(chron, calib_curve, d_r, d_std, cutoff=0.0001, normal_distr=False, t_a=[3], t_b=[4]): """Get density of calendar dates for chron date segment in core Parameters ---------- chron : DatedProxy-like calib_curve : CalibCurve or list of CalibCurves d_r : scalar or ndarray ...
[ "def", "calibrate_dates", "(", "chron", ",", "calib_curve", ",", "d_r", ",", "d_std", ",", "cutoff", "=", "0.0001", ",", "normal_distr", "=", "False", ",", "t_a", "=", "[", "3", "]", ",", "t_b", "=", "[", "4", "]", ")", ":", "# Python version of .bacon...
Get density of calendar dates for chron date segment in core Parameters ---------- chron : DatedProxy-like calib_curve : CalibCurve or list of CalibCurves d_r : scalar or ndarray Carbon reservoir offset. d_std : scalar or ndarray Carbon reservoir offset error standard deviation....
[ "Get", "density", "of", "calendar", "dates", "for", "chron", "date", "segment", "in", "core" ]
f5363d0d1225912adc30031bf2c13b54000de8f2
https://github.com/brews/snakebacon/blob/f5363d0d1225912adc30031bf2c13b54000de8f2/snakebacon/mcmcbackends/bacon/utils.py#L52-L123
train
58,590
inveniosoftware-attic/invenio-client
invenio_client/connector.py
InvenioConnector._init_browser
def _init_browser(self): """Overide in appropriate way to prepare a logged in browser.""" self.browser = splinter.Browser('phantomjs') self.browser.visit(self.server_url + "/youraccount/login") try: self.browser.fill('nickname', self.user) self.browser.fill('passw...
python
def _init_browser(self): """Overide in appropriate way to prepare a logged in browser.""" self.browser = splinter.Browser('phantomjs') self.browser.visit(self.server_url + "/youraccount/login") try: self.browser.fill('nickname', self.user) self.browser.fill('passw...
[ "def", "_init_browser", "(", "self", ")", ":", "self", ".", "browser", "=", "splinter", ".", "Browser", "(", "'phantomjs'", ")", "self", ".", "browser", ".", "visit", "(", "self", ".", "server_url", "+", "\"/youraccount/login\"", ")", "try", ":", "self", ...
Overide in appropriate way to prepare a logged in browser.
[ "Overide", "in", "appropriate", "way", "to", "prepare", "a", "logged", "in", "browser", "." ]
3f9ddb6f3b3ce3a21d399d1098d6769bf05cdd6c
https://github.com/inveniosoftware-attic/invenio-client/blob/3f9ddb6f3b3ce3a21d399d1098d6769bf05cdd6c/invenio_client/connector.py#L141-L152
train
58,591
inveniosoftware-attic/invenio-client
invenio_client/connector.py
InvenioConnector.upload_marcxml
def upload_marcxml(self, marcxml, mode): """Upload a record to the server. :param marcxml: the XML to upload. :param mode: the mode to use for the upload. - "-i" insert new records - "-r" replace existing records - "-c" correct fields of records -...
python
def upload_marcxml(self, marcxml, mode): """Upload a record to the server. :param marcxml: the XML to upload. :param mode: the mode to use for the upload. - "-i" insert new records - "-r" replace existing records - "-c" correct fields of records -...
[ "def", "upload_marcxml", "(", "self", ",", "marcxml", ",", "mode", ")", ":", "if", "mode", "not", "in", "[", "\"-i\"", ",", "\"-r\"", ",", "\"-c\"", ",", "\"-a\"", ",", "\"-ir\"", "]", ":", "raise", "NameError", "(", "\"Incorrect mode \"", "+", "str", ...
Upload a record to the server. :param marcxml: the XML to upload. :param mode: the mode to use for the upload. - "-i" insert new records - "-r" replace existing records - "-c" correct fields of records - "-a" append fields to records - "-ir" i...
[ "Upload", "a", "record", "to", "the", "server", "." ]
3f9ddb6f3b3ce3a21d399d1098d6769bf05cdd6c
https://github.com/inveniosoftware-attic/invenio-client/blob/3f9ddb6f3b3ce3a21d399d1098d6769bf05cdd6c/invenio_client/connector.py#L298-L314
train
58,592
inveniosoftware-attic/invenio-client
invenio_client/connector.py
Record.url
def url(self): """ Returns the URL to this record. Returns None if not known """ if self.server_url is not None and \ self.recid is not None: return '/'.join( [self.server_url, CFG_SITE_RECORD, str(self.recid)]) else: ...
python
def url(self): """ Returns the URL to this record. Returns None if not known """ if self.server_url is not None and \ self.recid is not None: return '/'.join( [self.server_url, CFG_SITE_RECORD, str(self.recid)]) else: ...
[ "def", "url", "(", "self", ")", ":", "if", "self", ".", "server_url", "is", "not", "None", "and", "self", ".", "recid", "is", "not", "None", ":", "return", "'/'", ".", "join", "(", "[", "self", ".", "server_url", ",", "CFG_SITE_RECORD", ",", "str", ...
Returns the URL to this record. Returns None if not known
[ "Returns", "the", "URL", "to", "this", "record", ".", "Returns", "None", "if", "not", "known" ]
3f9ddb6f3b3ce3a21d399d1098d6769bf05cdd6c
https://github.com/inveniosoftware-attic/invenio-client/blob/3f9ddb6f3b3ce3a21d399d1098d6769bf05cdd6c/invenio_client/connector.py#L399-L409
train
58,593
MKLab-ITI/reveal-user-annotation
reveal_user_annotation/twitter/clean_twitter_list.py
clean_list_of_twitter_list
def clean_list_of_twitter_list(list_of_twitter_lists, sent_tokenize, _treebank_word_tokenize, tagger, lemmatizer, lemmatize, stopset, first_cap_re, all_cap_re, digits_punctuation_whitespace_re, po...
python
def clean_list_of_twitter_list(list_of_twitter_lists, sent_tokenize, _treebank_word_tokenize, tagger, lemmatizer, lemmatize, stopset, first_cap_re, all_cap_re, digits_punctuation_whitespace_re, po...
[ "def", "clean_list_of_twitter_list", "(", "list_of_twitter_lists", ",", "sent_tokenize", ",", "_treebank_word_tokenize", ",", "tagger", ",", "lemmatizer", ",", "lemmatize", ",", "stopset", ",", "first_cap_re", ",", "all_cap_re", ",", "digits_punctuation_whitespace_re", ",...
Extracts the sets of keywords for each Twitter list. Inputs: - list_of_twitter_lists: A python list of Twitter lists in json format. - lemmatizing: A string containing one of the following: "porter", "snowball" or "wordnet". Output: - list_of_keyword_sets: A list of sets of keywords (i.e. not a ba...
[ "Extracts", "the", "sets", "of", "keywords", "for", "each", "Twitter", "list", "." ]
ed019c031857b091e5601f53ba3f01a499a0e3ef
https://github.com/MKLab-ITI/reveal-user-annotation/blob/ed019c031857b091e5601f53ba3f01a499a0e3ef/reveal_user_annotation/twitter/clean_twitter_list.py#L48-L79
train
58,594
MKLab-ITI/reveal-user-annotation
reveal_user_annotation/twitter/clean_twitter_list.py
user_twitter_list_bag_of_words
def user_twitter_list_bag_of_words(twitter_list_corpus, sent_tokenize, _treebank_word_tokenize, tagger, lemmatizer, lemmatize, stopset, first_cap_re, all_cap_re, digits_punctuation_whitespace_re, ...
python
def user_twitter_list_bag_of_words(twitter_list_corpus, sent_tokenize, _treebank_word_tokenize, tagger, lemmatizer, lemmatize, stopset, first_cap_re, all_cap_re, digits_punctuation_whitespace_re, ...
[ "def", "user_twitter_list_bag_of_words", "(", "twitter_list_corpus", ",", "sent_tokenize", ",", "_treebank_word_tokenize", ",", "tagger", ",", "lemmatizer", ",", "lemmatize", ",", "stopset", ",", "first_cap_re", ",", "all_cap_re", ",", "digits_punctuation_whitespace_re", ...
Extract a bag-of-words for a corpus of Twitter lists pertaining to a Twitter user. Inputs: - twitter_list_corpus: A python list of Twitter lists in json format. - lemmatizing: A string containing one of the following: "porter", "snowball" or "wordnet". Output: - bag_of_words: A bag-of-words in pyt...
[ "Extract", "a", "bag", "-", "of", "-", "words", "for", "a", "corpus", "of", "Twitter", "lists", "pertaining", "to", "a", "Twitter", "user", "." ]
ed019c031857b091e5601f53ba3f01a499a0e3ef
https://github.com/MKLab-ITI/reveal-user-annotation/blob/ed019c031857b091e5601f53ba3f01a499a0e3ef/reveal_user_annotation/twitter/clean_twitter_list.py#L82-L114
train
58,595
MKLab-ITI/reveal-user-annotation
reveal_user_annotation/text/map_data.py
grouper
def grouper(iterable, n, pad_value=None): """ Returns a generator of n-length chunks of an input iterable, with appropriate padding at the end. Example: grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x') Inputs: - iterable: The source iterable that needs to be chunkified. ...
python
def grouper(iterable, n, pad_value=None): """ Returns a generator of n-length chunks of an input iterable, with appropriate padding at the end. Example: grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x') Inputs: - iterable: The source iterable that needs to be chunkified. ...
[ "def", "grouper", "(", "iterable", ",", "n", ",", "pad_value", "=", "None", ")", ":", "chunk_gen", "=", "(", "chunk", "for", "chunk", "in", "zip_longest", "(", "*", "[", "iter", "(", "iterable", ")", "]", "*", "n", ",", "fillvalue", "=", "pad_value",...
Returns a generator of n-length chunks of an input iterable, with appropriate padding at the end. Example: grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x') Inputs: - iterable: The source iterable that needs to be chunkified. - n: The size of the chunks. - pad_...
[ "Returns", "a", "generator", "of", "n", "-", "length", "chunks", "of", "an", "input", "iterable", "with", "appropriate", "padding", "at", "the", "end", "." ]
ed019c031857b091e5601f53ba3f01a499a0e3ef
https://github.com/MKLab-ITI/reveal-user-annotation/blob/ed019c031857b091e5601f53ba3f01a499a0e3ef/reveal_user_annotation/text/map_data.py#L9-L22
train
58,596
MKLab-ITI/reveal-user-annotation
reveal_user_annotation/text/map_data.py
chunks
def chunks(iterable, n): """ A python generator that yields 100-length sub-list chunks. Input: - full_list: The input list that is to be separated in chunks of 100. - chunk_size: Should be set to 100, unless the Twitter API changes. Yields: - sub_list: List chunks of length 100. """ ...
python
def chunks(iterable, n): """ A python generator that yields 100-length sub-list chunks. Input: - full_list: The input list that is to be separated in chunks of 100. - chunk_size: Should be set to 100, unless the Twitter API changes. Yields: - sub_list: List chunks of length 100. """ ...
[ "def", "chunks", "(", "iterable", ",", "n", ")", ":", "for", "i", "in", "np", ".", "arange", "(", "0", ",", "len", "(", "iterable", ")", ",", "n", ")", ":", "yield", "iterable", "[", "i", ":", "i", "+", "n", "]" ]
A python generator that yields 100-length sub-list chunks. Input: - full_list: The input list that is to be separated in chunks of 100. - chunk_size: Should be set to 100, unless the Twitter API changes. Yields: - sub_list: List chunks of length 100.
[ "A", "python", "generator", "that", "yields", "100", "-", "length", "sub", "-", "list", "chunks", "." ]
ed019c031857b091e5601f53ba3f01a499a0e3ef
https://github.com/MKLab-ITI/reveal-user-annotation/blob/ed019c031857b091e5601f53ba3f01a499a0e3ef/reveal_user_annotation/text/map_data.py#L25-L35
train
58,597
MKLab-ITI/reveal-user-annotation
reveal_user_annotation/text/map_data.py
split_every
def split_every(iterable, n): # TODO: Remove this, or make it return a generator. """ A generator of n-length chunks of an input iterable """ i = iter(iterable) piece = list(islice(i, n)) while piece: yield piece piece = list(islice(i, n))
python
def split_every(iterable, n): # TODO: Remove this, or make it return a generator. """ A generator of n-length chunks of an input iterable """ i = iter(iterable) piece = list(islice(i, n)) while piece: yield piece piece = list(islice(i, n))
[ "def", "split_every", "(", "iterable", ",", "n", ")", ":", "# TODO: Remove this, or make it return a generator.", "i", "=", "iter", "(", "iterable", ")", "piece", "=", "list", "(", "islice", "(", "i", ",", "n", ")", ")", "while", "piece", ":", "yield", "pi...
A generator of n-length chunks of an input iterable
[ "A", "generator", "of", "n", "-", "length", "chunks", "of", "an", "input", "iterable" ]
ed019c031857b091e5601f53ba3f01a499a0e3ef
https://github.com/MKLab-ITI/reveal-user-annotation/blob/ed019c031857b091e5601f53ba3f01a499a0e3ef/reveal_user_annotation/text/map_data.py#L38-L46
train
58,598
NORDUnet/python-norduniclient
norduniclient/helpers.py
merge_properties
def merge_properties(item_properties, prop_name, merge_value): """ Tries to figure out which type of property value that should be merged and invoke the right function. Returns new properties if the merge was successful otherwise False. """ existing_value = item_properties.get(prop_name, None) ...
python
def merge_properties(item_properties, prop_name, merge_value): """ Tries to figure out which type of property value that should be merged and invoke the right function. Returns new properties if the merge was successful otherwise False. """ existing_value = item_properties.get(prop_name, None) ...
[ "def", "merge_properties", "(", "item_properties", ",", "prop_name", ",", "merge_value", ")", ":", "existing_value", "=", "item_properties", ".", "get", "(", "prop_name", ",", "None", ")", "if", "not", "existing_value", ":", "# A node without existing values for the p...
Tries to figure out which type of property value that should be merged and invoke the right function. Returns new properties if the merge was successful otherwise False.
[ "Tries", "to", "figure", "out", "which", "type", "of", "property", "value", "that", "should", "be", "merged", "and", "invoke", "the", "right", "function", ".", "Returns", "new", "properties", "if", "the", "merge", "was", "successful", "otherwise", "False", "...
ee5084a6f45caac614b4fda4a023749ca52f786c
https://github.com/NORDUnet/python-norduniclient/blob/ee5084a6f45caac614b4fda4a023749ca52f786c/norduniclient/helpers.py#L34-L50
train
58,599