repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
dotzero/tilda-api-python
tilda/client.py
Client.get_page
def get_page(self, page_id): """ Get short page info and body html code """ try: result = self._request('/getpage/', {'pageid': page_id}) return TildaPage(**result) except NetworkError: return []
python
def get_page(self, page_id): """ Get short page info and body html code """ try: result = self._request('/getpage/', {'pageid': page_id}) return TildaPage(**result) except NetworkError: return []
[ "def", "get_page", "(", "self", ",", "page_id", ")", ":", "try", ":", "result", "=", "self", ".", "_request", "(", "'/getpage/'", ",", "{", "'pageid'", ":", "page_id", "}", ")", "return", "TildaPage", "(", "*", "*", "result", ")", "except", "NetworkErr...
Get short page info and body html code
[ "Get", "short", "page", "info", "and", "body", "html", "code" ]
train
https://github.com/dotzero/tilda-api-python/blob/0ab984e0236cbfb676b0fbddc1ab37202d92e0a8/tilda/client.py#L110-L117
dotzero/tilda-api-python
tilda/client.py
Client.get_page_full
def get_page_full(self, page_id): """ Get full page info and full html code """ try: result = self._request('/getpagefull/', {'pageid': page_id}) return TildaPage(**result) except NetworkError: return []
python
def get_page_full(self, page_id): """ Get full page info and full html code """ try: result = self._request('/getpagefull/', {'pageid': page_id}) return TildaPage(**result) except NetworkError: return []
[ "def", "get_page_full", "(", "self", ",", "page_id", ")", ":", "try", ":", "result", "=", "self", ".", "_request", "(", "'/getpagefull/'", ",", "{", "'pageid'", ":", "page_id", "}", ")", "return", "TildaPage", "(", "*", "*", "result", ")", "except", "N...
Get full page info and full html code
[ "Get", "full", "page", "info", "and", "full", "html", "code" ]
train
https://github.com/dotzero/tilda-api-python/blob/0ab984e0236cbfb676b0fbddc1ab37202d92e0a8/tilda/client.py#L119-L126
dotzero/tilda-api-python
tilda/client.py
Client.get_page_export
def get_page_export(self, page_id): """ Get short page info for export and body html code """ try: result = self._request('/getpageexport/', {'pageid': page_id}) return TildaPage(**result) except NetworkError: return []
python
def get_page_export(self, page_id): """ Get short page info for export and body html code """ try: result = self._request('/getpageexport/', {'pageid': page_id}) return TildaPage(**result) except NetworkError: return []
[ "def", "get_page_export", "(", "self", ",", "page_id", ")", ":", "try", ":", "result", "=", "self", ".", "_request", "(", "'/getpageexport/'", ",", "{", "'pageid'", ":", "page_id", "}", ")", "return", "TildaPage", "(", "*", "*", "result", ")", "except", ...
Get short page info for export and body html code
[ "Get", "short", "page", "info", "for", "export", "and", "body", "html", "code" ]
train
https://github.com/dotzero/tilda-api-python/blob/0ab984e0236cbfb676b0fbddc1ab37202d92e0a8/tilda/client.py#L128-L135
dotzero/tilda-api-python
tilda/client.py
Client.get_page_full_export
def get_page_full_export(self, page_id): """ Get full page info for export and body html code """ try: result = self._request('/getpagefullexport/', {'pageid': page_id}) return TildaPage(**result) except NetworkError: return ...
python
def get_page_full_export(self, page_id): """ Get full page info for export and body html code """ try: result = self._request('/getpagefullexport/', {'pageid': page_id}) return TildaPage(**result) except NetworkError: return ...
[ "def", "get_page_full_export", "(", "self", ",", "page_id", ")", ":", "try", ":", "result", "=", "self", ".", "_request", "(", "'/getpagefullexport/'", ",", "{", "'pageid'", ":", "page_id", "}", ")", "return", "TildaPage", "(", "*", "*", "result", ")", "...
Get full page info for export and body html code
[ "Get", "full", "page", "info", "for", "export", "and", "body", "html", "code" ]
train
https://github.com/dotzero/tilda-api-python/blob/0ab984e0236cbfb676b0fbddc1ab37202d92e0a8/tilda/client.py#L137-L144
ff0000/scarlet
setup.py
fullsplit
def fullsplit(path, result=None, base_path=None): """ Split a pathname into components (the opposite of os.path.join) in a platform-neutral way. """ if base_path: path = path.replace(base_path, '') if result is None: result = [] head, tail = os.path.split(path) if head ...
python
def fullsplit(path, result=None, base_path=None): """ Split a pathname into components (the opposite of os.path.join) in a platform-neutral way. """ if base_path: path = path.replace(base_path, '') if result is None: result = [] head, tail = os.path.split(path) if head ...
[ "def", "fullsplit", "(", "path", ",", "result", "=", "None", ",", "base_path", "=", "None", ")", ":", "if", "base_path", ":", "path", "=", "path", ".", "replace", "(", "base_path", ",", "''", ")", "if", "result", "is", "None", ":", "result", "=", "...
Split a pathname into components (the opposite of os.path.join) in a platform-neutral way.
[ "Split", "a", "pathname", "into", "components", "(", "the", "opposite", "of", "os", ".", "path", ".", "join", ")", "in", "a", "platform", "-", "neutral", "way", "." ]
train
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/setup.py#L31-L47
finklabs/banana
banana/routes/home.py
_flatten
def _flatten(l): """helper to flatten a list of lists """ res = [] for sublist in l: if isinstance(sublist, whaaaaat.Separator): res.append(sublist) else: for item in sublist: res.append(item) return res
python
def _flatten(l): """helper to flatten a list of lists """ res = [] for sublist in l: if isinstance(sublist, whaaaaat.Separator): res.append(sublist) else: for item in sublist: res.append(item) return res
[ "def", "_flatten", "(", "l", ")", ":", "res", "=", "[", "]", "for", "sublist", "in", "l", ":", "if", "isinstance", "(", "sublist", ",", "whaaaaat", ".", "Separator", ")", ":", "res", ".", "append", "(", "sublist", ")", "else", ":", "for", "item", ...
helper to flatten a list of lists
[ "helper", "to", "flatten", "a", "list", "of", "lists" ]
train
https://github.com/finklabs/banana/blob/bc416b5a3971fba0b0a90644760ccaddb95b0149/banana/routes/home.py#L10-L20
finklabs/banana
banana/routes/home.py
handle
def handle(app): # TODO: for this to work properly we need a generator registry # generator, lifecycle etc. # list of tuples (label, value) # TODO customize & use own style default_choices = [ { 'name': 'Install a generator', 'value': 'install' }, { ...
python
def handle(app): # TODO: for this to work properly we need a generator registry # generator, lifecycle etc. # list of tuples (label, value) # TODO customize & use own style default_choices = [ { 'name': 'Install a generator', 'value': 'install' }, { ...
[ "def", "handle", "(", "app", ")", ":", "# TODO: for this to work properly we need a generator registry", "# generator, lifecycle etc.", "# list of tuples (label, value)", "# TODO customize & use own style", "default_choices", "=", "[", "{", "'name'", ":", "'Install a generator'", ...
if (globalConfigHasContent()) { defaultChoices.splice(defaultChoices.length - 1, 0, { name: 'Clear global config', value: 'clearConfig' }); } var generatorList = _.chain(app.generators).map(function (generator) { if (!generator.appGenerator) { return null; } var updateInf...
[ "if", "(", "globalConfigHasContent", "()", ")", "{", "defaultChoices", ".", "splice", "(", "defaultChoices", ".", "length", "-", "1", "0", "{", "name", ":", "Clear", "global", "config", "value", ":", "clearConfig", "}", ")", ";", "}" ]
train
https://github.com/finklabs/banana/blob/bc416b5a3971fba0b0a90644760ccaddb95b0149/banana/routes/home.py#L24-L113
klahnakoski/pyLibrary
mo_parquet/vendor/fastparquet/thrift_structures.py
read_thrift
def read_thrift(file_obj, ttype): """Read a thrift structure from the given fo.""" from thrift.transport.TTransport import TFileObjectTransport, TBufferedTransport starting_pos = file_obj.tell() # set up the protocol chain ft = TFileObjectTransport(file_obj) bufsize = 2 ** 16 # for accelera...
python
def read_thrift(file_obj, ttype): """Read a thrift structure from the given fo.""" from thrift.transport.TTransport import TFileObjectTransport, TBufferedTransport starting_pos = file_obj.tell() # set up the protocol chain ft = TFileObjectTransport(file_obj) bufsize = 2 ** 16 # for accelera...
[ "def", "read_thrift", "(", "file_obj", ",", "ttype", ")", ":", "from", "thrift", ".", "transport", ".", "TTransport", "import", "TFileObjectTransport", ",", "TBufferedTransport", "starting_pos", "=", "file_obj", ".", "tell", "(", ")", "# set up the protocol chain", ...
Read a thrift structure from the given fo.
[ "Read", "a", "thrift", "structure", "from", "the", "given", "fo", "." ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_parquet/vendor/fastparquet/thrift_structures.py#L11-L34
klahnakoski/pyLibrary
mo_parquet/vendor/fastparquet/thrift_structures.py
write_thrift
def write_thrift(fobj, thrift): """Write binary compact representation of thiftpy structured object Parameters ---------- fobj: open file-like object (binary mode) thrift: thriftpy object to write Returns ------- Number of bytes written """ t0 = fobj.tell() pout = TCompactP...
python
def write_thrift(fobj, thrift): """Write binary compact representation of thiftpy structured object Parameters ---------- fobj: open file-like object (binary mode) thrift: thriftpy object to write Returns ------- Number of bytes written """ t0 = fobj.tell() pout = TCompactP...
[ "def", "write_thrift", "(", "fobj", ",", "thrift", ")", ":", "t0", "=", "fobj", ".", "tell", "(", ")", "pout", "=", "TCompactProtocol", "(", "fobj", ")", "try", ":", "thrift", ".", "write", "(", "pout", ")", "fail", "=", "False", "except", "TProtocol...
Write binary compact representation of thiftpy structured object Parameters ---------- fobj: open file-like object (binary mode) thrift: thriftpy object to write Returns ------- Number of bytes written
[ "Write", "binary", "compact", "representation", "of", "thiftpy", "structured", "object" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_parquet/vendor/fastparquet/thrift_structures.py#L37-L70
klahnakoski/pyLibrary
mo_parquet/vendor/fastparquet/thrift_structures.py
thrift_print
def thrift_print(structure, offset=0): """ Handy recursive text ouput for thrift structures """ if not is_thrift_item(structure): return str(structure) s = str(structure.__class__) + '\n' for key in dir(structure): if key.startswith('_') or key in ['thrift_spec', 'read', 'write',...
python
def thrift_print(structure, offset=0): """ Handy recursive text ouput for thrift structures """ if not is_thrift_item(structure): return str(structure) s = str(structure.__class__) + '\n' for key in dir(structure): if key.startswith('_') or key in ['thrift_spec', 'read', 'write',...
[ "def", "thrift_print", "(", "structure", ",", "offset", "=", "0", ")", ":", "if", "not", "is_thrift_item", "(", "structure", ")", ":", "return", "str", "(", "structure", ")", "s", "=", "str", "(", "structure", ".", "__class__", ")", "+", "'\\n'", "for"...
Handy recursive text ouput for thrift structures
[ "Handy", "recursive", "text", "ouput", "for", "thrift", "structures" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_parquet/vendor/fastparquet/thrift_structures.py#L77-L90
rodionovd/machobot
machobot/dylib.py
insert_load_command
def insert_load_command(target_path, library_install_name): """ Inserts a new LC_LOAD_DYLIB load command into the target Mach-O header. Note: the target file will be overwritten. Consider backing it up first before calling this function. Returns True if everything is OK. Otherwise rises an exception. """ def pat...
python
def insert_load_command(target_path, library_install_name): """ Inserts a new LC_LOAD_DYLIB load command into the target Mach-O header. Note: the target file will be overwritten. Consider backing it up first before calling this function. Returns True if everything is OK. Otherwise rises an exception. """ def pat...
[ "def", "insert_load_command", "(", "target_path", ",", "library_install_name", ")", ":", "def", "patchHeader", "(", "t", ")", ":", "load_command", "=", "generate_dylib_load_command", "(", "t", ",", "library_install_name", ")", "return", "insert_load_command_into_header"...
Inserts a new LC_LOAD_DYLIB load command into the target Mach-O header. Note: the target file will be overwritten. Consider backing it up first before calling this function. Returns True if everything is OK. Otherwise rises an exception.
[ "Inserts", "a", "new", "LC_LOAD_DYLIB", "load", "command", "into", "the", "target", "Mach", "-", "O", "header", ".", "Note", ":", "the", "target", "file", "will", "be", "overwritten", ".", "Consider", "backing", "it", "up", "first", "before", "calling", "t...
train
https://github.com/rodionovd/machobot/blob/60e10b63c2538a73dc8ec3ce636b3ed5bf09f524/machobot/dylib.py#L19-L29
rodionovd/machobot
machobot/dylib.py
macho_dependencies_list
def macho_dependencies_list(target_path, header_magic=None): """ Generates a list of libraries the given Mach-O file depends on. In that list a single library is represented by its "install path": for some libraries it would be a full file path, and for others it would be a relative path (sometimes with dyld templ...
python
def macho_dependencies_list(target_path, header_magic=None): """ Generates a list of libraries the given Mach-O file depends on. In that list a single library is represented by its "install path": for some libraries it would be a full file path, and for others it would be a relative path (sometimes with dyld templ...
[ "def", "macho_dependencies_list", "(", "target_path", ",", "header_magic", "=", "None", ")", ":", "MachODeprendencies", "=", "namedtuple", "(", "\"MachODeprendecies\"", ",", "\"weak strong\"", ")", "# Convert the magic value into macholib representation if needed", "if", "isi...
Generates a list of libraries the given Mach-O file depends on. In that list a single library is represented by its "install path": for some libraries it would be a full file path, and for others it would be a relative path (sometimes with dyld templates like @executable_path or @rpath in it). Note: I don't know ...
[ "Generates", "a", "list", "of", "libraries", "the", "given", "Mach", "-", "O", "file", "depends", "on", "." ]
train
https://github.com/rodionovd/machobot/blob/60e10b63c2538a73dc8ec3ce636b3ed5bf09f524/machobot/dylib.py#L31-L79
rodionovd/machobot
machobot/dylib.py
insert_load_command_into_header
def insert_load_command_into_header(header, load_command): """ Inserts the given load command into the header and adjust its size. """ lc, cmd, path = load_command header.commands.append((lc, cmd, path)) header.header.ncmds += 1 header.changedHeaderSizeBy(lc.cmdsize)
python
def insert_load_command_into_header(header, load_command): """ Inserts the given load command into the header and adjust its size. """ lc, cmd, path = load_command header.commands.append((lc, cmd, path)) header.header.ncmds += 1 header.changedHeaderSizeBy(lc.cmdsize)
[ "def", "insert_load_command_into_header", "(", "header", ",", "load_command", ")", ":", "lc", ",", "cmd", ",", "path", "=", "load_command", "header", ".", "commands", ".", "append", "(", "(", "lc", ",", "cmd", ",", "path", ")", ")", "header", ".", "heade...
Inserts the given load command into the header and adjust its size.
[ "Inserts", "the", "given", "load", "command", "into", "the", "header", "and", "adjust", "its", "size", "." ]
train
https://github.com/rodionovd/machobot/blob/60e10b63c2538a73dc8ec3ce636b3ed5bf09f524/machobot/dylib.py#L81-L86
rodionovd/machobot
machobot/dylib.py
generate_dylib_load_command
def generate_dylib_load_command(header, libary_install_name): """ Generates a LC_LOAD_DYLIB command for the given header and a library install path. Note: the header must already contain at least one LC_LOAD_DYLIB command (see code comments). Returns a ready-for-use load_command in terms of macholib. """ # One...
python
def generate_dylib_load_command(header, libary_install_name): """ Generates a LC_LOAD_DYLIB command for the given header and a library install path. Note: the header must already contain at least one LC_LOAD_DYLIB command (see code comments). Returns a ready-for-use load_command in terms of macholib. """ # One...
[ "def", "generate_dylib_load_command", "(", "header", ",", "libary_install_name", ")", ":", "# One can not simply create instances of `dylib_command` and `load_command` classes,", "# because that's just not the way macholib works. If we try then all we'll get is a bunch", "# of endian (big/little...
Generates a LC_LOAD_DYLIB command for the given header and a library install path. Note: the header must already contain at least one LC_LOAD_DYLIB command (see code comments). Returns a ready-for-use load_command in terms of macholib.
[ "Generates", "a", "LC_LOAD_DYLIB", "command", "for", "the", "given", "header", "and", "a", "library", "install", "path", ".", "Note", ":", "the", "header", "must", "already", "contain", "at", "least", "one", "LC_LOAD_DYLIB", "command", "(", "see", "code", "c...
train
https://github.com/rodionovd/machobot/blob/60e10b63c2538a73dc8ec3ce636b3ed5bf09f524/machobot/dylib.py#L88-L125
ff0000/scarlet
scarlet/accounts/forms.py
SignupModelForm.clean_username
def clean_username(self): """ Validate that the username is alphanumeric and is not already in use. Also validates that the username is not listed in ACCOUNTS_FORBIDDEN_USERNAMES list. """ try: get_user_model().objects.get( username__iexact=sel...
python
def clean_username(self): """ Validate that the username is alphanumeric and is not already in use. Also validates that the username is not listed in ACCOUNTS_FORBIDDEN_USERNAMES list. """ try: get_user_model().objects.get( username__iexact=sel...
[ "def", "clean_username", "(", "self", ")", ":", "try", ":", "get_user_model", "(", ")", ".", "objects", ".", "get", "(", "username__iexact", "=", "self", ".", "cleaned_data", "[", "'username'", "]", ")", "except", "get_user_model", "(", ")", ".", "DoesNotE...
Validate that the username is alphanumeric and is not already in use. Also validates that the username is not listed in ACCOUNTS_FORBIDDEN_USERNAMES list.
[ "Validate", "that", "the", "username", "is", "alphanumeric", "and", "is", "not", "already", "in", "use", ".", "Also", "validates", "that", "the", "username", "is", "not", "listed", "in", "ACCOUNTS_FORBIDDEN_USERNAMES", "list", "." ]
train
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/accounts/forms.py#L62-L77
ff0000/scarlet
scarlet/accounts/forms.py
SignupModelForm.clean_email
def clean_email(self): """ Validate that the e-mail address is unique. """ if get_user_model().objects.filter( email__iexact=self.cleaned_data['email']): raise forms.ValidationError(_('This email is already in use. Please supply a different email.')) retur...
python
def clean_email(self): """ Validate that the e-mail address is unique. """ if get_user_model().objects.filter( email__iexact=self.cleaned_data['email']): raise forms.ValidationError(_('This email is already in use. Please supply a different email.')) retur...
[ "def", "clean_email", "(", "self", ")", ":", "if", "get_user_model", "(", ")", ".", "objects", ".", "filter", "(", "email__iexact", "=", "self", ".", "cleaned_data", "[", "'email'", "]", ")", ":", "raise", "forms", ".", "ValidationError", "(", "_", "(", ...
Validate that the e-mail address is unique.
[ "Validate", "that", "the", "e", "-", "mail", "address", "is", "unique", "." ]
train
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/accounts/forms.py#L79-L86
ff0000/scarlet
scarlet/accounts/forms.py
SignupModelForm.save
def save(self): """ Creates a new user and account. Returns the newly created user. """ username, email, password, first_name, last_name = (self.cleaned_data['username'], self.cleaned_data['email'], self.cleaned_data['password1'],...
python
def save(self): """ Creates a new user and account. Returns the newly created user. """ username, email, password, first_name, last_name = (self.cleaned_data['username'], self.cleaned_data['email'], self.cleaned_data['password1'],...
[ "def", "save", "(", "self", ")", ":", "username", ",", "email", ",", "password", ",", "first_name", ",", "last_name", "=", "(", "self", ".", "cleaned_data", "[", "'username'", "]", ",", "self", ".", "cleaned_data", "[", "'email'", "]", ",", "self", "."...
Creates a new user and account. Returns the newly created user.
[ "Creates", "a", "new", "user", "and", "account", ".", "Returns", "the", "newly", "created", "user", "." ]
train
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/accounts/forms.py#L99-L113
commonwealth-of-puerto-rico/libre
libre/apps/data_drivers/response.py
CustomResponse.get_authenticate_header
def get_authenticate_header(self, request): """ If a request is unauthenticated, determine the WWW-Authenticate header to use for 401 responses, if any. """ authenticators = self.get_authenticators() if authenticators: return authenticators[0].authenticate_hea...
python
def get_authenticate_header(self, request): """ If a request is unauthenticated, determine the WWW-Authenticate header to use for 401 responses, if any. """ authenticators = self.get_authenticators() if authenticators: return authenticators[0].authenticate_hea...
[ "def", "get_authenticate_header", "(", "self", ",", "request", ")", ":", "authenticators", "=", "self", ".", "get_authenticators", "(", ")", "if", "authenticators", ":", "return", "authenticators", "[", "0", "]", ".", "authenticate_header", "(", "request", ")" ]
If a request is unauthenticated, determine the WWW-Authenticate header to use for 401 responses, if any.
[ "If", "a", "request", "is", "unauthenticated", "determine", "the", "WWW", "-", "Authenticate", "header", "to", "use", "for", "401", "responses", "if", "any", "." ]
train
https://github.com/commonwealth-of-puerto-rico/libre/blob/5b32f4ab068b515d2ea652b182e161271ba874e8/libre/apps/data_drivers/response.py#L76-L83
finklabs/banana
banana/template.py
create_dir
def create_dir(dst): """create directory if necessary :param dst: """ directory = os.path.dirname(dst) if directory and not os.path.exists(directory): os.makedirs(directory)
python
def create_dir(dst): """create directory if necessary :param dst: """ directory = os.path.dirname(dst) if directory and not os.path.exists(directory): os.makedirs(directory)
[ "def", "create_dir", "(", "dst", ")", ":", "directory", "=", "os", ".", "path", ".", "dirname", "(", "dst", ")", "if", "directory", "and", "not", "os", ".", "path", ".", "exists", "(", "directory", ")", ":", "os", ".", "makedirs", "(", "directory", ...
create directory if necessary :param dst:
[ "create", "directory", "if", "necessary" ]
train
https://github.com/finklabs/banana/blob/bc416b5a3971fba0b0a90644760ccaddb95b0149/banana/template.py#L15-L22
finklabs/banana
banana/template.py
copy_wildcard
def copy_wildcard(src_folder, dst_folder, glob): """copy """ create_dir(dst_folder) for sname in iglob(os.path.join(src_folder, glob)): rname = os.path.relpath(sname, src_folder) dname = os.path.join(dst_folder, rname) create_dir(dname) shutil.copy(sname, dname)
python
def copy_wildcard(src_folder, dst_folder, glob): """copy """ create_dir(dst_folder) for sname in iglob(os.path.join(src_folder, glob)): rname = os.path.relpath(sname, src_folder) dname = os.path.join(dst_folder, rname) create_dir(dname) shutil.copy(sname, dname)
[ "def", "copy_wildcard", "(", "src_folder", ",", "dst_folder", ",", "glob", ")", ":", "create_dir", "(", "dst_folder", ")", "for", "sname", "in", "iglob", "(", "os", ".", "path", ".", "join", "(", "src_folder", ",", "glob", ")", ")", ":", "rname", "=", ...
copy
[ "copy" ]
train
https://github.com/finklabs/banana/blob/bc416b5a3971fba0b0a90644760ccaddb95b0149/banana/template.py#L34-L42
finklabs/banana
banana/template.py
copy_tpl
def copy_tpl(template_file, dst, template_vars): """This supports jinja2 templates. Please feel encouraged to use the template framework of your choosing. jinja2 docu: http://jinja.pocoo.org/docs/2.9/ :param template_file: :param dst: :param template_vars: dictionary containing key, values used...
python
def copy_tpl(template_file, dst, template_vars): """This supports jinja2 templates. Please feel encouraged to use the template framework of your choosing. jinja2 docu: http://jinja.pocoo.org/docs/2.9/ :param template_file: :param dst: :param template_vars: dictionary containing key, values used...
[ "def", "copy_tpl", "(", "template_file", ",", "dst", ",", "template_vars", ")", ":", "create_dir", "(", "dst", ")", "# load template", "template_loader", "=", "jinja2", ".", "FileSystemLoader", "(", "searchpath", "=", "'/'", ")", "template_env", "=", "jinja2", ...
This supports jinja2 templates. Please feel encouraged to use the template framework of your choosing. jinja2 docu: http://jinja.pocoo.org/docs/2.9/ :param template_file: :param dst: :param template_vars: dictionary containing key, values used in the template
[ "This", "supports", "jinja2", "templates", ".", "Please", "feel", "encouraged", "to", "use", "the", "template", "framework", "of", "your", "choosing", ".", "jinja2", "docu", ":", "http", ":", "//", "jinja", ".", "pocoo", ".", "org", "/", "docs", "/", "2"...
train
https://github.com/finklabs/banana/blob/bc416b5a3971fba0b0a90644760ccaddb95b0149/banana/template.py#L45-L63
klahnakoski/pyLibrary
tuid/clogger.py
Clogger.recompute_table_revnums
def recompute_table_revnums(self): ''' Recomputes the revnums for the csetLog table by creating a new table, and copying csetLog to it. The INTEGER PRIMARY KEY in the temp table auto increments as rows are added. IMPORTANT: Only call this after acquiring the ...
python
def recompute_table_revnums(self): ''' Recomputes the revnums for the csetLog table by creating a new table, and copying csetLog to it. The INTEGER PRIMARY KEY in the temp table auto increments as rows are added. IMPORTANT: Only call this after acquiring the ...
[ "def", "recompute_table_revnums", "(", "self", ")", ":", "with", "self", ".", "conn", ".", "transaction", "(", ")", "as", "t", ":", "t", ".", "execute", "(", "'''\n CREATE TABLE temp (\n revnum INTEGER PRIMARY KEY,\n revision...
Recomputes the revnums for the csetLog table by creating a new table, and copying csetLog to it. The INTEGER PRIMARY KEY in the temp table auto increments as rows are added. IMPORTANT: Only call this after acquiring the lock `self.working_locker`. :return:
[ "Recomputes", "the", "revnums", "for", "the", "csetLog", "table", "by", "creating", "a", "new", "table", "and", "copying", "csetLog", "to", "it", ".", "The", "INTEGER", "PRIMARY", "KEY", "in", "the", "temp", "table", "auto", "increments", "as", "rows", "ar...
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/tuid/clogger.py#L166-L191
klahnakoski/pyLibrary
tuid/clogger.py
Clogger.check_for_maintenance
def check_for_maintenance(self): ''' Returns True if the maintenance worker should be run now, and False otherwise. :return: ''' numrevs = self.conn.get_one("SELECT count(revnum) FROM csetLog")[0] if numrevs >= SIGNAL_MAINTENACE_CSETS: return True ...
python
def check_for_maintenance(self): ''' Returns True if the maintenance worker should be run now, and False otherwise. :return: ''' numrevs = self.conn.get_one("SELECT count(revnum) FROM csetLog")[0] if numrevs >= SIGNAL_MAINTENACE_CSETS: return True ...
[ "def", "check_for_maintenance", "(", "self", ")", ":", "numrevs", "=", "self", ".", "conn", ".", "get_one", "(", "\"SELECT count(revnum) FROM csetLog\"", ")", "[", "0", "]", "if", "numrevs", ">=", "SIGNAL_MAINTENACE_CSETS", ":", "return", "True", "return", "Fals...
Returns True if the maintenance worker should be run now, and False otherwise. :return:
[ "Returns", "True", "if", "the", "maintenance", "worker", "should", "be", "run", "now", "and", "False", "otherwise", ".", ":", "return", ":" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/tuid/clogger.py#L194-L203
klahnakoski/pyLibrary
tuid/clogger.py
Clogger.add_cset_entries
def add_cset_entries(self, ordered_rev_list, timestamp=False, number_forward=True): ''' Adds a list of revisions to the table. Assumes ordered_rev_list is an ordered based on how changesets are found in the changelog. Going forwards or backwards is dealt with by flipping the list ...
python
def add_cset_entries(self, ordered_rev_list, timestamp=False, number_forward=True): ''' Adds a list of revisions to the table. Assumes ordered_rev_list is an ordered based on how changesets are found in the changelog. Going forwards or backwards is dealt with by flipping the list ...
[ "def", "add_cset_entries", "(", "self", ",", "ordered_rev_list", ",", "timestamp", "=", "False", ",", "number_forward", "=", "True", ")", ":", "with", "self", ".", "conn", ".", "transaction", "(", ")", "as", "t", ":", "current_min", "=", "t", ".", "get_o...
Adds a list of revisions to the table. Assumes ordered_rev_list is an ordered based on how changesets are found in the changelog. Going forwards or backwards is dealt with by flipping the list :param ordered_cset_list: Order given from changeset log searching. :param timestamp: If false,...
[ "Adds", "a", "list", "of", "revisions", "to", "the", "table", ".", "Assumes", "ordered_rev_list", "is", "an", "ordered", "based", "on", "how", "changesets", "are", "found", "in", "the", "changelog", ".", "Going", "forwards", "or", "backwards", "is", "dealt",...
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/tuid/clogger.py#L206-L267
klahnakoski/pyLibrary
tuid/clogger.py
Clogger._fill_in_range
def _fill_in_range(self, parent_cset, child_cset, timestamp=False, number_forward=True): ''' Fills cset logs in a certain range. 'parent_cset' can be an int and in that case, we get that many changesets instead. If parent_cset is an int, then we consider that we are going backwards (numb...
python
def _fill_in_range(self, parent_cset, child_cset, timestamp=False, number_forward=True): ''' Fills cset logs in a certain range. 'parent_cset' can be an int and in that case, we get that many changesets instead. If parent_cset is an int, then we consider that we are going backwards (numb...
[ "def", "_fill_in_range", "(", "self", ",", "parent_cset", ",", "child_cset", ",", "timestamp", "=", "False", ",", "number_forward", "=", "True", ")", ":", "csets_to_add", "=", "[", "]", "found_parent", "=", "False", "find_parent", "=", "False", "if", "type",...
Fills cset logs in a certain range. 'parent_cset' can be an int and in that case, we get that many changesets instead. If parent_cset is an int, then we consider that we are going backwards (number_forward is False) and we ignore the first changeset of the first log, and we ignore the setting fo...
[ "Fills", "cset", "logs", "in", "a", "certain", "range", ".", "parent_cset", "can", "be", "an", "int", "and", "in", "that", "case", "we", "get", "that", "many", "changesets", "instead", ".", "If", "parent_cset", "is", "an", "int", "then", "we", "consider"...
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/tuid/clogger.py#L270-L350
klahnakoski/pyLibrary
tuid/clogger.py
Clogger.fill_backward_with_list
def fill_backward_with_list(self, please_stop=None): ''' Expects requests of the tuple form: (parent_cset, timestamp) parent_cset can be an int X to go back by X changesets, or a string to search for going backwards in time. If timestamp is false, no timestamps will be added to t...
python
def fill_backward_with_list(self, please_stop=None): ''' Expects requests of the tuple form: (parent_cset, timestamp) parent_cset can be an int X to go back by X changesets, or a string to search for going backwards in time. If timestamp is false, no timestamps will be added to t...
[ "def", "fill_backward_with_list", "(", "self", ",", "please_stop", "=", "None", ")", ":", "while", "not", "please_stop", ":", "try", ":", "request", "=", "self", ".", "csets_todo_backwards", ".", "pop", "(", "till", "=", "please_stop", ")", "if", "please_sto...
Expects requests of the tuple form: (parent_cset, timestamp) parent_cset can be an int X to go back by X changesets, or a string to search for going backwards in time. If timestamp is false, no timestamps will be added to the entries. :param please_stop: :return:
[ "Expects", "requests", "of", "the", "tuple", "form", ":", "(", "parent_cset", "timestamp", ")", "parent_cset", "can", "be", "an", "int", "X", "to", "go", "back", "by", "X", "changesets", "or", "a", "string", "to", "search", "for", "going", "backwards", "...
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/tuid/clogger.py#L353-L396
klahnakoski/pyLibrary
tuid/clogger.py
Clogger.update_tip
def update_tip(self): ''' Returns False if the tip is already at the newest, or True if an update has taken place. :return: ''' clog_obj = self._get_clog(self.tuid_service.hg_url / self.config.hg.branch / 'json-log' / 'tip') # Get current tip in DB with s...
python
def update_tip(self): ''' Returns False if the tip is already at the newest, or True if an update has taken place. :return: ''' clog_obj = self._get_clog(self.tuid_service.hg_url / self.config.hg.branch / 'json-log' / 'tip') # Get current tip in DB with s...
[ "def", "update_tip", "(", "self", ")", ":", "clog_obj", "=", "self", ".", "_get_clog", "(", "self", ".", "tuid_service", ".", "hg_url", "/", "self", ".", "config", ".", "hg", ".", "branch", "/", "'json-log'", "/", "'tip'", ")", "# Get current tip in DB", ...
Returns False if the tip is already at the newest, or True if an update has taken place. :return:
[ "Returns", "False", "if", "the", "tip", "is", "already", "at", "the", "newest", "or", "True", "if", "an", "update", "has", "taken", "place", ".", ":", "return", ":" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/tuid/clogger.py#L399-L463
klahnakoski/pyLibrary
tuid/clogger.py
Clogger.csetLog_maintenance
def csetLog_maintenance(self, please_stop=None): ''' Handles deleting old csetLog entries and timestamping revisions once they pass the length for permanent storage for deletion later. :param please_stop: :return: ''' while not please_stop: try...
python
def csetLog_maintenance(self, please_stop=None): ''' Handles deleting old csetLog entries and timestamping revisions once they pass the length for permanent storage for deletion later. :param please_stop: :return: ''' while not please_stop: try...
[ "def", "csetLog_maintenance", "(", "self", ",", "please_stop", "=", "None", ")", ":", "while", "not", "please_stop", ":", "try", ":", "# Wait until something signals the maintenance cycle", "# to begin (or end).", "(", "self", ".", "maintenance_signal", "|", "please_sto...
Handles deleting old csetLog entries and timestamping revisions once they pass the length for permanent storage for deletion later. :param please_stop: :return:
[ "Handles", "deleting", "old", "csetLog", "entries", "and", "timestamping", "revisions", "once", "they", "pass", "the", "length", "for", "permanent", "storage", "for", "deletion", "later", ".", ":", "param", "please_stop", ":", ":", "return", ":" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/tuid/clogger.py#L488-L627
klahnakoski/pyLibrary
tuid/clogger.py
Clogger.csetLog_deleter
def csetLog_deleter(self, please_stop=None): ''' Deletes changesets from the csetLog table and also changesets from the annotation table that have revisions matching the given changesets. Accepts lists of csets from self.deletions_todo. :param please_stop: :return...
python
def csetLog_deleter(self, please_stop=None): ''' Deletes changesets from the csetLog table and also changesets from the annotation table that have revisions matching the given changesets. Accepts lists of csets from self.deletions_todo. :param please_stop: :return...
[ "def", "csetLog_deleter", "(", "self", ",", "please_stop", "=", "None", ")", ":", "while", "not", "please_stop", ":", "try", ":", "request", "=", "self", ".", "deletions_todo", ".", "pop", "(", "till", "=", "please_stop", ")", "if", "please_stop", ":", "...
Deletes changesets from the csetLog table and also changesets from the annotation table that have revisions matching the given changesets. Accepts lists of csets from self.deletions_todo. :param please_stop: :return:
[ "Deletes", "changesets", "from", "the", "csetLog", "table", "and", "also", "changesets", "from", "the", "annotation", "table", "that", "have", "revisions", "matching", "the", "given", "changesets", ".", "Accepts", "lists", "of", "csets", "from", "self", ".", "...
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/tuid/clogger.py#L630-L706
klahnakoski/pyLibrary
jx_base/__init__.py
DataClass
def DataClass(name, columns, constraint=None): """ Use the DataClass to define a class, but with some extra features: 1. restrict the datatype of property 2. restrict if `required`, or if `nulls` are allowed 3. generic constraints on object properties It is expected that this class become a rea...
python
def DataClass(name, columns, constraint=None): """ Use the DataClass to define a class, but with some extra features: 1. restrict the datatype of property 2. restrict if `required`, or if `nulls` are allowed 3. generic constraints on object properties It is expected that this class become a rea...
[ "def", "DataClass", "(", "name", ",", "columns", ",", "constraint", "=", "None", ")", ":", "columns", "=", "wrap", "(", "[", "{", "\"name\"", ":", "c", ",", "\"required\"", ":", "True", ",", "\"nulls\"", ":", "False", ",", "\"type\"", ":", "object", ...
Use the DataClass to define a class, but with some extra features: 1. restrict the datatype of property 2. restrict if `required`, or if `nulls` are allowed 3. generic constraints on object properties It is expected that this class become a real class (or be removed) in the long term because it is ...
[ "Use", "the", "DataClass", "to", "define", "a", "class", "but", "with", "some", "extra", "features", ":", "1", ".", "restrict", "the", "datatype", "of", "property", "2", ".", "restrict", "if", "required", "or", "if", "nulls", "are", "allowed", "3", ".", ...
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/jx_base/__init__.py#L53-L198
SkyLothar/requests-aliyun
aliyunauth/sign_ver_1_0.py
AuthBase.sign
def sign(self, method, params): """Calculate signature with the SIG_METHOD(HMAC-SHA1) Returns a base64 encoeded string of the hex signature :param method: the http verb :param params: the params needs calculate """ query_str = utils.percent_encode(params.items(), True) ...
python
def sign(self, method, params): """Calculate signature with the SIG_METHOD(HMAC-SHA1) Returns a base64 encoeded string of the hex signature :param method: the http verb :param params: the params needs calculate """ query_str = utils.percent_encode(params.items(), True) ...
[ "def", "sign", "(", "self", ",", "method", ",", "params", ")", ":", "query_str", "=", "utils", ".", "percent_encode", "(", "params", ".", "items", "(", ")", ",", "True", ")", "str_to_sign", "=", "\"{0}&%2F&{1}\"", ".", "format", "(", "method", ",", "ut...
Calculate signature with the SIG_METHOD(HMAC-SHA1) Returns a base64 encoeded string of the hex signature :param method: the http verb :param params: the params needs calculate
[ "Calculate", "signature", "with", "the", "SIG_METHOD", "(", "HMAC", "-", "SHA1", ")", "Returns", "a", "base64", "encoeded", "string", "of", "the", "hex", "signature" ]
train
https://github.com/SkyLothar/requests-aliyun/blob/43f6646dcf7f09691ae997b09d365ad9e76386cf/aliyunauth/sign_ver_1_0.py#L82-L100
ga4gh/ga4gh-common
ga4gh/common/utils.py
getPathOfExecutable
def getPathOfExecutable(executable): """ Returns the full path of the executable, or None if the executable can not be found. """ exe_paths = os.environ['PATH'].split(':') for exe_path in exe_paths: exe_file = os.path.join(exe_path, executable) if os.path.isfile(exe_file) and os....
python
def getPathOfExecutable(executable): """ Returns the full path of the executable, or None if the executable can not be found. """ exe_paths = os.environ['PATH'].split(':') for exe_path in exe_paths: exe_file = os.path.join(exe_path, executable) if os.path.isfile(exe_file) and os....
[ "def", "getPathOfExecutable", "(", "executable", ")", ":", "exe_paths", "=", "os", ".", "environ", "[", "'PATH'", "]", ".", "split", "(", "':'", ")", "for", "exe_path", "in", "exe_paths", ":", "exe_file", "=", "os", ".", "path", ".", "join", "(", "exe_...
Returns the full path of the executable, or None if the executable can not be found.
[ "Returns", "the", "full", "path", "of", "the", "executable", "or", "None", "if", "the", "executable", "can", "not", "be", "found", "." ]
train
https://github.com/ga4gh/ga4gh-common/blob/ea1b562dce5bf088ac4577b838cfac7745f08346/ga4gh/common/utils.py#L30-L40
ga4gh/ga4gh-common
ga4gh/common/utils.py
requireExecutables
def requireExecutables(executables): """ Check that all of the given executables are on the path. If at least one of them is not, exit the script and inform the user of the missing requirement(s). """ missingExecutables = [] for executable in executables: if getPathOfExecutable(execu...
python
def requireExecutables(executables): """ Check that all of the given executables are on the path. If at least one of them is not, exit the script and inform the user of the missing requirement(s). """ missingExecutables = [] for executable in executables: if getPathOfExecutable(execu...
[ "def", "requireExecutables", "(", "executables", ")", ":", "missingExecutables", "=", "[", "]", "for", "executable", "in", "executables", ":", "if", "getPathOfExecutable", "(", "executable", ")", "is", "None", ":", "missingExecutables", ".", "append", "(", "exec...
Check that all of the given executables are on the path. If at least one of them is not, exit the script and inform the user of the missing requirement(s).
[ "Check", "that", "all", "of", "the", "given", "executables", "are", "on", "the", "path", ".", "If", "at", "least", "one", "of", "them", "is", "not", "exit", "the", "script", "and", "inform", "the", "user", "of", "the", "missing", "requirement", "(", "s...
train
https://github.com/ga4gh/ga4gh-common/blob/ea1b562dce5bf088ac4577b838cfac7745f08346/ga4gh/common/utils.py#L43-L58
ga4gh/ga4gh-common
ga4gh/common/utils.py
runCommandReturnOutput
def runCommandReturnOutput(cmd): """ Runs a shell command and return the stdout and stderr """ splits = shlex.split(cmd) proc = subprocess.Popen( splits, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = proc.communicate() if proc.returncode != 0: raise subproc...
python
def runCommandReturnOutput(cmd): """ Runs a shell command and return the stdout and stderr """ splits = shlex.split(cmd) proc = subprocess.Popen( splits, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = proc.communicate() if proc.returncode != 0: raise subproc...
[ "def", "runCommandReturnOutput", "(", "cmd", ")", ":", "splits", "=", "shlex", ".", "split", "(", "cmd", ")", "proc", "=", "subprocess", ".", "Popen", "(", "splits", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", ...
Runs a shell command and return the stdout and stderr
[ "Runs", "a", "shell", "command", "and", "return", "the", "stdout", "and", "stderr" ]
train
https://github.com/ga4gh/ga4gh-common/blob/ea1b562dce5bf088ac4577b838cfac7745f08346/ga4gh/common/utils.py#L69-L79
ga4gh/ga4gh-common
ga4gh/common/utils.py
getYamlDocument
def getYamlDocument(filePath): """ Return a yaml file's contents as a dictionary """ with open(filePath) as stream: doc = yaml.load(stream) return doc
python
def getYamlDocument(filePath): """ Return a yaml file's contents as a dictionary """ with open(filePath) as stream: doc = yaml.load(stream) return doc
[ "def", "getYamlDocument", "(", "filePath", ")", ":", "with", "open", "(", "filePath", ")", "as", "stream", ":", "doc", "=", "yaml", ".", "load", "(", "stream", ")", "return", "doc" ]
Return a yaml file's contents as a dictionary
[ "Return", "a", "yaml", "file", "s", "contents", "as", "a", "dictionary" ]
train
https://github.com/ga4gh/ga4gh-common/blob/ea1b562dce5bf088ac4577b838cfac7745f08346/ga4gh/common/utils.py#L108-L114
ga4gh/ga4gh-common
ga4gh/common/utils.py
captureOutput
def captureOutput(func, *args, **kwargs): """ Runs the specified function and arguments, and returns the tuple (stdout, stderr) as strings. """ stdout = sys.stdout sys.stdout = StringIO.StringIO() stderr = sys.stderr sys.stderr = StringIO.StringIO() try: func(*args, **kwargs)...
python
def captureOutput(func, *args, **kwargs): """ Runs the specified function and arguments, and returns the tuple (stdout, stderr) as strings. """ stdout = sys.stdout sys.stdout = StringIO.StringIO() stderr = sys.stderr sys.stderr = StringIO.StringIO() try: func(*args, **kwargs)...
[ "def", "captureOutput", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "stdout", "=", "sys", ".", "stdout", "sys", ".", "stdout", "=", "StringIO", ".", "StringIO", "(", ")", "stderr", "=", "sys", ".", "stderr", "sys", ".", "stder...
Runs the specified function and arguments, and returns the tuple (stdout, stderr) as strings.
[ "Runs", "the", "specified", "function", "and", "arguments", "and", "returns", "the", "tuple", "(", "stdout", "stderr", ")", "as", "strings", "." ]
train
https://github.com/ga4gh/ga4gh-common/blob/ea1b562dce5bf088ac4577b838cfac7745f08346/ga4gh/common/utils.py#L117-L135
ga4gh/ga4gh-common
ga4gh/common/utils.py
zipLists
def zipLists(*lists): """ Checks to see if all of the lists are the same length, and throws an AssertionError otherwise. Returns the zipped lists. """ length = len(lists[0]) for i, list_ in enumerate(lists[1:]): if len(list_) != length: msg = "List at index {} has length {} ...
python
def zipLists(*lists): """ Checks to see if all of the lists are the same length, and throws an AssertionError otherwise. Returns the zipped lists. """ length = len(lists[0]) for i, list_ in enumerate(lists[1:]): if len(list_) != length: msg = "List at index {} has length {} ...
[ "def", "zipLists", "(", "*", "lists", ")", ":", "length", "=", "len", "(", "lists", "[", "0", "]", ")", "for", "i", ",", "list_", "in", "enumerate", "(", "lists", "[", "1", ":", "]", ")", ":", "if", "len", "(", "list_", ")", "!=", "length", "...
Checks to see if all of the lists are the same length, and throws an AssertionError otherwise. Returns the zipped lists.
[ "Checks", "to", "see", "if", "all", "of", "the", "lists", "are", "the", "same", "length", "and", "throws", "an", "AssertionError", "otherwise", ".", "Returns", "the", "zipped", "lists", "." ]
train
https://github.com/ga4gh/ga4gh-common/blob/ea1b562dce5bf088ac4577b838cfac7745f08346/ga4gh/common/utils.py#L138-L149
ga4gh/ga4gh-common
ga4gh/common/utils.py
getLinesFromLogFile
def getLinesFromLogFile(stream): """ Returns all lines written to the passed in stream """ stream.flush() stream.seek(0) lines = stream.readlines() return lines
python
def getLinesFromLogFile(stream): """ Returns all lines written to the passed in stream """ stream.flush() stream.seek(0) lines = stream.readlines() return lines
[ "def", "getLinesFromLogFile", "(", "stream", ")", ":", "stream", ".", "flush", "(", ")", "stream", ".", "seek", "(", "0", ")", "lines", "=", "stream", ".", "readlines", "(", ")", "return", "lines" ]
Returns all lines written to the passed in stream
[ "Returns", "all", "lines", "written", "to", "the", "passed", "in", "stream" ]
train
https://github.com/ga4gh/ga4gh-common/blob/ea1b562dce5bf088ac4577b838cfac7745f08346/ga4gh/common/utils.py#L152-L159
ga4gh/ga4gh-common
ga4gh/common/utils.py
getFilePathsWithExtensionsInDirectory
def getFilePathsWithExtensionsInDirectory(dirTree, patterns, sort=True): """ Returns all file paths that match any one of patterns in a file tree with its root at dirTree. Sorts the paths by default. """ filePaths = [] for root, dirs, files in os.walk(dirTree): for filePath in files: ...
python
def getFilePathsWithExtensionsInDirectory(dirTree, patterns, sort=True): """ Returns all file paths that match any one of patterns in a file tree with its root at dirTree. Sorts the paths by default. """ filePaths = [] for root, dirs, files in os.walk(dirTree): for filePath in files: ...
[ "def", "getFilePathsWithExtensionsInDirectory", "(", "dirTree", ",", "patterns", ",", "sort", "=", "True", ")", ":", "filePaths", "=", "[", "]", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "dirTree", ")", ":", "for", "filePath...
Returns all file paths that match any one of patterns in a file tree with its root at dirTree. Sorts the paths by default.
[ "Returns", "all", "file", "paths", "that", "match", "any", "one", "of", "patterns", "in", "a", "file", "tree", "with", "its", "root", "at", "dirTree", ".", "Sorts", "the", "paths", "by", "default", "." ]
train
https://github.com/ga4gh/ga4gh-common/blob/ea1b562dce5bf088ac4577b838cfac7745f08346/ga4gh/common/utils.py#L182-L197
ga4gh/ga4gh-common
ga4gh/common/utils.py
performInDirectory
def performInDirectory(dirPath): """ Change the current working directory to dirPath before performing an operation, then restore the original working directory after """ originalDirectoryPath = os.getcwd() try: os.chdir(dirPath) yield finally: os.chdir(originalDirect...
python
def performInDirectory(dirPath): """ Change the current working directory to dirPath before performing an operation, then restore the original working directory after """ originalDirectoryPath = os.getcwd() try: os.chdir(dirPath) yield finally: os.chdir(originalDirect...
[ "def", "performInDirectory", "(", "dirPath", ")", ":", "originalDirectoryPath", "=", "os", ".", "getcwd", "(", ")", "try", ":", "os", ".", "chdir", "(", "dirPath", ")", "yield", "finally", ":", "os", ".", "chdir", "(", "originalDirectoryPath", ")" ]
Change the current working directory to dirPath before performing an operation, then restore the original working directory after
[ "Change", "the", "current", "working", "directory", "to", "dirPath", "before", "performing", "an", "operation", "then", "restore", "the", "original", "working", "directory", "after" ]
train
https://github.com/ga4gh/ga4gh-common/blob/ea1b562dce5bf088ac4577b838cfac7745f08346/ga4gh/common/utils.py#L339-L349
jmoiron/par2ools
par2ools/par2.py
Par2File.filenames
def filenames(self): """Returns the filenames that this par2 file repairs.""" return [p.name for p in self.packets if isinstance(p, FileDescriptionPacket)]
python
def filenames(self): """Returns the filenames that this par2 file repairs.""" return [p.name for p in self.packets if isinstance(p, FileDescriptionPacket)]
[ "def", "filenames", "(", "self", ")", ":", "return", "[", "p", ".", "name", "for", "p", "in", "self", ".", "packets", "if", "isinstance", "(", "p", ",", "FileDescriptionPacket", ")", "]" ]
Returns the filenames that this par2 file repairs.
[ "Returns", "the", "filenames", "that", "this", "par2", "file", "repairs", "." ]
train
https://github.com/jmoiron/par2ools/blob/3a9a71c8d0cadecb56bff711b2c2db9b3acb496c/par2ools/par2.py#L94-L96
jmoiron/par2ools
par2ools/par2.py
Par2File.related_pars
def related_pars(self): """Returns a list of related par2 files (ones par2 will try to read from to find file recovery blocks). If this par2 file was a file-like object (like a StringIO) without an associated path, return []. Otherwise, the name of this file + associated files are retur...
python
def related_pars(self): """Returns a list of related par2 files (ones par2 will try to read from to find file recovery blocks). If this par2 file was a file-like object (like a StringIO) without an associated path, return []. Otherwise, the name of this file + associated files are retur...
[ "def", "related_pars", "(", "self", ")", ":", "if", "not", "self", ".", "path", ":", "return", "[", "]", "names", "=", "[", "self", ".", "path", "]", "basename", "=", "self", ".", "path", ".", "replace", "(", "'.par2'", ",", "''", ")", ".", "repl...
Returns a list of related par2 files (ones par2 will try to read from to find file recovery blocks). If this par2 file was a file-like object (like a StringIO) without an associated path, return []. Otherwise, the name of this file + associated files are returned.
[ "Returns", "a", "list", "of", "related", "par2", "files", "(", "ones", "par2", "will", "try", "to", "read", "from", "to", "find", "file", "recovery", "blocks", ")", ".", "If", "this", "par2", "file", "was", "a", "file", "-", "like", "object", "(", "l...
train
https://github.com/jmoiron/par2ools/blob/3a9a71c8d0cadecb56bff711b2c2db9b3acb496c/par2ools/par2.py#L98-L108
klahnakoski/pyLibrary
jx_base/domains.py
Domain._set_slots_to_null
def _set_slots_to_null(self, cls): """ WHY ARE SLOTS NOT ACCESIBLE UNTIL WE ASSIGN TO THEM? """ if hasattr(cls, "__slots__"): for s in cls.__slots__: self.__setattr__(s, Null) for b in cls.__bases__: self._set_slots_to_null(b)
python
def _set_slots_to_null(self, cls): """ WHY ARE SLOTS NOT ACCESIBLE UNTIL WE ASSIGN TO THEM? """ if hasattr(cls, "__slots__"): for s in cls.__slots__: self.__setattr__(s, Null) for b in cls.__bases__: self._set_slots_to_null(b)
[ "def", "_set_slots_to_null", "(", "self", ",", "cls", ")", ":", "if", "hasattr", "(", "cls", ",", "\"__slots__\"", ")", ":", "for", "s", "in", "cls", ".", "__slots__", ":", "self", ".", "__setattr__", "(", "s", ",", "Null", ")", "for", "b", "in", "...
WHY ARE SLOTS NOT ACCESIBLE UNTIL WE ASSIGN TO THEM?
[ "WHY", "ARE", "SLOTS", "NOT", "ACCESIBLE", "UNTIL", "WE", "ASSIGN", "TO", "THEM?" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/jx_base/domains.py#L51-L59
erikrose/conway
bin/conway.py
main
def main(): """Play Conway's Game of Life on the terminal.""" def die((x, y)): """Pretend any out-of-bounds cell is dead.""" if 0 <= x < width and 0 <= y < height: return x, y LOAD_FACTOR = 9 # Smaller means more crowded. NUDGING_LOAD_FACTOR = LOAD_FACTOR * 3 # Smaller mea...
python
def main(): """Play Conway's Game of Life on the terminal.""" def die((x, y)): """Pretend any out-of-bounds cell is dead.""" if 0 <= x < width and 0 <= y < height: return x, y LOAD_FACTOR = 9 # Smaller means more crowded. NUDGING_LOAD_FACTOR = LOAD_FACTOR * 3 # Smaller mea...
[ "def", "main", "(", ")", ":", "def", "die", "(", "(", "x", ",", "y", ")", ")", ":", "\"\"\"Pretend any out-of-bounds cell is dead.\"\"\"", "if", "0", "<=", "x", "<", "width", "and", "0", "<=", "y", "<", "height", ":", "return", "x", ",", "y", "LOAD_F...
Play Conway's Game of Life on the terminal.
[ "Play", "Conway", "s", "Game", "of", "Life", "on", "the", "terminal", "." ]
train
https://github.com/erikrose/conway/blob/4c185d5f2d4b942a0710d7593926e7b749b16015/bin/conway.py#L21-L55
erikrose/conway
bin/conway.py
cell_strings
def cell_strings(term): """Return the strings that represent each possible living cell state. Return the most colorful ones the terminal supports. """ num_colors = term.number_of_colors if num_colors >= 16: funcs = term.on_bright_red, term.on_bright_green, term.on_bright_cyan elif num_...
python
def cell_strings(term): """Return the strings that represent each possible living cell state. Return the most colorful ones the terminal supports. """ num_colors = term.number_of_colors if num_colors >= 16: funcs = term.on_bright_red, term.on_bright_green, term.on_bright_cyan elif num_...
[ "def", "cell_strings", "(", "term", ")", ":", "num_colors", "=", "term", ".", "number_of_colors", "if", "num_colors", ">=", "16", ":", "funcs", "=", "term", ".", "on_bright_red", ",", "term", ".", "on_bright_green", ",", "term", ".", "on_bright_cyan", "elif"...
Return the strings that represent each possible living cell state. Return the most colorful ones the terminal supports.
[ "Return", "the", "strings", "that", "represent", "each", "possible", "living", "cell", "state", "." ]
train
https://github.com/erikrose/conway/blob/4c185d5f2d4b942a0710d7593926e7b749b16015/bin/conway.py#L65-L83
erikrose/conway
bin/conway.py
random_board
def random_board(max_x, max_y, load_factor): """Return a random board with given max x and y coords.""" return dict(((randint(0, max_x), randint(0, max_y)), 0) for _ in xrange(int(max_x * max_y / load_factor)))
python
def random_board(max_x, max_y, load_factor): """Return a random board with given max x and y coords.""" return dict(((randint(0, max_x), randint(0, max_y)), 0) for _ in xrange(int(max_x * max_y / load_factor)))
[ "def", "random_board", "(", "max_x", ",", "max_y", ",", "load_factor", ")", ":", "return", "dict", "(", "(", "(", "randint", "(", "0", ",", "max_x", ")", ",", "randint", "(", "0", ",", "max_y", ")", ")", ",", "0", ")", "for", "_", "in", "xrange",...
Return a random board with given max x and y coords.
[ "Return", "a", "random", "board", "with", "given", "max", "x", "and", "y", "coords", "." ]
train
https://github.com/erikrose/conway/blob/4c185d5f2d4b942a0710d7593926e7b749b16015/bin/conway.py#L86-L89
erikrose/conway
bin/conway.py
clear
def clear(board, term, height): """Clear the droppings of the given board.""" for y in xrange(height): print term.move(y, 0) + term.clear_eol,
python
def clear(board, term, height): """Clear the droppings of the given board.""" for y in xrange(height): print term.move(y, 0) + term.clear_eol,
[ "def", "clear", "(", "board", ",", "term", ",", "height", ")", ":", "for", "y", "in", "xrange", "(", "height", ")", ":", "print", "term", ".", "move", "(", "y", ",", "0", ")", "+", "term", ".", "clear_eol", "," ]
Clear the droppings of the given board.
[ "Clear", "the", "droppings", "of", "the", "given", "board", "." ]
train
https://github.com/erikrose/conway/blob/4c185d5f2d4b942a0710d7593926e7b749b16015/bin/conway.py#L92-L95
erikrose/conway
bin/conway.py
draw
def draw(board, term, cells): """Draw a board to the terminal.""" for (x, y), state in board.iteritems(): with term.location(x, y): print cells[state],
python
def draw(board, term, cells): """Draw a board to the terminal.""" for (x, y), state in board.iteritems(): with term.location(x, y): print cells[state],
[ "def", "draw", "(", "board", ",", "term", ",", "cells", ")", ":", "for", "(", "x", ",", "y", ")", ",", "state", "in", "board", ".", "iteritems", "(", ")", ":", "with", "term", ".", "location", "(", "x", ",", "y", ")", ":", "print", "cells", "...
Draw a board to the terminal.
[ "Draw", "a", "board", "to", "the", "terminal", "." ]
train
https://github.com/erikrose/conway/blob/4c185d5f2d4b942a0710d7593926e7b749b16015/bin/conway.py#L98-L102
erikrose/conway
bin/conway.py
next_board
def next_board(board, wrap): """Given a board, return the board one interation later. Adapted from Jack Diedrich's implementation from his 2012 PyCon talk "Stop Writing Classes" :arg wrap: A callable which takes a point and transforms it, for example to wrap to the other edge of the screen. Re...
python
def next_board(board, wrap): """Given a board, return the board one interation later. Adapted from Jack Diedrich's implementation from his 2012 PyCon talk "Stop Writing Classes" :arg wrap: A callable which takes a point and transforms it, for example to wrap to the other edge of the screen. Re...
[ "def", "next_board", "(", "board", ",", "wrap", ")", ":", "new_board", "=", "{", "}", "# We need consider only the points that are alive and their neighbors:", "points_to_recalc", "=", "set", "(", "board", ".", "iterkeys", "(", ")", ")", "|", "set", "(", "chain", ...
Given a board, return the board one interation later. Adapted from Jack Diedrich's implementation from his 2012 PyCon talk "Stop Writing Classes" :arg wrap: A callable which takes a point and transforms it, for example to wrap to the other edge of the screen. Return None to remove a point.
[ "Given", "a", "board", "return", "the", "board", "one", "interation", "later", "." ]
train
https://github.com/erikrose/conway/blob/4c185d5f2d4b942a0710d7593926e7b749b16015/bin/conway.py#L105-L135
erikrose/conway
bin/conway.py
neighbors
def neighbors((x, y)): """Return the (possibly out of bounds) neighbors of a point.""" yield x + 1, y yield x - 1, y yield x, y + 1 yield x, y - 1 yield x + 1, y + 1 yield x + 1, y - 1 yield x - 1, y + 1 yield x - 1, y - 1
python
def neighbors((x, y)): """Return the (possibly out of bounds) neighbors of a point.""" yield x + 1, y yield x - 1, y yield x, y + 1 yield x, y - 1 yield x + 1, y + 1 yield x + 1, y - 1 yield x - 1, y + 1 yield x - 1, y - 1
[ "def", "neighbors", "(", "(", "x", ",", "y", ")", ")", ":", "yield", "x", "+", "1", ",", "y", "yield", "x", "-", "1", ",", "y", "yield", "x", ",", "y", "+", "1", "yield", "x", ",", "y", "-", "1", "yield", "x", "+", "1", ",", "y", "+", ...
Return the (possibly out of bounds) neighbors of a point.
[ "Return", "the", "(", "possibly", "out", "of", "bounds", ")", "neighbors", "of", "a", "point", "." ]
train
https://github.com/erikrose/conway/blob/4c185d5f2d4b942a0710d7593926e7b749b16015/bin/conway.py#L138-L147
erikrose/conway
bin/conway.py
BoredomDetector.is_bored_of
def is_bored_of(self, board): """Return whether the simulation is probably in a loop. This is a stochastic guess. Basically, it detects whether the simulation has had the same number of cells a lot lately. May have false positives (like if you just have a screen full of gliders) or ...
python
def is_bored_of(self, board): """Return whether the simulation is probably in a loop. This is a stochastic guess. Basically, it detects whether the simulation has had the same number of cells a lot lately. May have false positives (like if you just have a screen full of gliders) or ...
[ "def", "is_bored_of", "(", "self", ",", "board", ")", ":", "self", ".", "iteration", "+=", "1", "if", "len", "(", "board", ")", "==", "self", ".", "num", ":", "self", ".", "times", "+=", "1", "is_bored", "=", "self", ".", "times", ">", "self", "....
Return whether the simulation is probably in a loop. This is a stochastic guess. Basically, it detects whether the simulation has had the same number of cells a lot lately. May have false positives (like if you just have a screen full of gliders) or take awhile to catch on sometimes. I'...
[ "Return", "whether", "the", "simulation", "is", "probably", "in", "a", "loop", "." ]
train
https://github.com/erikrose/conway/blob/4c185d5f2d4b942a0710d7593926e7b749b16015/bin/conway.py#L165-L184
openfisca/openfisca-france-indirect-taxation
openfisca_france_indirect_taxation/model/base.py
droit_d_accise
def droit_d_accise(depense, droit_cn, consommation_cn, taux_plein_tva): """ Calcule le montant de droit d'accise sur un volume de dépense payé pour le poste adéquat. """ return depense * ((1 + taux_plein_tva) * droit_cn) / (consommation_cn - (1 + taux_plein_tva) * droit_cn)
python
def droit_d_accise(depense, droit_cn, consommation_cn, taux_plein_tva): """ Calcule le montant de droit d'accise sur un volume de dépense payé pour le poste adéquat. """ return depense * ((1 + taux_plein_tva) * droit_cn) / (consommation_cn - (1 + taux_plein_tva) * droit_cn)
[ "def", "droit_d_accise", "(", "depense", ",", "droit_cn", ",", "consommation_cn", ",", "taux_plein_tva", ")", ":", "return", "depense", "*", "(", "(", "1", "+", "taux_plein_tva", ")", "*", "droit_cn", ")", "/", "(", "consommation_cn", "-", "(", "1", "+", ...
Calcule le montant de droit d'accise sur un volume de dépense payé pour le poste adéquat.
[ "Calcule", "le", "montant", "de", "droit", "d", "accise", "sur", "un", "volume", "de", "dépense", "payé", "pour", "le", "poste", "adéquat", "." ]
train
https://github.com/openfisca/openfisca-france-indirect-taxation/blob/b4bc7da90a1126ebfc3af2c3ec61de5a2b70bb2e/openfisca_france_indirect_taxation/model/base.py#L54-L58
klahnakoski/pyLibrary
mo_threads/queues.py
Queue.add
def add(self, value, timeout=None, force=False): """ :param value: ADDED THE THE QUEUE :param timeout: HOW LONG TO WAIT FOR QUEUE TO NOT BE FULL :param force: ADD TO QUEUE, EVEN IF FULL (USE ONLY WHEN CONSUMER IS RETURNING WORK TO THE QUEUE) :return: self """ w...
python
def add(self, value, timeout=None, force=False): """ :param value: ADDED THE THE QUEUE :param timeout: HOW LONG TO WAIT FOR QUEUE TO NOT BE FULL :param force: ADD TO QUEUE, EVEN IF FULL (USE ONLY WHEN CONSUMER IS RETURNING WORK TO THE QUEUE) :return: self """ w...
[ "def", "add", "(", "self", ",", "value", ",", "timeout", "=", "None", ",", "force", "=", "False", ")", ":", "with", "self", ".", "lock", ":", "if", "value", "is", "THREAD_STOP", ":", "# INSIDE THE lock SO THAT EXITING WILL RELEASE wait()", "self", ".", "queu...
:param value: ADDED THE THE QUEUE :param timeout: HOW LONG TO WAIT FOR QUEUE TO NOT BE FULL :param force: ADD TO QUEUE, EVEN IF FULL (USE ONLY WHEN CONSUMER IS RETURNING WORK TO THE QUEUE) :return: self
[ ":", "param", "value", ":", "ADDED", "THE", "THE", "QUEUE", ":", "param", "timeout", ":", "HOW", "LONG", "TO", "WAIT", "FOR", "QUEUE", "TO", "NOT", "BE", "FULL", ":", "param", "force", ":", "ADD", "TO", "QUEUE", "EVEN", "IF", "FULL", "(", "USE", "O...
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_threads/queues.py#L72-L96
klahnakoski/pyLibrary
mo_threads/queues.py
Queue.push
def push(self, value): """ SNEAK value TO FRONT OF THE QUEUE """ if self.closed and not self.allow_add_after_close: Log.error("Do not push to closed queue") with self.lock: self._wait_for_queue_space() if not self.closed: self....
python
def push(self, value): """ SNEAK value TO FRONT OF THE QUEUE """ if self.closed and not self.allow_add_after_close: Log.error("Do not push to closed queue") with self.lock: self._wait_for_queue_space() if not self.closed: self....
[ "def", "push", "(", "self", ",", "value", ")", ":", "if", "self", ".", "closed", "and", "not", "self", ".", "allow_add_after_close", ":", "Log", ".", "error", "(", "\"Do not push to closed queue\"", ")", "with", "self", ".", "lock", ":", "self", ".", "_w...
SNEAK value TO FRONT OF THE QUEUE
[ "SNEAK", "value", "TO", "FRONT", "OF", "THE", "QUEUE" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_threads/queues.py#L98-L109
klahnakoski/pyLibrary
mo_threads/queues.py
Queue.pop_message
def pop_message(self, till=None): """ RETURN TUPLE (message, payload) CALLER IS RESPONSIBLE FOR CALLING message.delete() WHEN DONE DUMMY IMPLEMENTATION FOR DEBUGGING """ if till is not None and not isinstance(till, Signal): Log.error("Expecting a signal") ret...
python
def pop_message(self, till=None): """ RETURN TUPLE (message, payload) CALLER IS RESPONSIBLE FOR CALLING message.delete() WHEN DONE DUMMY IMPLEMENTATION FOR DEBUGGING """ if till is not None and not isinstance(till, Signal): Log.error("Expecting a signal") ret...
[ "def", "pop_message", "(", "self", ",", "till", "=", "None", ")", ":", "if", "till", "is", "not", "None", "and", "not", "isinstance", "(", "till", ",", "Signal", ")", ":", "Log", ".", "error", "(", "\"Expecting a signal\"", ")", "return", "Null", ",", ...
RETURN TUPLE (message, payload) CALLER IS RESPONSIBLE FOR CALLING message.delete() WHEN DONE DUMMY IMPLEMENTATION FOR DEBUGGING
[ "RETURN", "TUPLE", "(", "message", "payload", ")", "CALLER", "IS", "RESPONSIBLE", "FOR", "CALLING", "message", ".", "delete", "()", "WHEN", "DONE", "DUMMY", "IMPLEMENTATION", "FOR", "DEBUGGING" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_threads/queues.py#L111-L119
klahnakoski/pyLibrary
mo_threads/queues.py
Queue._wait_for_queue_space
def _wait_for_queue_space(self, timeout=DEFAULT_WAIT_TIME): """ EXPECT THE self.lock TO BE HAD, WAITS FOR self.queue TO HAVE A LITTLE SPACE """ wait_time = 5 (DEBUG and len(self.queue) > 1 * 1000 * 1000) and Log.warning("Queue {{name}} has over a million items") now = t...
python
def _wait_for_queue_space(self, timeout=DEFAULT_WAIT_TIME): """ EXPECT THE self.lock TO BE HAD, WAITS FOR self.queue TO HAVE A LITTLE SPACE """ wait_time = 5 (DEBUG and len(self.queue) > 1 * 1000 * 1000) and Log.warning("Queue {{name}} has over a million items") now = t...
[ "def", "_wait_for_queue_space", "(", "self", ",", "timeout", "=", "DEFAULT_WAIT_TIME", ")", ":", "wait_time", "=", "5", "(", "DEBUG", "and", "len", "(", "self", ".", "queue", ")", ">", "1", "*", "1000", "*", "1000", ")", "and", "Log", ".", "warning", ...
EXPECT THE self.lock TO BE HAD, WAITS FOR self.queue TO HAVE A LITTLE SPACE
[ "EXPECT", "THE", "self", ".", "lock", "TO", "BE", "HAD", "WAITS", "FOR", "self", ".", "queue", "TO", "HAVE", "A", "LITTLE", "SPACE" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_threads/queues.py#L144-L178
klahnakoski/pyLibrary
mo_threads/queues.py
Queue.pop_all
def pop_all(self): """ NON-BLOCKING POP ALL IN QUEUE, IF ANY """ with self.lock: output = list(self.queue) self.queue.clear() return output
python
def pop_all(self): """ NON-BLOCKING POP ALL IN QUEUE, IF ANY """ with self.lock: output = list(self.queue) self.queue.clear() return output
[ "def", "pop_all", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "output", "=", "list", "(", "self", ".", "queue", ")", "self", ".", "queue", ".", "clear", "(", ")", "return", "output" ]
NON-BLOCKING POP ALL IN QUEUE, IF ANY
[ "NON", "-", "BLOCKING", "POP", "ALL", "IN", "QUEUE", "IF", "ANY" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_threads/queues.py#L214-L222
klahnakoski/pyLibrary
mo_threads/queues.py
Queue.pop_one
def pop_one(self): """ NON-BLOCKING POP IN QUEUE, IF ANY """ with self.lock: if self.closed: return [THREAD_STOP] elif not self.queue: return None else: v =self.queue.pop() if v is THREAD_...
python
def pop_one(self): """ NON-BLOCKING POP IN QUEUE, IF ANY """ with self.lock: if self.closed: return [THREAD_STOP] elif not self.queue: return None else: v =self.queue.pop() if v is THREAD_...
[ "def", "pop_one", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "if", "self", ".", "closed", ":", "return", "[", "THREAD_STOP", "]", "elif", "not", "self", ".", "queue", ":", "return", "None", "else", ":", "v", "=", "self", ".", "queue",...
NON-BLOCKING POP IN QUEUE, IF ANY
[ "NON", "-", "BLOCKING", "POP", "IN", "QUEUE", "IF", "ANY" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_threads/queues.py#L224-L237
klahnakoski/pyLibrary
mo_threads/queues.py
PriorityQueue.pop
def pop(self, till=None, priority=None): """ WAIT FOR NEXT ITEM ON THE QUEUE RETURN THREAD_STOP IF QUEUE IS CLOSED RETURN None IF till IS REACHED AND QUEUE IS STILL EMPTY :param till: A `Signal` to stop waiting and return None :return: A value, or a THREAD_STOP or None...
python
def pop(self, till=None, priority=None): """ WAIT FOR NEXT ITEM ON THE QUEUE RETURN THREAD_STOP IF QUEUE IS CLOSED RETURN None IF till IS REACHED AND QUEUE IS STILL EMPTY :param till: A `Signal` to stop waiting and return None :return: A value, or a THREAD_STOP or None...
[ "def", "pop", "(", "self", ",", "till", "=", "None", ",", "priority", "=", "None", ")", ":", "if", "till", "is", "not", "None", "and", "not", "isinstance", "(", "till", ",", "Signal", ")", ":", "Log", ".", "error", "(", "\"expecting a signal\"", ")",...
WAIT FOR NEXT ITEM ON THE QUEUE RETURN THREAD_STOP IF QUEUE IS CLOSED RETURN None IF till IS REACHED AND QUEUE IS STILL EMPTY :param till: A `Signal` to stop waiting and return None :return: A value, or a THREAD_STOP or None
[ "WAIT", "FOR", "NEXT", "ITEM", "ON", "THE", "QUEUE", "RETURN", "THREAD_STOP", "IF", "QUEUE", "IS", "CLOSED", "RETURN", "None", "IF", "till", "IS", "REACHED", "AND", "QUEUE", "IS", "STILL", "EMPTY" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_threads/queues.py#L325-L351
klahnakoski/pyLibrary
mo_threads/queues.py
PriorityQueue.pop_all
def pop_all(self, priority=None): """ NON-BLOCKING POP ALL IN QUEUE, IF ANY """ output = [] with self.lock: if not priority: priority = self.highest_entry() if priority: output = list(self.queue[priority].queue) ...
python
def pop_all(self, priority=None): """ NON-BLOCKING POP ALL IN QUEUE, IF ANY """ output = [] with self.lock: if not priority: priority = self.highest_entry() if priority: output = list(self.queue[priority].queue) ...
[ "def", "pop_all", "(", "self", ",", "priority", "=", "None", ")", ":", "output", "=", "[", "]", "with", "self", ".", "lock", ":", "if", "not", "priority", ":", "priority", "=", "self", ".", "highest_entry", "(", ")", "if", "priority", ":", "output", ...
NON-BLOCKING POP ALL IN QUEUE, IF ANY
[ "NON", "-", "BLOCKING", "POP", "ALL", "IN", "QUEUE", "IF", "ANY" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_threads/queues.py#L353-L364
klahnakoski/pyLibrary
mo_threads/queues.py
PriorityQueue.pop_all_queues
def pop_all_queues(self): """ NON-BLOCKING POP ALL IN QUEUE, IF ANY """ output = [] with self.lock: for q in self.queue: output.extend(list(q.queue)) q.queue.clear() return output
python
def pop_all_queues(self): """ NON-BLOCKING POP ALL IN QUEUE, IF ANY """ output = [] with self.lock: for q in self.queue: output.extend(list(q.queue)) q.queue.clear() return output
[ "def", "pop_all_queues", "(", "self", ")", ":", "output", "=", "[", "]", "with", "self", ".", "lock", ":", "for", "q", "in", "self", ".", "queue", ":", "output", ".", "extend", "(", "list", "(", "q", ".", "queue", ")", ")", "q", ".", "queue", "...
NON-BLOCKING POP ALL IN QUEUE, IF ANY
[ "NON", "-", "BLOCKING", "POP", "ALL", "IN", "QUEUE", "IF", "ANY" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_threads/queues.py#L366-L376
klahnakoski/pyLibrary
mo_threads/queues.py
PriorityQueue.pop_one
def pop_one(self, priority=None): """ NON-BLOCKING POP IN QUEUE, IF ANY """ with self.lock: if not priority: priority = self.highest_entry() if self.closed: return [THREAD_STOP] elif not self.queue: retur...
python
def pop_one(self, priority=None): """ NON-BLOCKING POP IN QUEUE, IF ANY """ with self.lock: if not priority: priority = self.highest_entry() if self.closed: return [THREAD_STOP] elif not self.queue: retur...
[ "def", "pop_one", "(", "self", ",", "priority", "=", "None", ")", ":", "with", "self", ".", "lock", ":", "if", "not", "priority", ":", "priority", "=", "self", ".", "highest_entry", "(", ")", "if", "self", ".", "closed", ":", "return", "[", "THREAD_S...
NON-BLOCKING POP IN QUEUE, IF ANY
[ "NON", "-", "BLOCKING", "POP", "IN", "QUEUE", "IF", "ANY" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_threads/queues.py#L378-L393
klahnakoski/pyLibrary
pyLibrary/env/typed_inserter.py
TypedInserter.typed_encode
def typed_encode(self, r): """ :param record: expecting id and value properties :return: dict with id and json properties """ try: value = r.get('value') if "json" in r: value = json2value(r["json"]) elif is_data(value) or val...
python
def typed_encode(self, r): """ :param record: expecting id and value properties :return: dict with id and json properties """ try: value = r.get('value') if "json" in r: value = json2value(r["json"]) elif is_data(value) or val...
[ "def", "typed_encode", "(", "self", ",", "r", ")", ":", "try", ":", "value", "=", "r", ".", "get", "(", "'value'", ")", "if", "\"json\"", "in", "r", ":", "value", "=", "json2value", "(", "r", "[", "\"json\"", "]", ")", "elif", "is_data", "(", "va...
:param record: expecting id and value properties :return: dict with id and json properties
[ ":", "param", "record", ":", "expecting", "id", "and", "value", "properties", ":", "return", ":", "dict", "with", "id", "and", "json", "properties" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/pyLibrary/env/typed_inserter.py#L39-L91
klahnakoski/pyLibrary
mo_math/randoms.py
Random.weight
def weight(weights): """ RETURN RANDOM INDEX INTO WEIGHT ARRAY, GIVEN WEIGHTS """ total = sum(weights) p = SEED.random() acc = 0 for i, w in enumerate(weights): acc += w / total if p < acc: return i return len(weigh...
python
def weight(weights): """ RETURN RANDOM INDEX INTO WEIGHT ARRAY, GIVEN WEIGHTS """ total = sum(weights) p = SEED.random() acc = 0 for i, w in enumerate(weights): acc += w / total if p < acc: return i return len(weigh...
[ "def", "weight", "(", "weights", ")", ":", "total", "=", "sum", "(", "weights", ")", "p", "=", "SEED", ".", "random", "(", ")", "acc", "=", "0", "for", "i", ",", "w", "in", "enumerate", "(", "weights", ")", ":", "acc", "+=", "w", "/", "total", ...
RETURN RANDOM INDEX INTO WEIGHT ARRAY, GIVEN WEIGHTS
[ "RETURN", "RANDOM", "INDEX", "INTO", "WEIGHT", "ARRAY", "GIVEN", "WEIGHTS" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_math/randoms.py#L71-L83
klahnakoski/pyLibrary
mo_math/vendor/aespython/aes_cipher.py
AESCipher.cipher_block
def cipher_block (self, state): """Perform AES block cipher on input""" # PKCS7 Padding state=state+[16-len(state)]*(16-len(state))# Fails test if it changes the input with += self._add_round_key(state, 0) for i in range(1, self._Nr): self._sub_bytes(state) ...
python
def cipher_block (self, state): """Perform AES block cipher on input""" # PKCS7 Padding state=state+[16-len(state)]*(16-len(state))# Fails test if it changes the input with += self._add_round_key(state, 0) for i in range(1, self._Nr): self._sub_bytes(state) ...
[ "def", "cipher_block", "(", "self", ",", "state", ")", ":", "# PKCS7 Padding", "state", "=", "state", "+", "[", "16", "-", "len", "(", "state", ")", "]", "*", "(", "16", "-", "len", "(", "state", ")", ")", "# Fails test if it changes the input with +=", ...
Perform AES block cipher on input
[ "Perform", "AES", "block", "cipher", "on", "input" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_math/vendor/aespython/aes_cipher.py#L92-L108
klahnakoski/pyLibrary
mo_math/vendor/aespython/aes_cipher.py
AESCipher.decipher_block
def decipher_block (self, state): """Perform AES block decipher on input""" if len(state) != 16: Log.error(u"Expecting block of 16") self._add_round_key(state, self._Nr) for i in range(self._Nr - 1, 0, -1): self._i_shift_rows(state) self._i_sub_bytes...
python
def decipher_block (self, state): """Perform AES block decipher on input""" if len(state) != 16: Log.error(u"Expecting block of 16") self._add_round_key(state, self._Nr) for i in range(self._Nr - 1, 0, -1): self._i_shift_rows(state) self._i_sub_bytes...
[ "def", "decipher_block", "(", "self", ",", "state", ")", ":", "if", "len", "(", "state", ")", "!=", "16", ":", "Log", ".", "error", "(", "u\"Expecting block of 16\"", ")", "self", ".", "_add_round_key", "(", "state", ",", "self", ".", "_Nr", ")", "for"...
Perform AES block decipher on input
[ "Perform", "AES", "block", "decipher", "on", "input" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_math/vendor/aespython/aes_cipher.py#L110-L126
inveniosoftware/invenio-collections
invenio_collections/cli.py
dry_run
def dry_run(func): """Dry run: simulate sql execution.""" @wraps(func) def inner(dry_run, *args, **kwargs): ret = func(dry_run=dry_run, *args, **kwargs) if not dry_run: db.session.commit() else: db.session.rollback() return ret return inner
python
def dry_run(func): """Dry run: simulate sql execution.""" @wraps(func) def inner(dry_run, *args, **kwargs): ret = func(dry_run=dry_run, *args, **kwargs) if not dry_run: db.session.commit() else: db.session.rollback() return ret return inner
[ "def", "dry_run", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "inner", "(", "dry_run", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "func", "(", "dry_run", "=", "dry_run", ",", "*", "args", ",", "*", "*", ...
Dry run: simulate sql execution.
[ "Dry", "run", ":", "simulate", "sql", "execution", "." ]
train
https://github.com/inveniosoftware/invenio-collections/blob/f3adca45c6d00a4dbf1f48fd501e8a68fe347f2f/invenio_collections/cli.py#L41-L51
inveniosoftware/invenio-collections
invenio_collections/cli.py
tree
def tree(names): """Show the tree of the collection(s) specified.""" # query query = Collection.query if names: query = query.filter(Collection.name.in_(names)) else: query = query.filter(Collection.level == 1) # print tree tr = LeftAligned(traverse=AttributeTraversal()) ...
python
def tree(names): """Show the tree of the collection(s) specified.""" # query query = Collection.query if names: query = query.filter(Collection.name.in_(names)) else: query = query.filter(Collection.level == 1) # print tree tr = LeftAligned(traverse=AttributeTraversal()) ...
[ "def", "tree", "(", "names", ")", ":", "# query", "query", "=", "Collection", ".", "query", "if", "names", ":", "query", "=", "query", ".", "filter", "(", "Collection", ".", "name", ".", "in_", "(", "names", ")", ")", "else", ":", "query", "=", "qu...
Show the tree of the collection(s) specified.
[ "Show", "the", "tree", "of", "the", "collection", "(", "s", ")", "specified", "." ]
train
https://github.com/inveniosoftware/invenio-collections/blob/f3adca45c6d00a4dbf1f48fd501e8a68fe347f2f/invenio_collections/cli.py#L104-L115
inveniosoftware/invenio-collections
invenio_collections/cli.py
path
def path(name): """Print path to root.""" try: coll = Collection.query.filter(Collection.name == name).one() tr = LeftAligned( traverse=CollTraversalPathToRoot(coll.path_to_root().all())) click.echo(tr(coll)) except NoResultFound: raise click.UsageError('Collectio...
python
def path(name): """Print path to root.""" try: coll = Collection.query.filter(Collection.name == name).one() tr = LeftAligned( traverse=CollTraversalPathToRoot(coll.path_to_root().all())) click.echo(tr(coll)) except NoResultFound: raise click.UsageError('Collectio...
[ "def", "path", "(", "name", ")", ":", "try", ":", "coll", "=", "Collection", ".", "query", ".", "filter", "(", "Collection", ".", "name", "==", "name", ")", ".", "one", "(", ")", "tr", "=", "LeftAligned", "(", "traverse", "=", "CollTraversalPathToRoot"...
Print path to root.
[ "Print", "path", "to", "root", "." ]
train
https://github.com/inveniosoftware/invenio-collections/blob/f3adca45c6d00a4dbf1f48fd501e8a68fe347f2f/invenio_collections/cli.py#L121-L129
inveniosoftware/invenio-collections
invenio_collections/cli.py
create
def create(name, dry_run, verbose, query=None, parent=None): """Create new collection.""" if parent is not None: parent = Collection.query.filter_by(name=parent).one().id collection = Collection(name=name, dbquery=query, parent_id=parent) db.session.add(collection) if verbose: click....
python
def create(name, dry_run, verbose, query=None, parent=None): """Create new collection.""" if parent is not None: parent = Collection.query.filter_by(name=parent).one().id collection = Collection(name=name, dbquery=query, parent_id=parent) db.session.add(collection) if verbose: click....
[ "def", "create", "(", "name", ",", "dry_run", ",", "verbose", ",", "query", "=", "None", ",", "parent", "=", "None", ")", ":", "if", "parent", "is", "not", "None", ":", "parent", "=", "Collection", ".", "query", ".", "filter_by", "(", "name", "=", ...
Create new collection.
[ "Create", "new", "collection", "." ]
train
https://github.com/inveniosoftware/invenio-collections/blob/f3adca45c6d00a4dbf1f48fd501e8a68fe347f2f/invenio_collections/cli.py#L142-L149
inveniosoftware/invenio-collections
invenio_collections/cli.py
delete
def delete(name, dry_run, verbose): """Delete a collection.""" collection = Collection.query.filter_by(name=name).one() if verbose: tr = LeftAligned(traverse=AttributeTraversal()) click.secho(tr(collection), fg='red') db.session.delete(collection)
python
def delete(name, dry_run, verbose): """Delete a collection.""" collection = Collection.query.filter_by(name=name).one() if verbose: tr = LeftAligned(traverse=AttributeTraversal()) click.secho(tr(collection), fg='red') db.session.delete(collection)
[ "def", "delete", "(", "name", ",", "dry_run", ",", "verbose", ")", ":", "collection", "=", "Collection", ".", "query", ".", "filter_by", "(", "name", "=", "name", ")", ".", "one", "(", ")", "if", "verbose", ":", "tr", "=", "LeftAligned", "(", "traver...
Delete a collection.
[ "Delete", "a", "collection", "." ]
train
https://github.com/inveniosoftware/invenio-collections/blob/f3adca45c6d00a4dbf1f48fd501e8a68fe347f2f/invenio_collections/cli.py#L158-L164
inveniosoftware/invenio-collections
invenio_collections/cli.py
query
def query(name): """Print the collection query.""" collection = Collection.query.filter_by(name=name).one() click.echo(collection.dbquery)
python
def query(name): """Print the collection query.""" collection = Collection.query.filter_by(name=name).one() click.echo(collection.dbquery)
[ "def", "query", "(", "name", ")", ":", "collection", "=", "Collection", ".", "query", ".", "filter_by", "(", "name", "=", "name", ")", ".", "one", "(", ")", "click", ".", "echo", "(", "collection", ".", "dbquery", ")" ]
Print the collection query.
[ "Print", "the", "collection", "query", "." ]
train
https://github.com/inveniosoftware/invenio-collections/blob/f3adca45c6d00a4dbf1f48fd501e8a68fe347f2f/invenio_collections/cli.py#L170-L173
inveniosoftware/invenio-collections
invenio_collections/cli.py
attach
def attach(names, parent, dry_run, verbose): """Attach collection(s) to a parent.""" parent = Collection.query.filter_by(name=parent).one() collections = Collection.query.filter(Collection.name.in_(names)).all() for collection in collections: collection.move_inside(parent.id) if verbose:...
python
def attach(names, parent, dry_run, verbose): """Attach collection(s) to a parent.""" parent = Collection.query.filter_by(name=parent).one() collections = Collection.query.filter(Collection.name.in_(names)).all() for collection in collections: collection.move_inside(parent.id) if verbose:...
[ "def", "attach", "(", "names", ",", "parent", ",", "dry_run", ",", "verbose", ")", ":", "parent", "=", "Collection", ".", "query", ".", "filter_by", "(", "name", "=", "parent", ")", ".", "one", "(", ")", "collections", "=", "Collection", ".", "query", ...
Attach collection(s) to a parent.
[ "Attach", "collection", "(", "s", ")", "to", "a", "parent", "." ]
train
https://github.com/inveniosoftware/invenio-collections/blob/f3adca45c6d00a4dbf1f48fd501e8a68fe347f2f/invenio_collections/cli.py#L183-L193
inveniosoftware/invenio-collections
invenio_collections/cli.py
StyleMixin.get_text
def get_text(self, node): """Get node text representation.""" return click.style( repr(node), fg='green' if node.level > 1 else 'red' )
python
def get_text(self, node): """Get node text representation.""" return click.style( repr(node), fg='green' if node.level > 1 else 'red' )
[ "def", "get_text", "(", "self", ",", "node", ")", ":", "return", "click", ".", "style", "(", "repr", "(", "node", ")", ",", "fg", "=", "'green'", "if", "node", ".", "level", ">", "1", "else", "'red'", ")" ]
Get node text representation.
[ "Get", "node", "text", "representation", "." ]
train
https://github.com/inveniosoftware/invenio-collections/blob/f3adca45c6d00a4dbf1f48fd501e8a68fe347f2f/invenio_collections/cli.py#L57-L61
inveniosoftware/invenio-collections
invenio_collections/cli.py
CollTraversalPathToRoot.get_children
def get_children(self, node): """Get children.""" # if node in self.nodes: try: index = self.nodes.index(node) + 1 return [self.nodes[index]] except IndexError: return []
python
def get_children(self, node): """Get children.""" # if node in self.nodes: try: index = self.nodes.index(node) + 1 return [self.nodes[index]] except IndexError: return []
[ "def", "get_children", "(", "self", ",", "node", ")", ":", "# if node in self.nodes:", "try", ":", "index", "=", "self", ".", "nodes", ".", "index", "(", "node", ")", "+", "1", "return", "[", "self", ".", "nodes", "[", "index", "]", "]", "except", "...
Get children.
[ "Get", "children", "." ]
train
https://github.com/inveniosoftware/invenio-collections/blob/f3adca45c6d00a4dbf1f48fd501e8a68fe347f2f/invenio_collections/cli.py#L73-L80
Galarzaa90/tibia.py
cli.py
cli_char
def cli_char(name, tibiadata, json): """Displays information about a Tibia character.""" name = " ".join(name) char = _fetch_and_parse(Character.get_url, Character.from_content, Character.get_url_tibiadata, Character.from_tibiadata, tibiadata, name) ...
python
def cli_char(name, tibiadata, json): """Displays information about a Tibia character.""" name = " ".join(name) char = _fetch_and_parse(Character.get_url, Character.from_content, Character.get_url_tibiadata, Character.from_tibiadata, tibiadata, name) ...
[ "def", "cli_char", "(", "name", ",", "tibiadata", ",", "json", ")", ":", "name", "=", "\" \"", ".", "join", "(", "name", ")", "char", "=", "_fetch_and_parse", "(", "Character", ".", "get_url", ",", "Character", ".", "from_content", ",", "Character", ".",...
Displays information about a Tibia character.
[ "Displays", "information", "about", "a", "Tibia", "character", "." ]
train
https://github.com/Galarzaa90/tibia.py/blob/02ba1a8f1e18177ef5c7dcd44affc8d761d59e12/cli.py#L45-L54
Galarzaa90/tibia.py
cli.py
cli_guild
def cli_guild(name, tibiadata, json): """Displays information about a Tibia guild.""" name = " ".join(name) guild = _fetch_and_parse(Guild.get_url, Guild.from_content, Guild.get_url_tibiadata, Guild.from_tibiadata, tibiadata, name) if json and gu...
python
def cli_guild(name, tibiadata, json): """Displays information about a Tibia guild.""" name = " ".join(name) guild = _fetch_and_parse(Guild.get_url, Guild.from_content, Guild.get_url_tibiadata, Guild.from_tibiadata, tibiadata, name) if json and gu...
[ "def", "cli_guild", "(", "name", ",", "tibiadata", ",", "json", ")", ":", "name", "=", "\" \"", ".", "join", "(", "name", ")", "guild", "=", "_fetch_and_parse", "(", "Guild", ".", "get_url", ",", "Guild", ".", "from_content", ",", "Guild", ".", "get_ur...
Displays information about a Tibia guild.
[ "Displays", "information", "about", "a", "Tibia", "guild", "." ]
train
https://github.com/Galarzaa90/tibia.py/blob/02ba1a8f1e18177ef5c7dcd44affc8d761d59e12/cli.py#L61-L70
Galarzaa90/tibia.py
cli.py
cli_guilds
def cli_guilds(world, tibiadata, json): """Displays the list of guilds for a specific world""" world = " ".join(world) guilds = _fetch_and_parse(ListedGuild.get_world_list_url, ListedGuild.list_from_content, ListedGuild.get_world_list_url_tibiadata, ListedGuild.list_from_tibiad...
python
def cli_guilds(world, tibiadata, json): """Displays the list of guilds for a specific world""" world = " ".join(world) guilds = _fetch_and_parse(ListedGuild.get_world_list_url, ListedGuild.list_from_content, ListedGuild.get_world_list_url_tibiadata, ListedGuild.list_from_tibiad...
[ "def", "cli_guilds", "(", "world", ",", "tibiadata", ",", "json", ")", ":", "world", "=", "\" \"", ".", "join", "(", "world", ")", "guilds", "=", "_fetch_and_parse", "(", "ListedGuild", ".", "get_world_list_url", ",", "ListedGuild", ".", "list_from_content", ...
Displays the list of guilds for a specific world
[ "Displays", "the", "list", "of", "guilds", "for", "a", "specific", "world" ]
train
https://github.com/Galarzaa90/tibia.py/blob/02ba1a8f1e18177ef5c7dcd44affc8d761d59e12/cli.py#L77-L87
ambitioninc/django-entity-event
entity_event/models.py
_unseen_event_ids
def _unseen_event_ids(medium): """ Return all events that have not been seen on this medium. """ query = ''' SELECT event.id FROM entity_event_event AS event LEFT OUTER JOIN (SELECT * FROM entity_event_eventseen AS seen WHERE seen.medium_...
python
def _unseen_event_ids(medium): """ Return all events that have not been seen on this medium. """ query = ''' SELECT event.id FROM entity_event_event AS event LEFT OUTER JOIN (SELECT * FROM entity_event_eventseen AS seen WHERE seen.medium_...
[ "def", "_unseen_event_ids", "(", "medium", ")", ":", "query", "=", "'''\n SELECT event.id\n FROM entity_event_event AS event\n LEFT OUTER JOIN (SELECT *\n FROM entity_event_eventseen AS seen\n WHERE seen.medium_id=%s) AS eventseen\n ...
Return all events that have not been seen on this medium.
[ "Return", "all", "events", "that", "have", "not", "been", "seen", "on", "this", "medium", "." ]
train
https://github.com/ambitioninc/django-entity-event/blob/70f50df133e42a7bf38d0f07fccc6d2890e5fd12/entity_event/models.py#L1191-L1206
ambitioninc/django-entity-event
entity_event/models.py
EventQuerySet.mark_seen
def mark_seen(self, medium): """ Creates EventSeen objects for the provided medium for every event in the queryset. Creating these EventSeen objects ensures they will not be returned when passing ``seen=False`` to any of the medium event retrieval functions, ``events``, ...
python
def mark_seen(self, medium): """ Creates EventSeen objects for the provided medium for every event in the queryset. Creating these EventSeen objects ensures they will not be returned when passing ``seen=False`` to any of the medium event retrieval functions, ``events``, ...
[ "def", "mark_seen", "(", "self", ",", "medium", ")", ":", "EventSeen", ".", "objects", ".", "bulk_create", "(", "[", "EventSeen", "(", "event", "=", "event", ",", "medium", "=", "medium", ")", "for", "event", "in", "self", "]", ")" ]
Creates EventSeen objects for the provided medium for every event in the queryset. Creating these EventSeen objects ensures they will not be returned when passing ``seen=False`` to any of the medium event retrieval functions, ``events``, ``entity_events``, or ``events_targets``.
[ "Creates", "EventSeen", "objects", "for", "the", "provided", "medium", "for", "every", "event", "in", "the", "queryset", "." ]
train
https://github.com/ambitioninc/django-entity-event/blob/70f50df133e42a7bf38d0f07fccc6d2890e5fd12/entity_event/models.py#L866-L878
ambitioninc/django-entity-event
entity_event/models.py
EventManager.create_event
def create_event(self, actors=None, ignore_duplicates=False, **kwargs): """ Create events with actors. This method can be used in place of ``Event.objects.create`` to create events, and the appropriate actors. It takes all the same keywords as ``Event.objects.create`` for the ev...
python
def create_event(self, actors=None, ignore_duplicates=False, **kwargs): """ Create events with actors. This method can be used in place of ``Event.objects.create`` to create events, and the appropriate actors. It takes all the same keywords as ``Event.objects.create`` for the ev...
[ "def", "create_event", "(", "self", ",", "actors", "=", "None", ",", "ignore_duplicates", "=", "False", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'actors'", "]", "=", "actors", "kwargs", "[", "'ignore_duplicates'", "]", "=", "ignore_duplicates", "...
Create events with actors. This method can be used in place of ``Event.objects.create`` to create events, and the appropriate actors. It takes all the same keywords as ``Event.objects.create`` for the event creation, but additionally takes a list of actors, and can be told to no...
[ "Create", "events", "with", "actors", "." ]
train
https://github.com/ambitioninc/django-entity-event/blob/70f50df133e42a7bf38d0f07fccc6d2890e5fd12/entity_event/models.py#L926-L988
ambitioninc/django-entity-event
entity_event/models.py
EventManager.create_events
def create_events(self, kwargs_list): """ Create events in bulk to save on queries. Each element in the kwargs list should be a dict with the same set of arguments you would normally pass to create_event :param kwargs_list: list of kwargs dicts :return: list of Event """ ...
python
def create_events(self, kwargs_list): """ Create events in bulk to save on queries. Each element in the kwargs list should be a dict with the same set of arguments you would normally pass to create_event :param kwargs_list: list of kwargs dicts :return: list of Event """ ...
[ "def", "create_events", "(", "self", ",", "kwargs_list", ")", ":", "# Build map of uuid to event info", "uuid_map", "=", "{", "kwargs", ".", "get", "(", "'uuid'", ",", "''", ")", ":", "{", "'actors'", ":", "kwargs", ".", "pop", "(", "'actors'", ",", "[", ...
Create events in bulk to save on queries. Each element in the kwargs list should be a dict with the same set of arguments you would normally pass to create_event :param kwargs_list: list of kwargs dicts :return: list of Event
[ "Create", "events", "in", "bulk", "to", "save", "on", "queries", ".", "Each", "element", "in", "the", "kwargs", "list", "should", "be", "a", "dict", "with", "the", "same", "set", "of", "arguments", "you", "would", "normally", "pass", "to", "create_event", ...
train
https://github.com/ambitioninc/django-entity-event/blob/70f50df133e42a7bf38d0f07fccc6d2890e5fd12/entity_event/models.py#L990-L1036
klahnakoski/pyLibrary
mo_graphs/paths.py
Path.right
def right(self, num=None): """ WITH SLICES BEING FLAT, WE NEED A SIMPLE WAY TO SLICE FROM THE RIGHT [-num:] """ if num == None: return self.last.node if num <= 0: return [] if not self.list: self._build_list() return self.list[...
python
def right(self, num=None): """ WITH SLICES BEING FLAT, WE NEED A SIMPLE WAY TO SLICE FROM THE RIGHT [-num:] """ if num == None: return self.last.node if num <= 0: return [] if not self.list: self._build_list() return self.list[...
[ "def", "right", "(", "self", ",", "num", "=", "None", ")", ":", "if", "num", "==", "None", ":", "return", "self", ".", "last", ".", "node", "if", "num", "<=", "0", ":", "return", "[", "]", "if", "not", "self", ".", "list", ":", "self", ".", "...
WITH SLICES BEING FLAT, WE NEED A SIMPLE WAY TO SLICE FROM THE RIGHT [-num:]
[ "WITH", "SLICES", "BEING", "FLAT", "WE", "NEED", "A", "SIMPLE", "WAY", "TO", "SLICE", "FROM", "THE", "RIGHT", "[", "-", "num", ":", "]" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_graphs/paths.py#L91-L102
klahnakoski/pyLibrary
mo_graphs/paths.py
Path.not_right
def not_right(self, num): """ WITH SLICES BEING FLAT, WE NEED A SIMPLE WAY TO SLICE FROM THE LEFT [:-num:] """ if not self.list: self._build_list() if num == None: return self.list[:-1:] if num <= 0: return [] return self.list...
python
def not_right(self, num): """ WITH SLICES BEING FLAT, WE NEED A SIMPLE WAY TO SLICE FROM THE LEFT [:-num:] """ if not self.list: self._build_list() if num == None: return self.list[:-1:] if num <= 0: return [] return self.list...
[ "def", "not_right", "(", "self", ",", "num", ")", ":", "if", "not", "self", ".", "list", ":", "self", ".", "_build_list", "(", ")", "if", "num", "==", "None", ":", "return", "self", ".", "list", "[", ":", "-", "1", ":", "]", "if", "num", "<=", ...
WITH SLICES BEING FLAT, WE NEED A SIMPLE WAY TO SLICE FROM THE LEFT [:-num:]
[ "WITH", "SLICES", "BEING", "FLAT", "WE", "NEED", "A", "SIMPLE", "WAY", "TO", "SLICE", "FROM", "THE", "LEFT", "[", ":", "-", "num", ":", "]" ]
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_graphs/paths.py#L104-L116
ff0000/scarlet
scarlet/cms/item.py
FormView.get_object_url
def get_object_url(self): """ Returns the url where this object can be edited. """ if self.kwargs.get(self.slug_url_kwarg, False) == \ unicode(getattr(self.object, self.slug_field, "")) \ and not self.force_add: url = self.request.buil...
python
def get_object_url(self): """ Returns the url where this object can be edited. """ if self.kwargs.get(self.slug_url_kwarg, False) == \ unicode(getattr(self.object, self.slug_field, "")) \ and not self.force_add: url = self.request.buil...
[ "def", "get_object_url", "(", "self", ")", ":", "if", "self", ".", "kwargs", ".", "get", "(", "self", ".", "slug_url_kwarg", ",", "False", ")", "==", "unicode", "(", "getattr", "(", "self", ".", "object", ",", "self", ".", "slug_field", ",", "\"\"", ...
Returns the url where this object can be edited.
[ "Returns", "the", "url", "where", "this", "object", "can", "be", "edited", "." ]
train
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/item.py#L92-L105
ff0000/scarlet
scarlet/cms/item.py
FormView.get_cancel_url
def get_cancel_url(self): """ Returns the cancel url for this view. if `self.cancel_view` is None the current url will be used. Otherwise the get_view_url will be called with the current bundle using `self.cancel_view` as the view name. """ if self.cancel...
python
def get_cancel_url(self): """ Returns the cancel url for this view. if `self.cancel_view` is None the current url will be used. Otherwise the get_view_url will be called with the current bundle using `self.cancel_view` as the view name. """ if self.cancel...
[ "def", "get_cancel_url", "(", "self", ")", ":", "if", "self", ".", "cancel_view", ":", "url", "=", "self", ".", "bundle", ".", "get_view_url", "(", "self", ".", "cancel_view", ",", "self", ".", "request", ".", "user", ",", "{", "}", ",", "self", ".",...
Returns the cancel url for this view. if `self.cancel_view` is None the current url will be used. Otherwise the get_view_url will be called with the current bundle using `self.cancel_view` as the view name.
[ "Returns", "the", "cancel", "url", "for", "this", "view", "." ]
train
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/item.py#L107-L123
ff0000/scarlet
scarlet/cms/item.py
FormView.get_success_url
def get_success_url(self): """ Returns the url to redirect to after a successful update. if `self.redirect_to_view` is None the current url will be used. Otherwise the get_view_url will be called on the current bundle using `self.redirect_to_view` as the view name. If th...
python
def get_success_url(self): """ Returns the url to redirect to after a successful update. if `self.redirect_to_view` is None the current url will be used. Otherwise the get_view_url will be called on the current bundle using `self.redirect_to_view` as the view name. If th...
[ "def", "get_success_url", "(", "self", ")", ":", "if", "self", ".", "redirect_to_view", ":", "kwargs", "=", "{", "}", "if", "self", ".", "redirect_to_view", "!=", "'main'", "and", "self", ".", "redirect_to_view", "!=", "'main_list'", ":", "kwargs", "[", "'...
Returns the url to redirect to after a successful update. if `self.redirect_to_view` is None the current url will be used. Otherwise the get_view_url will be called on the current bundle using `self.redirect_to_view` as the view name. If the name is "main" or "main_list" no object ...
[ "Returns", "the", "url", "to", "redirect", "to", "after", "a", "successful", "update", "." ]
train
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/item.py#L125-L146
ff0000/scarlet
scarlet/cms/item.py
FormView.get_object
def get_object(self): """ Get the object we are working with. Makes sure get_queryset is called even when in add mode. """ if not self.force_add and self.kwargs.get(self.slug_url_kwarg, None): return super(FormView, self).get_object() else: self.q...
python
def get_object(self): """ Get the object we are working with. Makes sure get_queryset is called even when in add mode. """ if not self.force_add and self.kwargs.get(self.slug_url_kwarg, None): return super(FormView, self).get_object() else: self.q...
[ "def", "get_object", "(", "self", ")", ":", "if", "not", "self", ".", "force_add", "and", "self", ".", "kwargs", ".", "get", "(", "self", ".", "slug_url_kwarg", ",", "None", ")", ":", "return", "super", "(", "FormView", ",", "self", ")", ".", "get_ob...
Get the object we are working with. Makes sure get_queryset is called even when in add mode.
[ "Get", "the", "object", "we", "are", "working", "with", ".", "Makes", "sure", "get_queryset", "is", "called", "even", "when", "in", "add", "mode", "." ]
train
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/item.py#L148-L159
ff0000/scarlet
scarlet/cms/item.py
FormView.get_fieldsets
def get_fieldsets(self): """ Hook for specifying fieldsets. If 'self.fieldsets' is empty this will default to include all the fields in the form with a title of None. """ if self.fieldsets: return self.fieldsets form_class = self.get_form_class() ...
python
def get_fieldsets(self): """ Hook for specifying fieldsets. If 'self.fieldsets' is empty this will default to include all the fields in the form with a title of None. """ if self.fieldsets: return self.fieldsets form_class = self.get_form_class() ...
[ "def", "get_fieldsets", "(", "self", ")", ":", "if", "self", ".", "fieldsets", ":", "return", "self", ".", "fieldsets", "form_class", "=", "self", ".", "get_form_class", "(", ")", "form", "=", "self", ".", "get_form", "(", "form_class", ")", "fields", "=...
Hook for specifying fieldsets. If 'self.fieldsets' is empty this will default to include all the fields in the form with a title of None.
[ "Hook", "for", "specifying", "fieldsets", ".", "If", "self", ".", "fieldsets", "is", "empty", "this", "will", "default", "to", "include", "all", "the", "fields", "in", "the", "form", "with", "a", "title", "of", "None", "." ]
train
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/item.py#L161-L178
ff0000/scarlet
scarlet/cms/item.py
FormView.get_form_class
def get_form_class(self): """ Returns the form class to use in this view. Makes sure that the form_field_callback is set to use the `formfield_for_dbfield` method and that any custom form classes are prepared by the `customize_form_widgets` method. """ if ...
python
def get_form_class(self): """ Returns the form class to use in this view. Makes sure that the form_field_callback is set to use the `formfield_for_dbfield` method and that any custom form classes are prepared by the `customize_form_widgets` method. """ if ...
[ "def", "get_form_class", "(", "self", ")", ":", "if", "self", ".", "fieldsets", ":", "fields", "=", "flatten_fieldsets", "(", "self", ".", "get_fieldsets", "(", ")", ")", "else", ":", "if", "(", "self", ".", "form_class", "and", "getattr", "(", "self", ...
Returns the form class to use in this view. Makes sure that the form_field_callback is set to use the `formfield_for_dbfield` method and that any custom form classes are prepared by the `customize_form_widgets` method.
[ "Returns", "the", "form", "class", "to", "use", "in", "this", "view", ".", "Makes", "sure", "that", "the", "form_field_callback", "is", "set", "to", "use", "the", "formfield_for_dbfield", "method", "and", "that", "any", "custom", "form", "classes", "are", "p...
train
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/item.py#L180-L248
ff0000/scarlet
scarlet/cms/item.py
FormView.get_form_kwargs
def get_form_kwargs(self): """ Returns the keyword arguments for instantiating the form. """ kwargs = {'initial': self.get_initial(), 'instance': self.object} if self.request.method in ('POST', 'PUT') and self.can_submit: kwargs.update({ ...
python
def get_form_kwargs(self): """ Returns the keyword arguments for instantiating the form. """ kwargs = {'initial': self.get_initial(), 'instance': self.object} if self.request.method in ('POST', 'PUT') and self.can_submit: kwargs.update({ ...
[ "def", "get_form_kwargs", "(", "self", ")", ":", "kwargs", "=", "{", "'initial'", ":", "self", ".", "get_initial", "(", ")", ",", "'instance'", ":", "self", ".", "object", "}", "if", "self", ".", "request", ".", "method", "in", "(", "'POST'", ",", "'...
Returns the keyword arguments for instantiating the form.
[ "Returns", "the", "keyword", "arguments", "for", "instantiating", "the", "form", "." ]
train
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/item.py#L250-L262
ff0000/scarlet
scarlet/cms/item.py
FormView.save_form
def save_form(self, form): """ Save a valid form. If there is a parent attribute, this will make sure that the parent object is added to the saved object. Either as a relationship before saving or in the case of many to many relations after saving. Any forced instance val...
python
def save_form(self, form): """ Save a valid form. If there is a parent attribute, this will make sure that the parent object is added to the saved object. Either as a relationship before saving or in the case of many to many relations after saving. Any forced instance val...
[ "def", "save_form", "(", "self", ",", "form", ")", ":", "# Add any force_instance_values", "force", "=", "self", ".", "get_force_instance_values", "(", ")", "if", "force", ":", "for", "k", ",", "v", "in", "force", ".", "items", "(", ")", ":", "setattr", ...
Save a valid form. If there is a parent attribute, this will make sure that the parent object is added to the saved object. Either as a relationship before saving or in the case of many to many relations after saving. Any forced instance values are set as well. Returns the saved...
[ "Save", "a", "valid", "form", ".", "If", "there", "is", "a", "parent", "attribute", "this", "will", "make", "sure", "that", "the", "parent", "object", "is", "added", "to", "the", "saved", "object", ".", "Either", "as", "a", "relationship", "before", "sav...
train
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/item.py#L341-L386
ff0000/scarlet
scarlet/cms/item.py
FormView.save_formsets
def save_formsets(self, form, formsets, auto_tags=None): """ Hook for saving formsets. Loops through all the given formsets and calls their save method. """ for formset in formsets.values(): tag_handler.set_auto_tags_for_formset(formset, auto_tags) ...
python
def save_formsets(self, form, formsets, auto_tags=None): """ Hook for saving formsets. Loops through all the given formsets and calls their save method. """ for formset in formsets.values(): tag_handler.set_auto_tags_for_formset(formset, auto_tags) ...
[ "def", "save_formsets", "(", "self", ",", "form", ",", "formsets", ",", "auto_tags", "=", "None", ")", ":", "for", "formset", "in", "formsets", ".", "values", "(", ")", ":", "tag_handler", ".", "set_auto_tags_for_formset", "(", "formset", ",", "auto_tags", ...
Hook for saving formsets. Loops through all the given formsets and calls their save method.
[ "Hook", "for", "saving", "formsets", ".", "Loops", "through", "all", "the", "given", "formsets", "and", "calls", "their", "save", "method", "." ]
train
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/item.py#L388-L396
ff0000/scarlet
scarlet/cms/item.py
FormView.form_valid
def form_valid(self, form, formsets): """ Response for valid form. In one transaction this will save the current form and formsets, log the action and message the user. Returns the results of calling the `success_response` method. """ # check if it's a new object...
python
def form_valid(self, form, formsets): """ Response for valid form. In one transaction this will save the current form and formsets, log the action and message the user. Returns the results of calling the `success_response` method. """ # check if it's a new object...
[ "def", "form_valid", "(", "self", ",", "form", ",", "formsets", ")", ":", "# check if it's a new object before it save the form", "new_object", "=", "False", "if", "not", "self", ".", "object", ":", "new_object", "=", "True", "instance", "=", "getattr", "(", "fo...
Response for valid form. In one transaction this will save the current form and formsets, log the action and message the user. Returns the results of calling the `success_response` method.
[ "Response", "for", "valid", "form", ".", "In", "one", "transaction", "this", "will", "save", "the", "current", "form", "and", "formsets", "log", "the", "action", "and", "message", "the", "user", "." ]
train
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/item.py#L398-L428
ff0000/scarlet
scarlet/cms/item.py
FormView.success_response
def success_response(self, message=None): """ Returns a 'render redirect' to the result of the `get_success_url` method. """ return self.render(self.request, redirect_url=self.get_success_url(), obj=self.object, ...
python
def success_response(self, message=None): """ Returns a 'render redirect' to the result of the `get_success_url` method. """ return self.render(self.request, redirect_url=self.get_success_url(), obj=self.object, ...
[ "def", "success_response", "(", "self", ",", "message", "=", "None", ")", ":", "return", "self", ".", "render", "(", "self", ".", "request", ",", "redirect_url", "=", "self", ".", "get_success_url", "(", ")", ",", "obj", "=", "self", ".", "object", ","...
Returns a 'render redirect' to the result of the `get_success_url` method.
[ "Returns", "a", "render", "redirect", "to", "the", "result", "of", "the", "get_success_url", "method", "." ]
train
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/item.py#L430-L440
ff0000/scarlet
scarlet/cms/item.py
FormView.render
def render(self, request, **kwargs): """ Renders this view. Adds cancel_url to the context. If the request get parameters contains 'popup' then the `render_type` is set to 'popup'. """ if request.GET.get('popup'): self.render_type = 'popup' kwargs[...
python
def render(self, request, **kwargs): """ Renders this view. Adds cancel_url to the context. If the request get parameters contains 'popup' then the `render_type` is set to 'popup'. """ if request.GET.get('popup'): self.render_type = 'popup' kwargs[...
[ "def", "render", "(", "self", ",", "request", ",", "*", "*", "kwargs", ")", ":", "if", "request", ".", "GET", ".", "get", "(", "'popup'", ")", ":", "self", ".", "render_type", "=", "'popup'", "kwargs", "[", "'popup'", "]", "=", "1", "kwargs", "[", ...
Renders this view. Adds cancel_url to the context. If the request get parameters contains 'popup' then the `render_type` is set to 'popup'.
[ "Renders", "this", "view", ".", "Adds", "cancel_url", "to", "the", "context", ".", "If", "the", "request", "get", "parameters", "contains", "popup", "then", "the", "render_type", "is", "set", "to", "popup", "." ]
train
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/item.py#L442-L455
ff0000/scarlet
scarlet/cms/item.py
FormView.get
def get(self, request, *args, **kwargs): """ Method for handling GET requests. Calls the `render` method with the following items in context. * **adminForm** - The main form wrapped in an helper class \ that helps with fieldset iteration and html attributes. * **...
python
def get(self, request, *args, **kwargs): """ Method for handling GET requests. Calls the `render` method with the following items in context. * **adminForm** - The main form wrapped in an helper class \ that helps with fieldset iteration and html attributes. * **...
[ "def", "get", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "object", "=", "self", ".", "get_object", "(", ")", "form_class", "=", "self", ".", "get_form_class", "(", ")", "form", "=", "self", ".", ...
Method for handling GET requests. Calls the `render` method with the following items in context. * **adminForm** - The main form wrapped in an helper class \ that helps with fieldset iteration and html attributes. * **obj** - The object being edited. * **formsets** - Any...
[ "Method", "for", "handling", "GET", "requests", ".", "Calls", "the", "render", "method", "with", "the", "following", "items", "in", "context", "." ]
train
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/item.py#L457-L481
ff0000/scarlet
scarlet/cms/item.py
FormView.post
def post(self, request, *args, **kwargs): """ Method for handling POST requests. Validates submitted form and formsets. Saves if valid, re displays page with errors if invalid. """ self.object = self.get_object() form_class = self.get_form_class() ...
python
def post(self, request, *args, **kwargs): """ Method for handling POST requests. Validates submitted form and formsets. Saves if valid, re displays page with errors if invalid. """ self.object = self.get_object() form_class = self.get_form_class() ...
[ "def", "post", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "object", "=", "self", ".", "get_object", "(", ")", "form_class", "=", "self", ".", "get_form_class", "(", ")", "form", "=", "self", ".", ...
Method for handling POST requests. Validates submitted form and formsets. Saves if valid, re displays page with errors if invalid.
[ "Method", "for", "handling", "POST", "requests", ".", "Validates", "submitted", "form", "and", "formsets", ".", "Saves", "if", "valid", "re", "displays", "page", "with", "errors", "if", "invalid", "." ]
train
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/item.py#L505-L534
ff0000/scarlet
scarlet/cms/item.py
PreviewWrapper.get_object
def get_object(self): """ Get the object for previewing. Raises a http404 error if the object is not found. """ obj = super(PreviewWrapper, self).get_object() if not obj: raise http.Http404 return obj
python
def get_object(self): """ Get the object for previewing. Raises a http404 error if the object is not found. """ obj = super(PreviewWrapper, self).get_object() if not obj: raise http.Http404 return obj
[ "def", "get_object", "(", "self", ")", ":", "obj", "=", "super", "(", "PreviewWrapper", ",", "self", ")", ".", "get_object", "(", ")", "if", "not", "obj", ":", "raise", "http", ".", "Http404", "return", "obj" ]
Get the object for previewing. Raises a http404 error if the object is not found.
[ "Get", "the", "object", "for", "previewing", ".", "Raises", "a", "http404", "error", "if", "the", "object", "is", "not", "found", "." ]
train
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/item.py#L568-L578
ff0000/scarlet
scarlet/cms/item.py
PreviewWrapper.get_preview_kwargs
def get_preview_kwargs(self, **kwargs): """ Gets the url keyword arguments to pass to the `preview_view` callable. If the `pass_through_kwarg` attribute is set the value of `pass_through_attr` will be looked up on the object. So if you are previewing an item Obj<id=2> an...
python
def get_preview_kwargs(self, **kwargs): """ Gets the url keyword arguments to pass to the `preview_view` callable. If the `pass_through_kwarg` attribute is set the value of `pass_through_attr` will be looked up on the object. So if you are previewing an item Obj<id=2> an...
[ "def", "get_preview_kwargs", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "pass_through_kwarg", ":", "return", "{", "}", "obj", "=", "self", ".", "get_object", "(", ")", "return", "{", "self", ".", "pass_through_kwarg", ":", ...
Gets the url keyword arguments to pass to the `preview_view` callable. If the `pass_through_kwarg` attribute is set the value of `pass_through_attr` will be looked up on the object. So if you are previewing an item Obj<id=2> and :: self.pass_through_kwarg =...
[ "Gets", "the", "url", "keyword", "arguments", "to", "pass", "to", "the", "preview_view", "callable", ".", "If", "the", "pass_through_kwarg", "attribute", "is", "set", "the", "value", "of", "pass_through_attr", "will", "be", "looked", "up", "on", "the", "object...
train
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/item.py#L580-L607