id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
246,100
daknuett/py_register_machine2
core/processor.py
Processor.interrupt
def interrupt(self, address): """ Interrupts the Processor and forces him to jump to ``address``. If ``push_pc`` is enabled this will push the PC to the stack. """ if(self.push_pc): self.memory_bus.write_word(self.sp, self.pc) self._set_sp(self.sp - 1) self._set_pc(address)
python
def interrupt(self, address): """ Interrupts the Processor and forces him to jump to ``address``. If ``push_pc`` is enabled this will push the PC to the stack. """ if(self.push_pc): self.memory_bus.write_word(self.sp, self.pc) self._set_sp(self.sp - 1) self._set_pc(address)
[ "def", "interrupt", "(", "self", ",", "address", ")", ":", "if", "(", "self", ".", "push_pc", ")", ":", "self", ".", "memory_bus", ".", "write_word", "(", "self", ".", "sp", ",", "self", ".", "pc", ")", "self", ".", "_set_sp", "(", "self", ".", "sp", "-", "1", ")", "self", ".", "_set_pc", "(", "address", ")" ]
Interrupts the Processor and forces him to jump to ``address``. If ``push_pc`` is enabled this will push the PC to the stack.
[ "Interrupts", "the", "Processor", "and", "forces", "him", "to", "jump", "to", "address", ".", "If", "push_pc", "is", "enabled", "this", "will", "push", "the", "PC", "to", "the", "stack", "." ]
599c53cd7576297d0d7a53344ed5d9aa98acc751
https://github.com/daknuett/py_register_machine2/blob/599c53cd7576297d0d7a53344ed5d9aa98acc751/core/processor.py#L218-L226
246,101
jamieleshaw/lurklib
lurklib/core.py
_Core._raw_recv
def _raw_recv(self): """ Return the next available IRC message in the buffer. """ with self.lock: if self._index >= len(self._buffer): self._mcon() if self._index >= 199: self._resetbuffer() self._mcon() msg = self._buffer[self._index] while self.find(msg, 'PING :'): self._index += 1 try: msg = self._buffer[self._index] except IndexError: self._mcon() self.stepback(append=False) self._index += 1 return msg
python
def _raw_recv(self): """ Return the next available IRC message in the buffer. """ with self.lock: if self._index >= len(self._buffer): self._mcon() if self._index >= 199: self._resetbuffer() self._mcon() msg = self._buffer[self._index] while self.find(msg, 'PING :'): self._index += 1 try: msg = self._buffer[self._index] except IndexError: self._mcon() self.stepback(append=False) self._index += 1 return msg
[ "def", "_raw_recv", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "if", "self", ".", "_index", ">=", "len", "(", "self", ".", "_buffer", ")", ":", "self", ".", "_mcon", "(", ")", "if", "self", ".", "_index", ">=", "199", ":", "self", ".", "_resetbuffer", "(", ")", "self", ".", "_mcon", "(", ")", "msg", "=", "self", ".", "_buffer", "[", "self", ".", "_index", "]", "while", "self", ".", "find", "(", "msg", ",", "'PING :'", ")", ":", "self", ".", "_index", "+=", "1", "try", ":", "msg", "=", "self", ".", "_buffer", "[", "self", ".", "_index", "]", "except", "IndexError", ":", "self", ".", "_mcon", "(", ")", "self", ".", "stepback", "(", "append", "=", "False", ")", "self", ".", "_index", "+=", "1", "return", "msg" ]
Return the next available IRC message in the buffer.
[ "Return", "the", "next", "available", "IRC", "message", "in", "the", "buffer", "." ]
a861f35d880140422103dd78ec3239814e85fd7e
https://github.com/jamieleshaw/lurklib/blob/a861f35d880140422103dd78ec3239814e85fd7e/lurklib/core.py#L146-L164
246,102
jut-io/jut-python-tools
jut/commands/upload.py
post
def post(json_data, url, dry_run=False): """ POST json data to the url provided and verify the requests was successful """ if dry_run: info('POST: %s' % json.dumps(json_data, indent=4)) else: response = SESSION.post(url, data=json.dumps(json_data), headers={'content-type': 'application/json'}) if response.status_code != 200: raise Exception("Failed to import %s with %s: %s" % (json_data, response.status_code, response.text))
python
def post(json_data, url, dry_run=False): """ POST json data to the url provided and verify the requests was successful """ if dry_run: info('POST: %s' % json.dumps(json_data, indent=4)) else: response = SESSION.post(url, data=json.dumps(json_data), headers={'content-type': 'application/json'}) if response.status_code != 200: raise Exception("Failed to import %s with %s: %s" % (json_data, response.status_code, response.text))
[ "def", "post", "(", "json_data", ",", "url", ",", "dry_run", "=", "False", ")", ":", "if", "dry_run", ":", "info", "(", "'POST: %s'", "%", "json", ".", "dumps", "(", "json_data", ",", "indent", "=", "4", ")", ")", "else", ":", "response", "=", "SESSION", ".", "post", "(", "url", ",", "data", "=", "json", ".", "dumps", "(", "json_data", ")", ",", "headers", "=", "{", "'content-type'", ":", "'application/json'", "}", ")", "if", "response", ".", "status_code", "!=", "200", ":", "raise", "Exception", "(", "\"Failed to import %s with %s: %s\"", "%", "(", "json_data", ",", "response", ".", "status_code", ",", "response", ".", "text", ")", ")" ]
POST json data to the url provided and verify the requests was successful
[ "POST", "json", "data", "to", "the", "url", "provided", "and", "verify", "the", "requests", "was", "successful" ]
65574d23f51a7bbced9bb25010d02da5ca5d906f
https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/commands/upload.py#L19-L36
246,103
jut-io/jut-python-tools
jut/commands/upload.py
push_json_file
def push_json_file(json_file, url, dry_run=False, batch_size=100, anonymize_fields=[], remove_fields=[], rename_fields=[]): """ read the json file provided and POST in batches no bigger than the batch_size specified to the specified url. """ batch = [] json_data = json.loads(json_file.read()) if isinstance(json_data, list): for item in json_data: # anonymize fields for field_name in anonymize_fields: if field_name in item: item[field_name] = md5sum(item[field_name]) # remove fields for field_name in remove_fields: if field_name in item: del item[field_name] # rename fields for (field_name, new_field_name) in rename_fields: if field_name in item: item[new_field_name] = item[field_name] del item[field_name] batch.append(item) if len(batch) >= batch_size: post(batch, url, dry_run=dry_run) batch = [] if len(batch) > 0: post(batch, url, dry_run=dry_run) else: post(json_data, url, dry_run=dry_run)
python
def push_json_file(json_file, url, dry_run=False, batch_size=100, anonymize_fields=[], remove_fields=[], rename_fields=[]): """ read the json file provided and POST in batches no bigger than the batch_size specified to the specified url. """ batch = [] json_data = json.loads(json_file.read()) if isinstance(json_data, list): for item in json_data: # anonymize fields for field_name in anonymize_fields: if field_name in item: item[field_name] = md5sum(item[field_name]) # remove fields for field_name in remove_fields: if field_name in item: del item[field_name] # rename fields for (field_name, new_field_name) in rename_fields: if field_name in item: item[new_field_name] = item[field_name] del item[field_name] batch.append(item) if len(batch) >= batch_size: post(batch, url, dry_run=dry_run) batch = [] if len(batch) > 0: post(batch, url, dry_run=dry_run) else: post(json_data, url, dry_run=dry_run)
[ "def", "push_json_file", "(", "json_file", ",", "url", ",", "dry_run", "=", "False", ",", "batch_size", "=", "100", ",", "anonymize_fields", "=", "[", "]", ",", "remove_fields", "=", "[", "]", ",", "rename_fields", "=", "[", "]", ")", ":", "batch", "=", "[", "]", "json_data", "=", "json", ".", "loads", "(", "json_file", ".", "read", "(", ")", ")", "if", "isinstance", "(", "json_data", ",", "list", ")", ":", "for", "item", "in", "json_data", ":", "# anonymize fields", "for", "field_name", "in", "anonymize_fields", ":", "if", "field_name", "in", "item", ":", "item", "[", "field_name", "]", "=", "md5sum", "(", "item", "[", "field_name", "]", ")", "# remove fields", "for", "field_name", "in", "remove_fields", ":", "if", "field_name", "in", "item", ":", "del", "item", "[", "field_name", "]", "# rename fields", "for", "(", "field_name", ",", "new_field_name", ")", "in", "rename_fields", ":", "if", "field_name", "in", "item", ":", "item", "[", "new_field_name", "]", "=", "item", "[", "field_name", "]", "del", "item", "[", "field_name", "]", "batch", ".", "append", "(", "item", ")", "if", "len", "(", "batch", ")", ">=", "batch_size", ":", "post", "(", "batch", ",", "url", ",", "dry_run", "=", "dry_run", ")", "batch", "=", "[", "]", "if", "len", "(", "batch", ")", ">", "0", ":", "post", "(", "batch", ",", "url", ",", "dry_run", "=", "dry_run", ")", "else", ":", "post", "(", "json_data", ",", "url", ",", "dry_run", "=", "dry_run", ")" ]
read the json file provided and POST in batches no bigger than the batch_size specified to the specified url.
[ "read", "the", "json", "file", "provided", "and", "POST", "in", "batches", "no", "bigger", "than", "the", "batch_size", "specified", "to", "the", "specified", "url", "." ]
65574d23f51a7bbced9bb25010d02da5ca5d906f
https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/commands/upload.py#L43-L93
246,104
jmgilman/Neolib
neolib/shop/MainShop.py
MainShop.load
def load(self): """ Loads the shop name and inventory """ pg = self.usr.getPage("http://www.neopets.com/objects.phtml?type=shop&obj_type=" + self.id) self.name = pg.find("td", "contentModuleHeader").text.strip() self.inventory = MainShopInventory(self.usr, self.id)
python
def load(self): """ Loads the shop name and inventory """ pg = self.usr.getPage("http://www.neopets.com/objects.phtml?type=shop&obj_type=" + self.id) self.name = pg.find("td", "contentModuleHeader").text.strip() self.inventory = MainShopInventory(self.usr, self.id)
[ "def", "load", "(", "self", ")", ":", "pg", "=", "self", ".", "usr", ".", "getPage", "(", "\"http://www.neopets.com/objects.phtml?type=shop&obj_type=\"", "+", "self", ".", "id", ")", "self", ".", "name", "=", "pg", ".", "find", "(", "\"td\"", ",", "\"contentModuleHeader\"", ")", ".", "text", ".", "strip", "(", ")", "self", ".", "inventory", "=", "MainShopInventory", "(", "self", ".", "usr", ",", "self", ".", "id", ")" ]
Loads the shop name and inventory
[ "Loads", "the", "shop", "name", "and", "inventory" ]
228fafeaed0f3195676137732384a14820ae285c
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/shop/MainShop.py#L48-L54
246,105
alfred82santa/aio-service-client
service_client/utils.py
random_token
def random_token(length=10): """ Builds a random string. :param length: Token length. **Default:** 10 :type length: int :return: str """ return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(length))
python
def random_token(length=10): """ Builds a random string. :param length: Token length. **Default:** 10 :type length: int :return: str """ return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(length))
[ "def", "random_token", "(", "length", "=", "10", ")", ":", "return", "''", ".", "join", "(", "random", ".", "choice", "(", "string", ".", "ascii_uppercase", "+", "string", ".", "digits", ")", "for", "_", "in", "range", "(", "length", ")", ")" ]
Builds a random string. :param length: Token length. **Default:** 10 :type length: int :return: str
[ "Builds", "a", "random", "string", "." ]
dd9ad49e23067b22178534915aa23ba24f6ff39b
https://github.com/alfred82santa/aio-service-client/blob/dd9ad49e23067b22178534915aa23ba24f6ff39b/service_client/utils.py#L43-L52
246,106
sci-bots/mpm
mpm/commands.py
get_plugins_directory
def get_plugins_directory(config_path=None, microdrop_user_root=None): ''' Resolve plugins directory. Plugins directory is resolved as follows, highest-priority first: 1. ``plugins`` directory specified in provided :data:`config_path`. 2. ``plugins`` sub-directory of specified MicroDrop profile path (i.e., :data:`microdrop_user_root`) 3. ``plugins`` sub-directory of parent directory of configuration file path specified using ``MICRODROP_CONFIG`` environment variable. 4. ``plugins`` sub-directory of MicroDrop profile path specified using ``MICRODROP_PROFILE`` environment variable. 5. Plugins directory specified in ``<home directory>/MicroDrop/microdrop.ini``. 6. Plugins directory in default profile location, i.e., ``<home directory>/MicroDrop/plugins``. Parameters ---------- config_path : str, optional Configuration file path (i.e., path to ``microdrop.ini``). microdrop_user_root : str, optional Path to MicroDrop user data directory. Returns ------- path Absolute path to plugins directory. ''' RESOLVED_BY_NONE = 'default' RESOLVED_BY_CONFIG_ARG = 'config_path argument' RESOLVED_BY_PROFILE_ARG = 'microdrop_user_root argument' RESOLVED_BY_CONFIG_ENV = 'MICRODROP_CONFIG environment variable' RESOLVED_BY_PROFILE_ENV = 'MICRODROP_PROFILE environment variable' resolved_by = [RESOLVED_BY_NONE] # # Find plugins directory path # if microdrop_user_root is not None: microdrop_user_root = path(microdrop_user_root).realpath() resolved_by.append(RESOLVED_BY_PROFILE_ARG) elif 'MICRODROP_PROFILE' in os.environ: microdrop_user_root = path(os.environ['MICRODROP_PROFILE']).realpath() resolved_by.append(RESOLVED_BY_PROFILE_ENV) else: microdrop_user_root = path(home_dir()).joinpath('MicroDrop') if config_path is not None: config_path = path(config_path).expand() resolved_by.append(RESOLVED_BY_CONFIG_ARG) elif 'MICRODROP_CONFIG' in os.environ: config_path = path(os.environ['MICRODROP_CONFIG']).realpath() resolved_by.append(RESOLVED_BY_CONFIG_ENV) else: config_path = microdrop_user_root.joinpath('microdrop.ini') try: # Look up plugins directory stored in configuration file. plugins_directory = path(configobj.ConfigObj(config_path) ['plugins']['directory']) if not plugins_directory.isabs(): # Plugins directory stored in configuration file as relative path. # Interpret as relative to parent directory of configuration file. plugins_directory = config_path.parent.joinpath(plugins_directory) if not plugins_directory.isdir(): raise IOError('Plugins directory does not exist: {}' .format(plugins_directory)) except Exception, why: # Error looking up plugins directory in configuration file (maybe no # plugins directory was listed in configuration file?). plugins_directory = microdrop_user_root.joinpath('plugins') logger.warning('%s. Using default plugins directory: %s', why, plugins_directory) if resolved_by[-1] in (RESOLVED_BY_CONFIG_ARG, RESOLVED_BY_CONFIG_ENV): resolved_by.pop() logger.info('Resolved plugins directory by %s: %s', resolved_by[-1], plugins_directory) return plugins_directory
python
def get_plugins_directory(config_path=None, microdrop_user_root=None): ''' Resolve plugins directory. Plugins directory is resolved as follows, highest-priority first: 1. ``plugins`` directory specified in provided :data:`config_path`. 2. ``plugins`` sub-directory of specified MicroDrop profile path (i.e., :data:`microdrop_user_root`) 3. ``plugins`` sub-directory of parent directory of configuration file path specified using ``MICRODROP_CONFIG`` environment variable. 4. ``plugins`` sub-directory of MicroDrop profile path specified using ``MICRODROP_PROFILE`` environment variable. 5. Plugins directory specified in ``<home directory>/MicroDrop/microdrop.ini``. 6. Plugins directory in default profile location, i.e., ``<home directory>/MicroDrop/plugins``. Parameters ---------- config_path : str, optional Configuration file path (i.e., path to ``microdrop.ini``). microdrop_user_root : str, optional Path to MicroDrop user data directory. Returns ------- path Absolute path to plugins directory. ''' RESOLVED_BY_NONE = 'default' RESOLVED_BY_CONFIG_ARG = 'config_path argument' RESOLVED_BY_PROFILE_ARG = 'microdrop_user_root argument' RESOLVED_BY_CONFIG_ENV = 'MICRODROP_CONFIG environment variable' RESOLVED_BY_PROFILE_ENV = 'MICRODROP_PROFILE environment variable' resolved_by = [RESOLVED_BY_NONE] # # Find plugins directory path # if microdrop_user_root is not None: microdrop_user_root = path(microdrop_user_root).realpath() resolved_by.append(RESOLVED_BY_PROFILE_ARG) elif 'MICRODROP_PROFILE' in os.environ: microdrop_user_root = path(os.environ['MICRODROP_PROFILE']).realpath() resolved_by.append(RESOLVED_BY_PROFILE_ENV) else: microdrop_user_root = path(home_dir()).joinpath('MicroDrop') if config_path is not None: config_path = path(config_path).expand() resolved_by.append(RESOLVED_BY_CONFIG_ARG) elif 'MICRODROP_CONFIG' in os.environ: config_path = path(os.environ['MICRODROP_CONFIG']).realpath() resolved_by.append(RESOLVED_BY_CONFIG_ENV) else: config_path = microdrop_user_root.joinpath('microdrop.ini') try: # Look up plugins directory stored in configuration file. plugins_directory = path(configobj.ConfigObj(config_path) ['plugins']['directory']) if not plugins_directory.isabs(): # Plugins directory stored in configuration file as relative path. # Interpret as relative to parent directory of configuration file. plugins_directory = config_path.parent.joinpath(plugins_directory) if not plugins_directory.isdir(): raise IOError('Plugins directory does not exist: {}' .format(plugins_directory)) except Exception, why: # Error looking up plugins directory in configuration file (maybe no # plugins directory was listed in configuration file?). plugins_directory = microdrop_user_root.joinpath('plugins') logger.warning('%s. Using default plugins directory: %s', why, plugins_directory) if resolved_by[-1] in (RESOLVED_BY_CONFIG_ARG, RESOLVED_BY_CONFIG_ENV): resolved_by.pop() logger.info('Resolved plugins directory by %s: %s', resolved_by[-1], plugins_directory) return plugins_directory
[ "def", "get_plugins_directory", "(", "config_path", "=", "None", ",", "microdrop_user_root", "=", "None", ")", ":", "RESOLVED_BY_NONE", "=", "'default'", "RESOLVED_BY_CONFIG_ARG", "=", "'config_path argument'", "RESOLVED_BY_PROFILE_ARG", "=", "'microdrop_user_root argument'", "RESOLVED_BY_CONFIG_ENV", "=", "'MICRODROP_CONFIG environment variable'", "RESOLVED_BY_PROFILE_ENV", "=", "'MICRODROP_PROFILE environment variable'", "resolved_by", "=", "[", "RESOLVED_BY_NONE", "]", "# # Find plugins directory path #", "if", "microdrop_user_root", "is", "not", "None", ":", "microdrop_user_root", "=", "path", "(", "microdrop_user_root", ")", ".", "realpath", "(", ")", "resolved_by", ".", "append", "(", "RESOLVED_BY_PROFILE_ARG", ")", "elif", "'MICRODROP_PROFILE'", "in", "os", ".", "environ", ":", "microdrop_user_root", "=", "path", "(", "os", ".", "environ", "[", "'MICRODROP_PROFILE'", "]", ")", ".", "realpath", "(", ")", "resolved_by", ".", "append", "(", "RESOLVED_BY_PROFILE_ENV", ")", "else", ":", "microdrop_user_root", "=", "path", "(", "home_dir", "(", ")", ")", ".", "joinpath", "(", "'MicroDrop'", ")", "if", "config_path", "is", "not", "None", ":", "config_path", "=", "path", "(", "config_path", ")", ".", "expand", "(", ")", "resolved_by", ".", "append", "(", "RESOLVED_BY_CONFIG_ARG", ")", "elif", "'MICRODROP_CONFIG'", "in", "os", ".", "environ", ":", "config_path", "=", "path", "(", "os", ".", "environ", "[", "'MICRODROP_CONFIG'", "]", ")", ".", "realpath", "(", ")", "resolved_by", ".", "append", "(", "RESOLVED_BY_CONFIG_ENV", ")", "else", ":", "config_path", "=", "microdrop_user_root", ".", "joinpath", "(", "'microdrop.ini'", ")", "try", ":", "# Look up plugins directory stored in configuration file.", "plugins_directory", "=", "path", "(", "configobj", ".", "ConfigObj", "(", "config_path", ")", "[", "'plugins'", "]", "[", "'directory'", "]", ")", "if", "not", "plugins_directory", ".", "isabs", "(", ")", ":", "# Plugins directory stored in configuration file as relative path.", "# Interpret as relative to parent directory of configuration file.", "plugins_directory", "=", "config_path", ".", "parent", ".", "joinpath", "(", "plugins_directory", ")", "if", "not", "plugins_directory", ".", "isdir", "(", ")", ":", "raise", "IOError", "(", "'Plugins directory does not exist: {}'", ".", "format", "(", "plugins_directory", ")", ")", "except", "Exception", ",", "why", ":", "# Error looking up plugins directory in configuration file (maybe no", "# plugins directory was listed in configuration file?).", "plugins_directory", "=", "microdrop_user_root", ".", "joinpath", "(", "'plugins'", ")", "logger", ".", "warning", "(", "'%s. Using default plugins directory: %s'", ",", "why", ",", "plugins_directory", ")", "if", "resolved_by", "[", "-", "1", "]", "in", "(", "RESOLVED_BY_CONFIG_ARG", ",", "RESOLVED_BY_CONFIG_ENV", ")", ":", "resolved_by", ".", "pop", "(", ")", "logger", ".", "info", "(", "'Resolved plugins directory by %s: %s'", ",", "resolved_by", "[", "-", "1", "]", ",", "plugins_directory", ")", "return", "plugins_directory" ]
Resolve plugins directory. Plugins directory is resolved as follows, highest-priority first: 1. ``plugins`` directory specified in provided :data:`config_path`. 2. ``plugins`` sub-directory of specified MicroDrop profile path (i.e., :data:`microdrop_user_root`) 3. ``plugins`` sub-directory of parent directory of configuration file path specified using ``MICRODROP_CONFIG`` environment variable. 4. ``plugins`` sub-directory of MicroDrop profile path specified using ``MICRODROP_PROFILE`` environment variable. 5. Plugins directory specified in ``<home directory>/MicroDrop/microdrop.ini``. 6. Plugins directory in default profile location, i.e., ``<home directory>/MicroDrop/plugins``. Parameters ---------- config_path : str, optional Configuration file path (i.e., path to ``microdrop.ini``). microdrop_user_root : str, optional Path to MicroDrop user data directory. Returns ------- path Absolute path to plugins directory.
[ "Resolve", "plugins", "directory", "." ]
a69651cda4b37ee6b17df4fe0809249e7f4dc536
https://github.com/sci-bots/mpm/blob/a69651cda4b37ee6b17df4fe0809249e7f4dc536/mpm/commands.py#L45-L123
246,107
sci-bots/mpm
mpm/commands.py
plugin_request
def plugin_request(plugin_str): ''' Extract plugin name and version specifiers from plugin descriptor string. .. versionchanged:: 0.25.2 Import from `pip_helpers` locally to avoid error `sci-bots/mpm#5`_. .. _sci-bots/mpm#5: https://github.com/sci-bots/mpm/issues/5 ''' from pip_helpers import CRE_PACKAGE match = CRE_PACKAGE.match(plugin_str) if not match: raise ValueError('Invalid plugin descriptor. Must be like "foo", ' '"foo==1.0", "foo>=1.0", etc.') return match.groupdict()
python
def plugin_request(plugin_str): ''' Extract plugin name and version specifiers from plugin descriptor string. .. versionchanged:: 0.25.2 Import from `pip_helpers` locally to avoid error `sci-bots/mpm#5`_. .. _sci-bots/mpm#5: https://github.com/sci-bots/mpm/issues/5 ''' from pip_helpers import CRE_PACKAGE match = CRE_PACKAGE.match(plugin_str) if not match: raise ValueError('Invalid plugin descriptor. Must be like "foo", ' '"foo==1.0", "foo>=1.0", etc.') return match.groupdict()
[ "def", "plugin_request", "(", "plugin_str", ")", ":", "from", "pip_helpers", "import", "CRE_PACKAGE", "match", "=", "CRE_PACKAGE", ".", "match", "(", "plugin_str", ")", "if", "not", "match", ":", "raise", "ValueError", "(", "'Invalid plugin descriptor. Must be like \"foo\", '", "'\"foo==1.0\", \"foo>=1.0\", etc.'", ")", "return", "match", ".", "groupdict", "(", ")" ]
Extract plugin name and version specifiers from plugin descriptor string. .. versionchanged:: 0.25.2 Import from `pip_helpers` locally to avoid error `sci-bots/mpm#5`_. .. _sci-bots/mpm#5: https://github.com/sci-bots/mpm/issues/5
[ "Extract", "plugin", "name", "and", "version", "specifiers", "from", "plugin", "descriptor", "string", "." ]
a69651cda4b37ee6b17df4fe0809249e7f4dc536
https://github.com/sci-bots/mpm/blob/a69651cda4b37ee6b17df4fe0809249e7f4dc536/mpm/commands.py#L126-L141
246,108
billyoverton/tweetqueue
tweetqueue/__main__.py
tweetqueue
def tweetqueue(ctx, dry_run, config): """A command line tool for time-delaying your tweets.""" ctx.obj = {} ctx.obj['DRYRUN'] = dry_run # If the subcommand is "config", bypass all setup code if ctx.invoked_subcommand == 'config': return # If the config file wasn't provided, attempt to load the default one. if config is None: user_home = os.path.expanduser("~") default_config = os.path.join(user_home, ".tweetqueue") if not os.path.isfile(default_config): click.echo("Default configuration was not found and none was provided.") click.echo("Run 'tweetqueue config' to create one.") ctx.exit(1) config = open(default_config, 'rb') try: ctx.obj['config'] = json.load(config) except Exception as e: click.echo("Unable to read configuration file.") click.echo("Are you sure it is valid JSON") click.echo("JSON Error: " + e.message) ctx.exit(1) # Verify that the config file has all required options required_config = [ 'API_KEY', 'API_SECRET', 'ACCESS_TOKEN', 'ACCESS_TOKEN_SECRET', 'DATABASE_LOCATION' ] if not all(key in ctx.obj['config'] for key in required_config): click.echo("Missing required value in config file.") ctx.exit(1) # Make a tweepy api object for the context auth = tweepy.OAuthHandler( ctx.obj['config']['API_KEY'], ctx.obj['config']['API_SECRET'] ) auth.set_access_token( ctx.obj['config']['ACCESS_TOKEN'], ctx.obj['config']['ACCESS_TOKEN_SECRET'] ) ctx.obj['TWEEPY_API'] = tweepy.API(auth) ctx.obj['TWEETLIST'] = TweetList(ctx.obj['config']['DATABASE_LOCATION'])
python
def tweetqueue(ctx, dry_run, config): """A command line tool for time-delaying your tweets.""" ctx.obj = {} ctx.obj['DRYRUN'] = dry_run # If the subcommand is "config", bypass all setup code if ctx.invoked_subcommand == 'config': return # If the config file wasn't provided, attempt to load the default one. if config is None: user_home = os.path.expanduser("~") default_config = os.path.join(user_home, ".tweetqueue") if not os.path.isfile(default_config): click.echo("Default configuration was not found and none was provided.") click.echo("Run 'tweetqueue config' to create one.") ctx.exit(1) config = open(default_config, 'rb') try: ctx.obj['config'] = json.load(config) except Exception as e: click.echo("Unable to read configuration file.") click.echo("Are you sure it is valid JSON") click.echo("JSON Error: " + e.message) ctx.exit(1) # Verify that the config file has all required options required_config = [ 'API_KEY', 'API_SECRET', 'ACCESS_TOKEN', 'ACCESS_TOKEN_SECRET', 'DATABASE_LOCATION' ] if not all(key in ctx.obj['config'] for key in required_config): click.echo("Missing required value in config file.") ctx.exit(1) # Make a tweepy api object for the context auth = tweepy.OAuthHandler( ctx.obj['config']['API_KEY'], ctx.obj['config']['API_SECRET'] ) auth.set_access_token( ctx.obj['config']['ACCESS_TOKEN'], ctx.obj['config']['ACCESS_TOKEN_SECRET'] ) ctx.obj['TWEEPY_API'] = tweepy.API(auth) ctx.obj['TWEETLIST'] = TweetList(ctx.obj['config']['DATABASE_LOCATION'])
[ "def", "tweetqueue", "(", "ctx", ",", "dry_run", ",", "config", ")", ":", "ctx", ".", "obj", "=", "{", "}", "ctx", ".", "obj", "[", "'DRYRUN'", "]", "=", "dry_run", "# If the subcommand is \"config\", bypass all setup code", "if", "ctx", ".", "invoked_subcommand", "==", "'config'", ":", "return", "# If the config file wasn't provided, attempt to load the default one.", "if", "config", "is", "None", ":", "user_home", "=", "os", ".", "path", ".", "expanduser", "(", "\"~\"", ")", "default_config", "=", "os", ".", "path", ".", "join", "(", "user_home", ",", "\".tweetqueue\"", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "default_config", ")", ":", "click", ".", "echo", "(", "\"Default configuration was not found and none was provided.\"", ")", "click", ".", "echo", "(", "\"Run 'tweetqueue config' to create one.\"", ")", "ctx", ".", "exit", "(", "1", ")", "config", "=", "open", "(", "default_config", ",", "'rb'", ")", "try", ":", "ctx", ".", "obj", "[", "'config'", "]", "=", "json", ".", "load", "(", "config", ")", "except", "Exception", "as", "e", ":", "click", ".", "echo", "(", "\"Unable to read configuration file.\"", ")", "click", ".", "echo", "(", "\"Are you sure it is valid JSON\"", ")", "click", ".", "echo", "(", "\"JSON Error: \"", "+", "e", ".", "message", ")", "ctx", ".", "exit", "(", "1", ")", "# Verify that the config file has all required options", "required_config", "=", "[", "'API_KEY'", ",", "'API_SECRET'", ",", "'ACCESS_TOKEN'", ",", "'ACCESS_TOKEN_SECRET'", ",", "'DATABASE_LOCATION'", "]", "if", "not", "all", "(", "key", "in", "ctx", ".", "obj", "[", "'config'", "]", "for", "key", "in", "required_config", ")", ":", "click", ".", "echo", "(", "\"Missing required value in config file.\"", ")", "ctx", ".", "exit", "(", "1", ")", "# Make a tweepy api object for the context", "auth", "=", "tweepy", ".", "OAuthHandler", "(", "ctx", ".", "obj", "[", "'config'", "]", "[", "'API_KEY'", "]", ",", "ctx", ".", "obj", "[", "'config'", "]", "[", "'API_SECRET'", "]", ")", "auth", ".", "set_access_token", "(", "ctx", ".", "obj", "[", "'config'", "]", "[", "'ACCESS_TOKEN'", "]", ",", "ctx", ".", "obj", "[", "'config'", "]", "[", "'ACCESS_TOKEN_SECRET'", "]", ")", "ctx", ".", "obj", "[", "'TWEEPY_API'", "]", "=", "tweepy", ".", "API", "(", "auth", ")", "ctx", ".", "obj", "[", "'TWEETLIST'", "]", "=", "TweetList", "(", "ctx", ".", "obj", "[", "'config'", "]", "[", "'DATABASE_LOCATION'", "]", ")" ]
A command line tool for time-delaying your tweets.
[ "A", "command", "line", "tool", "for", "time", "-", "delaying", "your", "tweets", "." ]
e54972a0137ea2a21b2357b81408d9d4c92fdd61
https://github.com/billyoverton/tweetqueue/blob/e54972a0137ea2a21b2357b81408d9d4c92fdd61/tweetqueue/__main__.py#L19-L73
246,109
billyoverton/tweetqueue
tweetqueue/__main__.py
tweet
def tweet(ctx, message): """Sends a tweet directly to your timeline""" if not valid_tweet(message): click.echo("Message is too long for twitter.") click.echo("Message:" + message) ctx.exit(2) if not ctx.obj['DRYRUN']: ctx.obj['TWEEPY_API'].update_status(message) else: click.echo("Tweet not sent due to dry-run mode.")
python
def tweet(ctx, message): """Sends a tweet directly to your timeline""" if not valid_tweet(message): click.echo("Message is too long for twitter.") click.echo("Message:" + message) ctx.exit(2) if not ctx.obj['DRYRUN']: ctx.obj['TWEEPY_API'].update_status(message) else: click.echo("Tweet not sent due to dry-run mode.")
[ "def", "tweet", "(", "ctx", ",", "message", ")", ":", "if", "not", "valid_tweet", "(", "message", ")", ":", "click", ".", "echo", "(", "\"Message is too long for twitter.\"", ")", "click", ".", "echo", "(", "\"Message:\"", "+", "message", ")", "ctx", ".", "exit", "(", "2", ")", "if", "not", "ctx", ".", "obj", "[", "'DRYRUN'", "]", ":", "ctx", ".", "obj", "[", "'TWEEPY_API'", "]", ".", "update_status", "(", "message", ")", "else", ":", "click", ".", "echo", "(", "\"Tweet not sent due to dry-run mode.\"", ")" ]
Sends a tweet directly to your timeline
[ "Sends", "a", "tweet", "directly", "to", "your", "timeline" ]
e54972a0137ea2a21b2357b81408d9d4c92fdd61
https://github.com/billyoverton/tweetqueue/blob/e54972a0137ea2a21b2357b81408d9d4c92fdd61/tweetqueue/__main__.py#L78-L88
246,110
billyoverton/tweetqueue
tweetqueue/__main__.py
queue
def queue(ctx, message): """Adds a message to your twitter queue""" if not valid_tweet(message): click.echo("Message is too long for twitter.") click.echo("Message: " + message) ctx.exit(2) if ctx.obj['DRYRUN']: click.echo("Message not queue due to dry-run mode.") ctx.exit(0) ctx.obj['TWEETLIST'].append(message)
python
def queue(ctx, message): """Adds a message to your twitter queue""" if not valid_tweet(message): click.echo("Message is too long for twitter.") click.echo("Message: " + message) ctx.exit(2) if ctx.obj['DRYRUN']: click.echo("Message not queue due to dry-run mode.") ctx.exit(0) ctx.obj['TWEETLIST'].append(message)
[ "def", "queue", "(", "ctx", ",", "message", ")", ":", "if", "not", "valid_tweet", "(", "message", ")", ":", "click", ".", "echo", "(", "\"Message is too long for twitter.\"", ")", "click", ".", "echo", "(", "\"Message: \"", "+", "message", ")", "ctx", ".", "exit", "(", "2", ")", "if", "ctx", ".", "obj", "[", "'DRYRUN'", "]", ":", "click", ".", "echo", "(", "\"Message not queue due to dry-run mode.\"", ")", "ctx", ".", "exit", "(", "0", ")", "ctx", ".", "obj", "[", "'TWEETLIST'", "]", ".", "append", "(", "message", ")" ]
Adds a message to your twitter queue
[ "Adds", "a", "message", "to", "your", "twitter", "queue" ]
e54972a0137ea2a21b2357b81408d9d4c92fdd61
https://github.com/billyoverton/tweetqueue/blob/e54972a0137ea2a21b2357b81408d9d4c92fdd61/tweetqueue/__main__.py#L93-L104
246,111
billyoverton/tweetqueue
tweetqueue/__main__.py
dequeue
def dequeue(ctx): """Sends a tweet from the queue""" tweet =ctx.obj['TWEETLIST'].peek() if tweet is None: click.echo("Nothing to dequeue.") ctx.exit(1) if ctx.obj['DRYRUN']: click.echo(tweet) else: tweet = ctx.obj['TWEETLIST'].pop() ctx.obj['TWEEPY_API'].update_status(tweet)
python
def dequeue(ctx): """Sends a tweet from the queue""" tweet =ctx.obj['TWEETLIST'].peek() if tweet is None: click.echo("Nothing to dequeue.") ctx.exit(1) if ctx.obj['DRYRUN']: click.echo(tweet) else: tweet = ctx.obj['TWEETLIST'].pop() ctx.obj['TWEEPY_API'].update_status(tweet)
[ "def", "dequeue", "(", "ctx", ")", ":", "tweet", "=", "ctx", ".", "obj", "[", "'TWEETLIST'", "]", ".", "peek", "(", ")", "if", "tweet", "is", "None", ":", "click", ".", "echo", "(", "\"Nothing to dequeue.\"", ")", "ctx", ".", "exit", "(", "1", ")", "if", "ctx", ".", "obj", "[", "'DRYRUN'", "]", ":", "click", ".", "echo", "(", "tweet", ")", "else", ":", "tweet", "=", "ctx", ".", "obj", "[", "'TWEETLIST'", "]", ".", "pop", "(", ")", "ctx", ".", "obj", "[", "'TWEEPY_API'", "]", ".", "update_status", "(", "tweet", ")" ]
Sends a tweet from the queue
[ "Sends", "a", "tweet", "from", "the", "queue" ]
e54972a0137ea2a21b2357b81408d9d4c92fdd61
https://github.com/billyoverton/tweetqueue/blob/e54972a0137ea2a21b2357b81408d9d4c92fdd61/tweetqueue/__main__.py#L108-L120
246,112
billyoverton/tweetqueue
tweetqueue/__main__.py
config
def config(ctx): """Creates a tweetqueue configuration file""" home_directory = os.path.expanduser('~') default_config_file = os.path.join(home_directory, '.tweetqueue') default_database_file = os.path.join(home_directory, '.tweetqueue.db') config = {} config['API_KEY'] = click.prompt('API Key') config['API_SECRET'] = click.prompt('API Secret') config['ACCESS_TOKEN'] = click.prompt('Access Token') config['ACCESS_TOKEN_SECRET'] = click.prompt('Access Token Secret') config['DATABASE_LOCATION'] = click.prompt('Database', default=default_database_file) config_file = click.prompt('\nSave to', default=default_config_file) if click.confirm('Do you want to save this configuration?', abort=True): f = open(config_file, 'wb') json.dump(config, f, indent=4, separators=(',',': ')) f.close()
python
def config(ctx): """Creates a tweetqueue configuration file""" home_directory = os.path.expanduser('~') default_config_file = os.path.join(home_directory, '.tweetqueue') default_database_file = os.path.join(home_directory, '.tweetqueue.db') config = {} config['API_KEY'] = click.prompt('API Key') config['API_SECRET'] = click.prompt('API Secret') config['ACCESS_TOKEN'] = click.prompt('Access Token') config['ACCESS_TOKEN_SECRET'] = click.prompt('Access Token Secret') config['DATABASE_LOCATION'] = click.prompt('Database', default=default_database_file) config_file = click.prompt('\nSave to', default=default_config_file) if click.confirm('Do you want to save this configuration?', abort=True): f = open(config_file, 'wb') json.dump(config, f, indent=4, separators=(',',': ')) f.close()
[ "def", "config", "(", "ctx", ")", ":", "home_directory", "=", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", "default_config_file", "=", "os", ".", "path", ".", "join", "(", "home_directory", ",", "'.tweetqueue'", ")", "default_database_file", "=", "os", ".", "path", ".", "join", "(", "home_directory", ",", "'.tweetqueue.db'", ")", "config", "=", "{", "}", "config", "[", "'API_KEY'", "]", "=", "click", ".", "prompt", "(", "'API Key'", ")", "config", "[", "'API_SECRET'", "]", "=", "click", ".", "prompt", "(", "'API Secret'", ")", "config", "[", "'ACCESS_TOKEN'", "]", "=", "click", ".", "prompt", "(", "'Access Token'", ")", "config", "[", "'ACCESS_TOKEN_SECRET'", "]", "=", "click", ".", "prompt", "(", "'Access Token Secret'", ")", "config", "[", "'DATABASE_LOCATION'", "]", "=", "click", ".", "prompt", "(", "'Database'", ",", "default", "=", "default_database_file", ")", "config_file", "=", "click", ".", "prompt", "(", "'\\nSave to'", ",", "default", "=", "default_config_file", ")", "if", "click", ".", "confirm", "(", "'Do you want to save this configuration?'", ",", "abort", "=", "True", ")", ":", "f", "=", "open", "(", "config_file", ",", "'wb'", ")", "json", ".", "dump", "(", "config", ",", "f", ",", "indent", "=", "4", ",", "separators", "=", "(", "','", ",", "': '", ")", ")", "f", ".", "close", "(", ")" ]
Creates a tweetqueue configuration file
[ "Creates", "a", "tweetqueue", "configuration", "file" ]
e54972a0137ea2a21b2357b81408d9d4c92fdd61
https://github.com/billyoverton/tweetqueue/blob/e54972a0137ea2a21b2357b81408d9d4c92fdd61/tweetqueue/__main__.py#L124-L143
246,113
billyoverton/tweetqueue
tweetqueue/__main__.py
delete
def delete(ctx,tweet): """Deletes a tweet from the queue with a given ID""" if not ctx.obj['DRYRUN']: try: ctx.obj['TWEETLIST'].delete(tweet) except ValueError as e: click.echo("Now tweet was found with that id.") ctx.exit(1) else: click.echo("Not ran due to dry-run.")
python
def delete(ctx,tweet): """Deletes a tweet from the queue with a given ID""" if not ctx.obj['DRYRUN']: try: ctx.obj['TWEETLIST'].delete(tweet) except ValueError as e: click.echo("Now tweet was found with that id.") ctx.exit(1) else: click.echo("Not ran due to dry-run.")
[ "def", "delete", "(", "ctx", ",", "tweet", ")", ":", "if", "not", "ctx", ".", "obj", "[", "'DRYRUN'", "]", ":", "try", ":", "ctx", ".", "obj", "[", "'TWEETLIST'", "]", ".", "delete", "(", "tweet", ")", "except", "ValueError", "as", "e", ":", "click", ".", "echo", "(", "\"Now tweet was found with that id.\"", ")", "ctx", ".", "exit", "(", "1", ")", "else", ":", "click", ".", "echo", "(", "\"Not ran due to dry-run.\"", ")" ]
Deletes a tweet from the queue with a given ID
[ "Deletes", "a", "tweet", "from", "the", "queue", "with", "a", "given", "ID" ]
e54972a0137ea2a21b2357b81408d9d4c92fdd61
https://github.com/billyoverton/tweetqueue/blob/e54972a0137ea2a21b2357b81408d9d4c92fdd61/tweetqueue/__main__.py#L148-L157
246,114
unionbilling/union-python
union/client.py
UnionClient.make_request
def make_request(self, model, action, url_params={}, post_data=None): ''' Send request to API then validate, parse, and return the response ''' url = self._create_url(model, **url_params) headers = self._headers(action) try: response = requests.request(action, url, headers=headers, data=post_data) except Exception as e: raise APIError("There was an error communicating with Union: %s" % e) if not self._is_valid(response): raise ValidationError("The Union response returned an error: %s" % response.content) return self._parse_response(response)
python
def make_request(self, model, action, url_params={}, post_data=None): ''' Send request to API then validate, parse, and return the response ''' url = self._create_url(model, **url_params) headers = self._headers(action) try: response = requests.request(action, url, headers=headers, data=post_data) except Exception as e: raise APIError("There was an error communicating with Union: %s" % e) if not self._is_valid(response): raise ValidationError("The Union response returned an error: %s" % response.content) return self._parse_response(response)
[ "def", "make_request", "(", "self", ",", "model", ",", "action", ",", "url_params", "=", "{", "}", ",", "post_data", "=", "None", ")", ":", "url", "=", "self", ".", "_create_url", "(", "model", ",", "*", "*", "url_params", ")", "headers", "=", "self", ".", "_headers", "(", "action", ")", "try", ":", "response", "=", "requests", ".", "request", "(", "action", ",", "url", ",", "headers", "=", "headers", ",", "data", "=", "post_data", ")", "except", "Exception", "as", "e", ":", "raise", "APIError", "(", "\"There was an error communicating with Union: %s\"", "%", "e", ")", "if", "not", "self", ".", "_is_valid", "(", "response", ")", ":", "raise", "ValidationError", "(", "\"The Union response returned an error: %s\"", "%", "response", ".", "content", ")", "return", "self", ".", "_parse_response", "(", "response", ")" ]
Send request to API then validate, parse, and return the response
[ "Send", "request", "to", "API", "then", "validate", "parse", "and", "return", "the", "response" ]
551e4fc1a0b395b632781d80527a3660a7c67c0c
https://github.com/unionbilling/union-python/blob/551e4fc1a0b395b632781d80527a3660a7c67c0c/union/client.py#L98-L113
246,115
ramrod-project/database-brain
schema/brain/queries/writes.py
insert_jobs
def insert_jobs(jobs, verify_jobs=True, conn=None): """ insert_jobs function inserts data into Brain.Jobs table jobs must be in Job format :param jobs: <list> of Jobs :param verify_jobs: <bool> :param conn: <rethinkdb.DefaultConnection> :return: <dict> rethinkdb insert response value """ assert isinstance(jobs, list) if verify_jobs \ and not verify({Jobs.DESCRIPTOR.name: jobs}, Jobs()): raise ValueError("Invalid Jobs") inserted = RBJ.insert(jobs).run(conn) return inserted
python
def insert_jobs(jobs, verify_jobs=True, conn=None): """ insert_jobs function inserts data into Brain.Jobs table jobs must be in Job format :param jobs: <list> of Jobs :param verify_jobs: <bool> :param conn: <rethinkdb.DefaultConnection> :return: <dict> rethinkdb insert response value """ assert isinstance(jobs, list) if verify_jobs \ and not verify({Jobs.DESCRIPTOR.name: jobs}, Jobs()): raise ValueError("Invalid Jobs") inserted = RBJ.insert(jobs).run(conn) return inserted
[ "def", "insert_jobs", "(", "jobs", ",", "verify_jobs", "=", "True", ",", "conn", "=", "None", ")", ":", "assert", "isinstance", "(", "jobs", ",", "list", ")", "if", "verify_jobs", "and", "not", "verify", "(", "{", "Jobs", ".", "DESCRIPTOR", ".", "name", ":", "jobs", "}", ",", "Jobs", "(", ")", ")", ":", "raise", "ValueError", "(", "\"Invalid Jobs\"", ")", "inserted", "=", "RBJ", ".", "insert", "(", "jobs", ")", ".", "run", "(", "conn", ")", "return", "inserted" ]
insert_jobs function inserts data into Brain.Jobs table jobs must be in Job format :param jobs: <list> of Jobs :param verify_jobs: <bool> :param conn: <rethinkdb.DefaultConnection> :return: <dict> rethinkdb insert response value
[ "insert_jobs", "function", "inserts", "data", "into", "Brain", ".", "Jobs", "table" ]
b024cb44f34cabb9d80af38271ddb65c25767083
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/queries/writes.py#L74-L90
246,116
ramrod-project/database-brain
schema/brain/queries/writes.py
update_job_status
def update_job_status(job_id, status, conn=None): """Updates a job to a new status :param job_id: <str> the id of the job :param status: <str> new status :param conn: <connection> a database connection (default: {None}) :return: <dict> the update dicts for the job and the output """ if status not in VALID_STATES: raise ValueError("Invalid status") job_update = RBJ.get(job_id).update({STATUS_FIELD: status}).run(conn) if job_update["replaced"] == 0 and job_update["unchanged"] == 0: raise ValueError("Unknown job_id: {}".format(job_id)) output_job_status = {OUTPUTJOB_FIELD: {STATUS_FIELD: status}} if RBO.index_list().contains(IDX_OUTPUT_JOB_ID).run(conn): # NEW output_update = RBO.get_all(job_id, index=IDX_OUTPUT_JOB_ID).update(output_job_status).run(conn) else: # OLD id_filter = (r.row[OUTPUTJOB_FIELD][ID_FIELD] == job_id) output_update = RBO.filter(id_filter).update(output_job_status).run(conn) return {str(RBJ): job_update, str(RBO): output_update}
python
def update_job_status(job_id, status, conn=None): """Updates a job to a new status :param job_id: <str> the id of the job :param status: <str> new status :param conn: <connection> a database connection (default: {None}) :return: <dict> the update dicts for the job and the output """ if status not in VALID_STATES: raise ValueError("Invalid status") job_update = RBJ.get(job_id).update({STATUS_FIELD: status}).run(conn) if job_update["replaced"] == 0 and job_update["unchanged"] == 0: raise ValueError("Unknown job_id: {}".format(job_id)) output_job_status = {OUTPUTJOB_FIELD: {STATUS_FIELD: status}} if RBO.index_list().contains(IDX_OUTPUT_JOB_ID).run(conn): # NEW output_update = RBO.get_all(job_id, index=IDX_OUTPUT_JOB_ID).update(output_job_status).run(conn) else: # OLD id_filter = (r.row[OUTPUTJOB_FIELD][ID_FIELD] == job_id) output_update = RBO.filter(id_filter).update(output_job_status).run(conn) return {str(RBJ): job_update, str(RBO): output_update}
[ "def", "update_job_status", "(", "job_id", ",", "status", ",", "conn", "=", "None", ")", ":", "if", "status", "not", "in", "VALID_STATES", ":", "raise", "ValueError", "(", "\"Invalid status\"", ")", "job_update", "=", "RBJ", ".", "get", "(", "job_id", ")", ".", "update", "(", "{", "STATUS_FIELD", ":", "status", "}", ")", ".", "run", "(", "conn", ")", "if", "job_update", "[", "\"replaced\"", "]", "==", "0", "and", "job_update", "[", "\"unchanged\"", "]", "==", "0", ":", "raise", "ValueError", "(", "\"Unknown job_id: {}\"", ".", "format", "(", "job_id", ")", ")", "output_job_status", "=", "{", "OUTPUTJOB_FIELD", ":", "{", "STATUS_FIELD", ":", "status", "}", "}", "if", "RBO", ".", "index_list", "(", ")", ".", "contains", "(", "IDX_OUTPUT_JOB_ID", ")", ".", "run", "(", "conn", ")", ":", "# NEW", "output_update", "=", "RBO", ".", "get_all", "(", "job_id", ",", "index", "=", "IDX_OUTPUT_JOB_ID", ")", ".", "update", "(", "output_job_status", ")", ".", "run", "(", "conn", ")", "else", ":", "# OLD", "id_filter", "=", "(", "r", ".", "row", "[", "OUTPUTJOB_FIELD", "]", "[", "ID_FIELD", "]", "==", "job_id", ")", "output_update", "=", "RBO", ".", "filter", "(", "id_filter", ")", ".", "update", "(", "output_job_status", ")", ".", "run", "(", "conn", ")", "return", "{", "str", "(", "RBJ", ")", ":", "job_update", ",", "str", "(", "RBO", ")", ":", "output_update", "}" ]
Updates a job to a new status :param job_id: <str> the id of the job :param status: <str> new status :param conn: <connection> a database connection (default: {None}) :return: <dict> the update dicts for the job and the output
[ "Updates", "a", "job", "to", "a", "new", "status" ]
b024cb44f34cabb9d80af38271ddb65c25767083
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/queries/writes.py#L95-L117
246,117
ramrod-project/database-brain
schema/brain/queries/writes.py
write_output
def write_output(job_id, content, conn=None): """writes output to the output table :param job_id: <str> id of the job :param content: <str> output to write :param conn: """ output_job = get_job_by_id(job_id, conn) results = {} if output_job is not None: entry = { OUTPUTJOB_FIELD: output_job, CONTENT_FIELD: content } results = RBO.insert(entry, conflict=RDB_REPLACE).run(conn) return results
python
def write_output(job_id, content, conn=None): """writes output to the output table :param job_id: <str> id of the job :param content: <str> output to write :param conn: """ output_job = get_job_by_id(job_id, conn) results = {} if output_job is not None: entry = { OUTPUTJOB_FIELD: output_job, CONTENT_FIELD: content } results = RBO.insert(entry, conflict=RDB_REPLACE).run(conn) return results
[ "def", "write_output", "(", "job_id", ",", "content", ",", "conn", "=", "None", ")", ":", "output_job", "=", "get_job_by_id", "(", "job_id", ",", "conn", ")", "results", "=", "{", "}", "if", "output_job", "is", "not", "None", ":", "entry", "=", "{", "OUTPUTJOB_FIELD", ":", "output_job", ",", "CONTENT_FIELD", ":", "content", "}", "results", "=", "RBO", ".", "insert", "(", "entry", ",", "conflict", "=", "RDB_REPLACE", ")", ".", "run", "(", "conn", ")", "return", "results" ]
writes output to the output table :param job_id: <str> id of the job :param content: <str> output to write :param conn:
[ "writes", "output", "to", "the", "output", "table" ]
b024cb44f34cabb9d80af38271ddb65c25767083
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/queries/writes.py#L122-L137
246,118
Pringley/rw
rw/__init__.py
generate_words
def generate_words(numberofwords, wordlist, secure=None): """Generate a list of random words from wordlist.""" if not secure: chooser = random.choice else: chooser = random.SystemRandom().choice return [chooser(wordlist) for _ in range(numberofwords)]
python
def generate_words(numberofwords, wordlist, secure=None): """Generate a list of random words from wordlist.""" if not secure: chooser = random.choice else: chooser = random.SystemRandom().choice return [chooser(wordlist) for _ in range(numberofwords)]
[ "def", "generate_words", "(", "numberofwords", ",", "wordlist", ",", "secure", "=", "None", ")", ":", "if", "not", "secure", ":", "chooser", "=", "random", ".", "choice", "else", ":", "chooser", "=", "random", ".", "SystemRandom", "(", ")", ".", "choice", "return", "[", "chooser", "(", "wordlist", ")", "for", "_", "in", "range", "(", "numberofwords", ")", "]" ]
Generate a list of random words from wordlist.
[ "Generate", "a", "list", "of", "random", "words", "from", "wordlist", "." ]
0d1d9933030621c60e051a8bea3b5f520aa33efd
https://github.com/Pringley/rw/blob/0d1d9933030621c60e051a8bea3b5f520aa33efd/rw/__init__.py#L28-L34
246,119
Pringley/rw
rw/__init__.py
load_stream
def load_stream(filename): """Load a file stream from the package resources.""" rawfile = pkg_resources.resource_stream(__name__, filename) if six.PY2: return rawfile return io.TextIOWrapper(rawfile, 'utf-8')
python
def load_stream(filename): """Load a file stream from the package resources.""" rawfile = pkg_resources.resource_stream(__name__, filename) if six.PY2: return rawfile return io.TextIOWrapper(rawfile, 'utf-8')
[ "def", "load_stream", "(", "filename", ")", ":", "rawfile", "=", "pkg_resources", ".", "resource_stream", "(", "__name__", ",", "filename", ")", "if", "six", ".", "PY2", ":", "return", "rawfile", "return", "io", ".", "TextIOWrapper", "(", "rawfile", ",", "'utf-8'", ")" ]
Load a file stream from the package resources.
[ "Load", "a", "file", "stream", "from", "the", "package", "resources", "." ]
0d1d9933030621c60e051a8bea3b5f520aa33efd
https://github.com/Pringley/rw/blob/0d1d9933030621c60e051a8bea3b5f520aa33efd/rw/__init__.py#L40-L45
246,120
Pringley/rw
rw/__init__.py
cli
def cli(): """Run the command line interface.""" args = docopt.docopt(__doc__, version=__VERSION__) secure = args['--secure'] numberofwords = int(args['<numberofwords>']) dictpath = args['--dict'] if dictpath is not None: dictfile = open(dictpath) else: dictfile = load_stream('words.txt') with dictfile: wordlist = read_wordlist(dictfile) words = generate_words(numberofwords, wordlist, secure=secure) print(' '.join(words))
python
def cli(): """Run the command line interface.""" args = docopt.docopt(__doc__, version=__VERSION__) secure = args['--secure'] numberofwords = int(args['<numberofwords>']) dictpath = args['--dict'] if dictpath is not None: dictfile = open(dictpath) else: dictfile = load_stream('words.txt') with dictfile: wordlist = read_wordlist(dictfile) words = generate_words(numberofwords, wordlist, secure=secure) print(' '.join(words))
[ "def", "cli", "(", ")", ":", "args", "=", "docopt", ".", "docopt", "(", "__doc__", ",", "version", "=", "__VERSION__", ")", "secure", "=", "args", "[", "'--secure'", "]", "numberofwords", "=", "int", "(", "args", "[", "'<numberofwords>'", "]", ")", "dictpath", "=", "args", "[", "'--dict'", "]", "if", "dictpath", "is", "not", "None", ":", "dictfile", "=", "open", "(", "dictpath", ")", "else", ":", "dictfile", "=", "load_stream", "(", "'words.txt'", ")", "with", "dictfile", ":", "wordlist", "=", "read_wordlist", "(", "dictfile", ")", "words", "=", "generate_words", "(", "numberofwords", ",", "wordlist", ",", "secure", "=", "secure", ")", "print", "(", "' '", ".", "join", "(", "words", ")", ")" ]
Run the command line interface.
[ "Run", "the", "command", "line", "interface", "." ]
0d1d9933030621c60e051a8bea3b5f520aa33efd
https://github.com/Pringley/rw/blob/0d1d9933030621c60e051a8bea3b5f520aa33efd/rw/__init__.py#L47-L62
246,121
minhhoit/yacms
yacms/pages/page_processors.py
processor_for
def processor_for(content_model_or_slug, exact_page=False): """ Decorator that registers the decorated function as a page processor for the given content model or slug. When a page exists that forms the prefix of custom urlpatterns in a project (eg: the blog page and app), the page will be added to the template context. Passing in ``True`` for the ``exact_page`` arg, will ensure that the page processor is not run in this situation, requiring that the loaded page object is for the exact URL currently being viewed. """ content_model = None slug = "" if isinstance(content_model_or_slug, (str, _str)): try: parts = content_model_or_slug.split(".", 1) content_model = apps.get_model(*parts) except (TypeError, ValueError, LookupError): slug = content_model_or_slug elif issubclass(content_model_or_slug, Page): content_model = content_model_or_slug else: raise TypeError("%s is not a valid argument for page_processor, " "which should be a model subclass of Page in class " "or string form (app.model), or a valid slug" % content_model_or_slug) def decorator(func): parts = (func, exact_page) if content_model: model_name = content_model._meta.object_name.lower() processors[model_name].insert(0, parts) else: processors["slug:%s" % slug].insert(0, parts) return func return decorator
python
def processor_for(content_model_or_slug, exact_page=False): """ Decorator that registers the decorated function as a page processor for the given content model or slug. When a page exists that forms the prefix of custom urlpatterns in a project (eg: the blog page and app), the page will be added to the template context. Passing in ``True`` for the ``exact_page`` arg, will ensure that the page processor is not run in this situation, requiring that the loaded page object is for the exact URL currently being viewed. """ content_model = None slug = "" if isinstance(content_model_or_slug, (str, _str)): try: parts = content_model_or_slug.split(".", 1) content_model = apps.get_model(*parts) except (TypeError, ValueError, LookupError): slug = content_model_or_slug elif issubclass(content_model_or_slug, Page): content_model = content_model_or_slug else: raise TypeError("%s is not a valid argument for page_processor, " "which should be a model subclass of Page in class " "or string form (app.model), or a valid slug" % content_model_or_slug) def decorator(func): parts = (func, exact_page) if content_model: model_name = content_model._meta.object_name.lower() processors[model_name].insert(0, parts) else: processors["slug:%s" % slug].insert(0, parts) return func return decorator
[ "def", "processor_for", "(", "content_model_or_slug", ",", "exact_page", "=", "False", ")", ":", "content_model", "=", "None", "slug", "=", "\"\"", "if", "isinstance", "(", "content_model_or_slug", ",", "(", "str", ",", "_str", ")", ")", ":", "try", ":", "parts", "=", "content_model_or_slug", ".", "split", "(", "\".\"", ",", "1", ")", "content_model", "=", "apps", ".", "get_model", "(", "*", "parts", ")", "except", "(", "TypeError", ",", "ValueError", ",", "LookupError", ")", ":", "slug", "=", "content_model_or_slug", "elif", "issubclass", "(", "content_model_or_slug", ",", "Page", ")", ":", "content_model", "=", "content_model_or_slug", "else", ":", "raise", "TypeError", "(", "\"%s is not a valid argument for page_processor, \"", "\"which should be a model subclass of Page in class \"", "\"or string form (app.model), or a valid slug\"", "%", "content_model_or_slug", ")", "def", "decorator", "(", "func", ")", ":", "parts", "=", "(", "func", ",", "exact_page", ")", "if", "content_model", ":", "model_name", "=", "content_model", ".", "_meta", ".", "object_name", ".", "lower", "(", ")", "processors", "[", "model_name", "]", ".", "insert", "(", "0", ",", "parts", ")", "else", ":", "processors", "[", "\"slug:%s\"", "%", "slug", "]", ".", "insert", "(", "0", ",", "parts", ")", "return", "func", "return", "decorator" ]
Decorator that registers the decorated function as a page processor for the given content model or slug. When a page exists that forms the prefix of custom urlpatterns in a project (eg: the blog page and app), the page will be added to the template context. Passing in ``True`` for the ``exact_page`` arg, will ensure that the page processor is not run in this situation, requiring that the loaded page object is for the exact URL currently being viewed.
[ "Decorator", "that", "registers", "the", "decorated", "function", "as", "a", "page", "processor", "for", "the", "given", "content", "model", "or", "slug", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/pages/page_processors.py#L17-L53
246,122
minhhoit/yacms
yacms/pages/page_processors.py
autodiscover
def autodiscover(): """ Taken from ``django.contrib.admin.autodiscover`` and used to run any calls to the ``processor_for`` decorator. """ global LOADED if LOADED: return LOADED = True for app in get_app_name_list(): try: module = import_module(app) except ImportError: pass else: try: import_module("%s.page_processors" % app) except: if module_has_submodule(module, "page_processors"): raise
python
def autodiscover(): """ Taken from ``django.contrib.admin.autodiscover`` and used to run any calls to the ``processor_for`` decorator. """ global LOADED if LOADED: return LOADED = True for app in get_app_name_list(): try: module = import_module(app) except ImportError: pass else: try: import_module("%s.page_processors" % app) except: if module_has_submodule(module, "page_processors"): raise
[ "def", "autodiscover", "(", ")", ":", "global", "LOADED", "if", "LOADED", ":", "return", "LOADED", "=", "True", "for", "app", "in", "get_app_name_list", "(", ")", ":", "try", ":", "module", "=", "import_module", "(", "app", ")", "except", "ImportError", ":", "pass", "else", ":", "try", ":", "import_module", "(", "\"%s.page_processors\"", "%", "app", ")", "except", ":", "if", "module_has_submodule", "(", "module", ",", "\"page_processors\"", ")", ":", "raise" ]
Taken from ``django.contrib.admin.autodiscover`` and used to run any calls to the ``processor_for`` decorator.
[ "Taken", "from", "django", ".", "contrib", ".", "admin", ".", "autodiscover", "and", "used", "to", "run", "any", "calls", "to", "the", "processor_for", "decorator", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/pages/page_processors.py#L59-L78
246,123
praekelt/jmbo-poll
poll/models.py
Poll.can_vote_on_poll
def can_vote_on_poll(self, request): """Based on jmbo.models.can_vote.""" # can't vote if liking is closed if self.votes_closed: return False, 'closed' # can't vote if liking is disabled if not self.votes_enabled: return False, 'disabled' # anonymous users can't vote if anonymous votes are disabled if not request.user.is_authenticated() and not \ self.anonymous_votes: return False, 'auth_required' # return false if existing votes are found votes = Vote.objects.filter( object_id__in=[o.id for o in self.polloption_set.all()], token=request.secretballot_token ) if votes.exists(): return False, 'voted' else: return True, 'can_vote'
python
def can_vote_on_poll(self, request): """Based on jmbo.models.can_vote.""" # can't vote if liking is closed if self.votes_closed: return False, 'closed' # can't vote if liking is disabled if not self.votes_enabled: return False, 'disabled' # anonymous users can't vote if anonymous votes are disabled if not request.user.is_authenticated() and not \ self.anonymous_votes: return False, 'auth_required' # return false if existing votes are found votes = Vote.objects.filter( object_id__in=[o.id for o in self.polloption_set.all()], token=request.secretballot_token ) if votes.exists(): return False, 'voted' else: return True, 'can_vote'
[ "def", "can_vote_on_poll", "(", "self", ",", "request", ")", ":", "# can't vote if liking is closed", "if", "self", ".", "votes_closed", ":", "return", "False", ",", "'closed'", "# can't vote if liking is disabled", "if", "not", "self", ".", "votes_enabled", ":", "return", "False", ",", "'disabled'", "# anonymous users can't vote if anonymous votes are disabled", "if", "not", "request", ".", "user", ".", "is_authenticated", "(", ")", "and", "not", "self", ".", "anonymous_votes", ":", "return", "False", ",", "'auth_required'", "# return false if existing votes are found", "votes", "=", "Vote", ".", "objects", ".", "filter", "(", "object_id__in", "=", "[", "o", ".", "id", "for", "o", "in", "self", ".", "polloption_set", ".", "all", "(", ")", "]", ",", "token", "=", "request", ".", "secretballot_token", ")", "if", "votes", ".", "exists", "(", ")", ":", "return", "False", ",", "'voted'", "else", ":", "return", "True", ",", "'can_vote'" ]
Based on jmbo.models.can_vote.
[ "Based", "on", "jmbo", ".", "models", ".", "can_vote", "." ]
322cd398372139e9db74a37cb2ce8ab1c2ef17fd
https://github.com/praekelt/jmbo-poll/blob/322cd398372139e9db74a37cb2ce8ab1c2ef17fd/poll/models.py#L30-L54
246,124
praekelt/jmbo-poll
poll/models.py
Poll.vote_count
def vote_count(self): """ Returns the total number of votes cast across all the poll's options. """ return Vote.objects.filter( content_type=ContentType.objects.get(app_label='poll', model='polloption'), object_id__in=[o.id for o in self.polloption_set.all()] ).aggregate(Sum('vote'))['vote__sum'] or 0
python
def vote_count(self): """ Returns the total number of votes cast across all the poll's options. """ return Vote.objects.filter( content_type=ContentType.objects.get(app_label='poll', model='polloption'), object_id__in=[o.id for o in self.polloption_set.all()] ).aggregate(Sum('vote'))['vote__sum'] or 0
[ "def", "vote_count", "(", "self", ")", ":", "return", "Vote", ".", "objects", ".", "filter", "(", "content_type", "=", "ContentType", ".", "objects", ".", "get", "(", "app_label", "=", "'poll'", ",", "model", "=", "'polloption'", ")", ",", "object_id__in", "=", "[", "o", ".", "id", "for", "o", "in", "self", ".", "polloption_set", ".", "all", "(", ")", "]", ")", ".", "aggregate", "(", "Sum", "(", "'vote'", ")", ")", "[", "'vote__sum'", "]", "or", "0" ]
Returns the total number of votes cast across all the poll's options.
[ "Returns", "the", "total", "number", "of", "votes", "cast", "across", "all", "the", "poll", "s", "options", "." ]
322cd398372139e9db74a37cb2ce8ab1c2ef17fd
https://github.com/praekelt/jmbo-poll/blob/322cd398372139e9db74a37cb2ce8ab1c2ef17fd/poll/models.py#L58-L66
246,125
praekelt/jmbo-poll
poll/models.py
PollOption.vote_count
def vote_count(self): """ Returns the total number of votes cast for this poll options. """ return Vote.objects.filter( content_type=ContentType.objects.get_for_model(self), object_id=self.id ).aggregate(Sum('vote'))['vote__sum'] or 0
python
def vote_count(self): """ Returns the total number of votes cast for this poll options. """ return Vote.objects.filter( content_type=ContentType.objects.get_for_model(self), object_id=self.id ).aggregate(Sum('vote'))['vote__sum'] or 0
[ "def", "vote_count", "(", "self", ")", ":", "return", "Vote", ".", "objects", ".", "filter", "(", "content_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "self", ")", ",", "object_id", "=", "self", ".", "id", ")", ".", "aggregate", "(", "Sum", "(", "'vote'", ")", ")", "[", "'vote__sum'", "]", "or", "0" ]
Returns the total number of votes cast for this poll options.
[ "Returns", "the", "total", "number", "of", "votes", "cast", "for", "this", "poll", "options", "." ]
322cd398372139e9db74a37cb2ce8ab1c2ef17fd
https://github.com/praekelt/jmbo-poll/blob/322cd398372139e9db74a37cb2ce8ab1c2ef17fd/poll/models.py#L82-L90
246,126
praekelt/jmbo-poll
poll/models.py
PollOption.percentage
def percentage(self): """ Returns the percentage of votes cast for this poll option in relation to all of its poll's other options. """ total_vote_count = self.poll.vote_count if total_vote_count: return self.vote_count * 100.0 / total_vote_count return 0
python
def percentage(self): """ Returns the percentage of votes cast for this poll option in relation to all of its poll's other options. """ total_vote_count = self.poll.vote_count if total_vote_count: return self.vote_count * 100.0 / total_vote_count return 0
[ "def", "percentage", "(", "self", ")", ":", "total_vote_count", "=", "self", ".", "poll", ".", "vote_count", "if", "total_vote_count", ":", "return", "self", ".", "vote_count", "*", "100.0", "/", "total_vote_count", "return", "0" ]
Returns the percentage of votes cast for this poll option in relation to all of its poll's other options.
[ "Returns", "the", "percentage", "of", "votes", "cast", "for", "this", "poll", "option", "in", "relation", "to", "all", "of", "its", "poll", "s", "other", "options", "." ]
322cd398372139e9db74a37cb2ce8ab1c2ef17fd
https://github.com/praekelt/jmbo-poll/blob/322cd398372139e9db74a37cb2ce8ab1c2ef17fd/poll/models.py#L92-L100
246,127
ECESeniorDesign/lazy_record
lazy_record/query.py
does_not_mutate
def does_not_mutate(func): """Prevents methods from mutating the receiver""" def wrapper(self, *args, **kwargs): new = self.copy() return func(new, *args, **kwargs) wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ return wrapper
python
def does_not_mutate(func): """Prevents methods from mutating the receiver""" def wrapper(self, *args, **kwargs): new = self.copy() return func(new, *args, **kwargs) wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ return wrapper
[ "def", "does_not_mutate", "(", "func", ")", ":", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "new", "=", "self", ".", "copy", "(", ")", "return", "func", "(", "new", ",", "*", "args", ",", "*", "*", "kwargs", ")", "wrapper", ".", "__name__", "=", "func", ".", "__name__", "wrapper", ".", "__doc__", "=", "func", ".", "__doc__", "return", "wrapper" ]
Prevents methods from mutating the receiver
[ "Prevents", "methods", "from", "mutating", "the", "receiver" ]
929d3cc7c2538b0f792365c0d2b0e0d41084c2dd
https://github.com/ECESeniorDesign/lazy_record/blob/929d3cc7c2538b0f792365c0d2b0e0d41084c2dd/lazy_record/query.py#L10-L17
246,128
ECESeniorDesign/lazy_record
lazy_record/query.py
Query.find_by
def find_by(self, **kwargs): """ Find first record subject to restrictions in +kwargs+, raising RecordNotFound if no such record exists. """ result = self.where(**kwargs).first() if result: return result else: raise RecordNotFound(kwargs)
python
def find_by(self, **kwargs): """ Find first record subject to restrictions in +kwargs+, raising RecordNotFound if no such record exists. """ result = self.where(**kwargs).first() if result: return result else: raise RecordNotFound(kwargs)
[ "def", "find_by", "(", "self", ",", "*", "*", "kwargs", ")", ":", "result", "=", "self", ".", "where", "(", "*", "*", "kwargs", ")", ".", "first", "(", ")", "if", "result", ":", "return", "result", "else", ":", "raise", "RecordNotFound", "(", "kwargs", ")" ]
Find first record subject to restrictions in +kwargs+, raising RecordNotFound if no such record exists.
[ "Find", "first", "record", "subject", "to", "restrictions", "in", "+", "kwargs", "+", "raising", "RecordNotFound", "if", "no", "such", "record", "exists", "." ]
929d3cc7c2538b0f792365c0d2b0e0d41084c2dd
https://github.com/ECESeniorDesign/lazy_record/blob/929d3cc7c2538b0f792365c0d2b0e0d41084c2dd/lazy_record/query.py#L68-L77
246,129
ECESeniorDesign/lazy_record
lazy_record/query.py
Query.where
def where(self, *custom_restrictions, **restrictions): """ Restricts the records to the query subject to the passed +restrictions+. Analog to "WHERE" in SQL. Can pass multiple restrictions, and can invoke this method multiple times per query. """ for attr, value in restrictions.items(): self.where_query[attr] = value if custom_restrictions: self.custom_where.append(tuple(custom_restrictions)) return self
python
def where(self, *custom_restrictions, **restrictions): """ Restricts the records to the query subject to the passed +restrictions+. Analog to "WHERE" in SQL. Can pass multiple restrictions, and can invoke this method multiple times per query. """ for attr, value in restrictions.items(): self.where_query[attr] = value if custom_restrictions: self.custom_where.append(tuple(custom_restrictions)) return self
[ "def", "where", "(", "self", ",", "*", "custom_restrictions", ",", "*", "*", "restrictions", ")", ":", "for", "attr", ",", "value", "in", "restrictions", ".", "items", "(", ")", ":", "self", ".", "where_query", "[", "attr", "]", "=", "value", "if", "custom_restrictions", ":", "self", ".", "custom_where", ".", "append", "(", "tuple", "(", "custom_restrictions", ")", ")", "return", "self" ]
Restricts the records to the query subject to the passed +restrictions+. Analog to "WHERE" in SQL. Can pass multiple restrictions, and can invoke this method multiple times per query.
[ "Restricts", "the", "records", "to", "the", "query", "subject", "to", "the", "passed", "+", "restrictions", "+", ".", "Analog", "to", "WHERE", "in", "SQL", ".", "Can", "pass", "multiple", "restrictions", "and", "can", "invoke", "this", "method", "multiple", "times", "per", "query", "." ]
929d3cc7c2538b0f792365c0d2b0e0d41084c2dd
https://github.com/ECESeniorDesign/lazy_record/blob/929d3cc7c2538b0f792365c0d2b0e0d41084c2dd/lazy_record/query.py#L130-L140
246,130
ECESeniorDesign/lazy_record
lazy_record/query.py
Query.joins
def joins(self, table): """ Analog to "INNER JOIN" in SQL on the passed +table+. Use only once per query. """ def do_join(table, model): while model is not associations.model_from_name(table): # ex) Category -> Forum -> Thread -> Post # Category: {"posts": "forums"} # Forum: {"posts": "threads"} # Thread: {"posts": None} # >>> Category.joins("posts") # => [ # {'table': 'forums', 'on': ['category_id', 'id']} # {'table': 'threads', 'on': ['forum_id', 'id']} # {'table': 'posts', 'on': ['thread_id', 'id']} # ] if table in associations.associations_for(model): # This to next: one-many (they have the fk) # If associations.associations_for(model)[table] is None, then this is # terminal (i.e. table is the FINAL association in the # chain) next_level = associations.associations_for(model)[table] or table next_model = associations.model_from_name(next_level) foreign_key = associations.foreign_keys_for(model).get( next_level, inflector.foreignKey(model.__name__)) yield {'table': next_level, 'on': [foreign_key, 'id']} else: # One-One or Many-One # singular table had better be in associations.associations_for(model) singular = inflector.singularize(table) next_level = associations.associations_for(model)[singular] or singular next_model = associations.model_from_name(next_level) this_table_name = Repo.table_name(model) foreign_key = associations.foreign_keys_for(model).get( next_level, inflector.foreignKey(model.__name__)) if associations.model_has_foreign_key_for_table(table, model): # we have the foreign key order = ['id', foreign_key] else: # They have the foreign key order = [foreign_key, 'id'] yield {'table': inflector.pluralize(next_level), 'on': order} model = next_model self.join_args = list(do_join(table, self.model)) return self
python
def joins(self, table): """ Analog to "INNER JOIN" in SQL on the passed +table+. Use only once per query. """ def do_join(table, model): while model is not associations.model_from_name(table): # ex) Category -> Forum -> Thread -> Post # Category: {"posts": "forums"} # Forum: {"posts": "threads"} # Thread: {"posts": None} # >>> Category.joins("posts") # => [ # {'table': 'forums', 'on': ['category_id', 'id']} # {'table': 'threads', 'on': ['forum_id', 'id']} # {'table': 'posts', 'on': ['thread_id', 'id']} # ] if table in associations.associations_for(model): # This to next: one-many (they have the fk) # If associations.associations_for(model)[table] is None, then this is # terminal (i.e. table is the FINAL association in the # chain) next_level = associations.associations_for(model)[table] or table next_model = associations.model_from_name(next_level) foreign_key = associations.foreign_keys_for(model).get( next_level, inflector.foreignKey(model.__name__)) yield {'table': next_level, 'on': [foreign_key, 'id']} else: # One-One or Many-One # singular table had better be in associations.associations_for(model) singular = inflector.singularize(table) next_level = associations.associations_for(model)[singular] or singular next_model = associations.model_from_name(next_level) this_table_name = Repo.table_name(model) foreign_key = associations.foreign_keys_for(model).get( next_level, inflector.foreignKey(model.__name__)) if associations.model_has_foreign_key_for_table(table, model): # we have the foreign key order = ['id', foreign_key] else: # They have the foreign key order = [foreign_key, 'id'] yield {'table': inflector.pluralize(next_level), 'on': order} model = next_model self.join_args = list(do_join(table, self.model)) return self
[ "def", "joins", "(", "self", ",", "table", ")", ":", "def", "do_join", "(", "table", ",", "model", ")", ":", "while", "model", "is", "not", "associations", ".", "model_from_name", "(", "table", ")", ":", "# ex) Category -> Forum -> Thread -> Post", "# Category: {\"posts\": \"forums\"}", "# Forum: {\"posts\": \"threads\"}", "# Thread: {\"posts\": None}", "# >>> Category.joins(\"posts\")", "# => [", "# {'table': 'forums', 'on': ['category_id', 'id']}", "# {'table': 'threads', 'on': ['forum_id', 'id']}", "# {'table': 'posts', 'on': ['thread_id', 'id']}", "# ]", "if", "table", "in", "associations", ".", "associations_for", "(", "model", ")", ":", "# This to next: one-many (they have the fk)", "# If associations.associations_for(model)[table] is None, then this is", "# terminal (i.e. table is the FINAL association in the", "# chain)", "next_level", "=", "associations", ".", "associations_for", "(", "model", ")", "[", "table", "]", "or", "table", "next_model", "=", "associations", ".", "model_from_name", "(", "next_level", ")", "foreign_key", "=", "associations", ".", "foreign_keys_for", "(", "model", ")", ".", "get", "(", "next_level", ",", "inflector", ".", "foreignKey", "(", "model", ".", "__name__", ")", ")", "yield", "{", "'table'", ":", "next_level", ",", "'on'", ":", "[", "foreign_key", ",", "'id'", "]", "}", "else", ":", "# One-One or Many-One", "# singular table had better be in associations.associations_for(model)", "singular", "=", "inflector", ".", "singularize", "(", "table", ")", "next_level", "=", "associations", ".", "associations_for", "(", "model", ")", "[", "singular", "]", "or", "singular", "next_model", "=", "associations", ".", "model_from_name", "(", "next_level", ")", "this_table_name", "=", "Repo", ".", "table_name", "(", "model", ")", "foreign_key", "=", "associations", ".", "foreign_keys_for", "(", "model", ")", ".", "get", "(", "next_level", ",", "inflector", ".", "foreignKey", "(", "model", ".", "__name__", ")", ")", "if", "associations", ".", "model_has_foreign_key_for_table", "(", "table", ",", "model", ")", ":", "# we have the foreign key", "order", "=", "[", "'id'", ",", "foreign_key", "]", "else", ":", "# They have the foreign key", "order", "=", "[", "foreign_key", ",", "'id'", "]", "yield", "{", "'table'", ":", "inflector", ".", "pluralize", "(", "next_level", ")", ",", "'on'", ":", "order", "}", "model", "=", "next_model", "self", ".", "join_args", "=", "list", "(", "do_join", "(", "table", ",", "self", ".", "model", ")", ")", "return", "self" ]
Analog to "INNER JOIN" in SQL on the passed +table+. Use only once per query.
[ "Analog", "to", "INNER", "JOIN", "in", "SQL", "on", "the", "passed", "+", "table", "+", ".", "Use", "only", "once", "per", "query", "." ]
929d3cc7c2538b0f792365c0d2b0e0d41084c2dd
https://github.com/ECESeniorDesign/lazy_record/blob/929d3cc7c2538b0f792365c0d2b0e0d41084c2dd/lazy_record/query.py#L143-L193
246,131
ECESeniorDesign/lazy_record
lazy_record/query.py
Query.create
def create(self, **attributes): """ Creates a new record suject to the restructions in the query and with the passed +attributes+. Operates using `build`. """ record = self.build(**attributes) record.save() return record
python
def create(self, **attributes): """ Creates a new record suject to the restructions in the query and with the passed +attributes+. Operates using `build`. """ record = self.build(**attributes) record.save() return record
[ "def", "create", "(", "self", ",", "*", "*", "attributes", ")", ":", "record", "=", "self", ".", "build", "(", "*", "*", "attributes", ")", "record", ".", "save", "(", ")", "return", "record" ]
Creates a new record suject to the restructions in the query and with the passed +attributes+. Operates using `build`.
[ "Creates", "a", "new", "record", "suject", "to", "the", "restructions", "in", "the", "query", "and", "with", "the", "passed", "+", "attributes", "+", ".", "Operates", "using", "build", "." ]
929d3cc7c2538b0f792365c0d2b0e0d41084c2dd
https://github.com/ECESeniorDesign/lazy_record/blob/929d3cc7c2538b0f792365c0d2b0e0d41084c2dd/lazy_record/query.py#L259-L266
246,132
polysquare/polysquare-generic-file-linter
polysquarelinter/technical_words_dictionary.py
create
def create(technical_terms_filename, spellchecker_cache_path): """Create a Dictionary at spellchecker_cache_path with technical words.""" user_dictionary = os.path.join(os.getcwd(), "DICTIONARY") user_words = read_dictionary_file(user_dictionary) technical_terms_set = set(user_words) if technical_terms_filename: with open(technical_terms_filename) as tech_tf: technical_terms_set |= set(tech_tf.read().splitlines()) return Dictionary(technical_terms_set, "technical_words", dictionary_sources=[technical_terms_filename, user_dictionary], cache=spellchecker_cache_path)
python
def create(technical_terms_filename, spellchecker_cache_path): """Create a Dictionary at spellchecker_cache_path with technical words.""" user_dictionary = os.path.join(os.getcwd(), "DICTIONARY") user_words = read_dictionary_file(user_dictionary) technical_terms_set = set(user_words) if technical_terms_filename: with open(technical_terms_filename) as tech_tf: technical_terms_set |= set(tech_tf.read().splitlines()) return Dictionary(technical_terms_set, "technical_words", dictionary_sources=[technical_terms_filename, user_dictionary], cache=spellchecker_cache_path)
[ "def", "create", "(", "technical_terms_filename", ",", "spellchecker_cache_path", ")", ":", "user_dictionary", "=", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "\"DICTIONARY\"", ")", "user_words", "=", "read_dictionary_file", "(", "user_dictionary", ")", "technical_terms_set", "=", "set", "(", "user_words", ")", "if", "technical_terms_filename", ":", "with", "open", "(", "technical_terms_filename", ")", "as", "tech_tf", ":", "technical_terms_set", "|=", "set", "(", "tech_tf", ".", "read", "(", ")", ".", "splitlines", "(", ")", ")", "return", "Dictionary", "(", "technical_terms_set", ",", "\"technical_words\"", ",", "dictionary_sources", "=", "[", "technical_terms_filename", ",", "user_dictionary", "]", ",", "cache", "=", "spellchecker_cache_path", ")" ]
Create a Dictionary at spellchecker_cache_path with technical words.
[ "Create", "a", "Dictionary", "at", "spellchecker_cache_path", "with", "technical", "words", "." ]
cfc88771acd3d5551c28fa5d917bb0aeb584c4cc
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/technical_words_dictionary.py#L15-L30
246,133
jjangsangy/kan
kan/structures.py
GoogleBooksAPIClient.connect
def connect(self, agent='Python'): """ Context manager for HTTP Connection state and ensures proper handling of network sockets, sends a GET request. Exception is raised at the yield statement. :yield request: FileIO<Socket> """ headers = {'User-Agent': agent} request = urlopen(Request(self.url, headers=headers)) try: yield request finally: request.close()
python
def connect(self, agent='Python'): """ Context manager for HTTP Connection state and ensures proper handling of network sockets, sends a GET request. Exception is raised at the yield statement. :yield request: FileIO<Socket> """ headers = {'User-Agent': agent} request = urlopen(Request(self.url, headers=headers)) try: yield request finally: request.close()
[ "def", "connect", "(", "self", ",", "agent", "=", "'Python'", ")", ":", "headers", "=", "{", "'User-Agent'", ":", "agent", "}", "request", "=", "urlopen", "(", "Request", "(", "self", ".", "url", ",", "headers", "=", "headers", ")", ")", "try", ":", "yield", "request", "finally", ":", "request", ".", "close", "(", ")" ]
Context manager for HTTP Connection state and ensures proper handling of network sockets, sends a GET request. Exception is raised at the yield statement. :yield request: FileIO<Socket>
[ "Context", "manager", "for", "HTTP", "Connection", "state", "and", "ensures", "proper", "handling", "of", "network", "sockets", "sends", "a", "GET", "request", "." ]
7da9d9ec5dc6b8bbb86cfd27d737978a406d9fa6
https://github.com/jjangsangy/kan/blob/7da9d9ec5dc6b8bbb86cfd27d737978a406d9fa6/kan/structures.py#L118-L132
246,134
jjangsangy/kan
kan/structures.py
GoogleBooksAPIClient.reader
def reader(self): """ Reads raw text from the connection stream. Ensures proper exception handling. :return bytes: request """ request_stream = '' with self.connect() as request: if request.msg != 'OK': raise HTTPError request_stream = request.read().decode('utf-8') return request_stream
python
def reader(self): """ Reads raw text from the connection stream. Ensures proper exception handling. :return bytes: request """ request_stream = '' with self.connect() as request: if request.msg != 'OK': raise HTTPError request_stream = request.read().decode('utf-8') return request_stream
[ "def", "reader", "(", "self", ")", ":", "request_stream", "=", "''", "with", "self", ".", "connect", "(", ")", "as", "request", ":", "if", "request", ".", "msg", "!=", "'OK'", ":", "raise", "HTTPError", "request_stream", "=", "request", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "return", "request_stream" ]
Reads raw text from the connection stream. Ensures proper exception handling. :return bytes: request
[ "Reads", "raw", "text", "from", "the", "connection", "stream", ".", "Ensures", "proper", "exception", "handling", "." ]
7da9d9ec5dc6b8bbb86cfd27d737978a406d9fa6
https://github.com/jjangsangy/kan/blob/7da9d9ec5dc6b8bbb86cfd27d737978a406d9fa6/kan/structures.py#L135-L147
246,135
jjangsangy/kan
kan/structures.py
GoogleBooksAPIClient.json
def json(self): """ Serializes json text stream into python dictionary. :return dict: json """ _json = json.loads(self.reader) if _json.get('error', None): raise HTTPError(_json['error']['errors']) return _json
python
def json(self): """ Serializes json text stream into python dictionary. :return dict: json """ _json = json.loads(self.reader) if _json.get('error', None): raise HTTPError(_json['error']['errors']) return _json
[ "def", "json", "(", "self", ")", ":", "_json", "=", "json", ".", "loads", "(", "self", ".", "reader", ")", "if", "_json", ".", "get", "(", "'error'", ",", "None", ")", ":", "raise", "HTTPError", "(", "_json", "[", "'error'", "]", "[", "'errors'", "]", ")", "return", "_json" ]
Serializes json text stream into python dictionary. :return dict: json
[ "Serializes", "json", "text", "stream", "into", "python", "dictionary", "." ]
7da9d9ec5dc6b8bbb86cfd27d737978a406d9fa6
https://github.com/jjangsangy/kan/blob/7da9d9ec5dc6b8bbb86cfd27d737978a406d9fa6/kan/structures.py#L150-L159
246,136
alfred82santa/dirty-loader
dirty_loader/__init__.py
import_class
def import_class(classpath, package=None): """ Load and return a class """ if '.' in classpath: module, classname = classpath.rsplit('.', 1) if package and not module.startswith('.'): module = '.{0}'.format(module) mod = import_module(module, package) else: classname = classpath mod = import_module(package) return getattr(mod, classname)
python
def import_class(classpath, package=None): """ Load and return a class """ if '.' in classpath: module, classname = classpath.rsplit('.', 1) if package and not module.startswith('.'): module = '.{0}'.format(module) mod = import_module(module, package) else: classname = classpath mod = import_module(package) return getattr(mod, classname)
[ "def", "import_class", "(", "classpath", ",", "package", "=", "None", ")", ":", "if", "'.'", "in", "classpath", ":", "module", ",", "classname", "=", "classpath", ".", "rsplit", "(", "'.'", ",", "1", ")", "if", "package", "and", "not", "module", ".", "startswith", "(", "'.'", ")", ":", "module", "=", "'.{0}'", ".", "format", "(", "module", ")", "mod", "=", "import_module", "(", "module", ",", "package", ")", "else", ":", "classname", "=", "classpath", "mod", "=", "import_module", "(", "package", ")", "return", "getattr", "(", "mod", ",", "classname", ")" ]
Load and return a class
[ "Load", "and", "return", "a", "class" ]
0d7895e3c84a0c197d804ce31305c5cba4c512e4
https://github.com/alfred82santa/dirty-loader/blob/0d7895e3c84a0c197d804ce31305c5cba4c512e4/dirty_loader/__init__.py#L423-L436
246,137
alfred82santa/dirty-loader
dirty_loader/__init__.py
Loader.register_module
def register_module(self, module, idx=-1): """ Register a module. You could indicate position inside inner list. :param module: must be a string or a module object to register. :type module: str :param idx: position where you want to insert new module. By default it is inserted at the end. :type idx: int """ if module in self._modules: raise AlreadyRegisteredError("Module '{0}' is already registered on loader.".format(module)) if idx < 0: self._modules.append(module) else: self._modules.insert(idx, module)
python
def register_module(self, module, idx=-1): """ Register a module. You could indicate position inside inner list. :param module: must be a string or a module object to register. :type module: str :param idx: position where you want to insert new module. By default it is inserted at the end. :type idx: int """ if module in self._modules: raise AlreadyRegisteredError("Module '{0}' is already registered on loader.".format(module)) if idx < 0: self._modules.append(module) else: self._modules.insert(idx, module)
[ "def", "register_module", "(", "self", ",", "module", ",", "idx", "=", "-", "1", ")", ":", "if", "module", "in", "self", ".", "_modules", ":", "raise", "AlreadyRegisteredError", "(", "\"Module '{0}' is already registered on loader.\"", ".", "format", "(", "module", ")", ")", "if", "idx", "<", "0", ":", "self", ".", "_modules", ".", "append", "(", "module", ")", "else", ":", "self", ".", "_modules", ".", "insert", "(", "idx", ",", "module", ")" ]
Register a module. You could indicate position inside inner list. :param module: must be a string or a module object to register. :type module: str :param idx: position where you want to insert new module. By default it is inserted at the end. :type idx: int
[ "Register", "a", "module", ".", "You", "could", "indicate", "position", "inside", "inner", "list", "." ]
0d7895e3c84a0c197d804ce31305c5cba4c512e4
https://github.com/alfred82santa/dirty-loader/blob/0d7895e3c84a0c197d804ce31305c5cba4c512e4/dirty_loader/__init__.py#L40-L56
246,138
alfred82santa/dirty-loader
dirty_loader/__init__.py
Loader.load_class
def load_class(self, classname): """ Loads a class looking for it in each module registered. :param classname: Class name you want to load. :type classname: str :return: Class object :rtype: type """ module_list = self._get_module_list() for module in module_list: try: return import_class(classname, module.__name__) except (AttributeError, ImportError): pass raise ImportError("Class '{0}' could not be loaded.".format(classname))
python
def load_class(self, classname): """ Loads a class looking for it in each module registered. :param classname: Class name you want to load. :type classname: str :return: Class object :rtype: type """ module_list = self._get_module_list() for module in module_list: try: return import_class(classname, module.__name__) except (AttributeError, ImportError): pass raise ImportError("Class '{0}' could not be loaded.".format(classname))
[ "def", "load_class", "(", "self", ",", "classname", ")", ":", "module_list", "=", "self", ".", "_get_module_list", "(", ")", "for", "module", "in", "module_list", ":", "try", ":", "return", "import_class", "(", "classname", ",", "module", ".", "__name__", ")", "except", "(", "AttributeError", ",", "ImportError", ")", ":", "pass", "raise", "ImportError", "(", "\"Class '{0}' could not be loaded.\"", ".", "format", "(", "classname", ")", ")" ]
Loads a class looking for it in each module registered. :param classname: Class name you want to load. :type classname: str :return: Class object :rtype: type
[ "Loads", "a", "class", "looking", "for", "it", "in", "each", "module", "registered", "." ]
0d7895e3c84a0c197d804ce31305c5cba4c512e4
https://github.com/alfred82santa/dirty-loader/blob/0d7895e3c84a0c197d804ce31305c5cba4c512e4/dirty_loader/__init__.py#L81-L99
246,139
alfred82santa/dirty-loader
dirty_loader/__init__.py
Loader.factory
def factory(self, classname, *args, **kwargs): """ Creates an instance of class looking for it in each module registered. You can add needed params to instance the class. :param classname: Class name you want to create an instance. :type classname: str :return: An instance of classname :rtype: object """ klass = self.load_class(classname) return self.get_factory_by_class(klass)(*args, **kwargs)
python
def factory(self, classname, *args, **kwargs): """ Creates an instance of class looking for it in each module registered. You can add needed params to instance the class. :param classname: Class name you want to create an instance. :type classname: str :return: An instance of classname :rtype: object """ klass = self.load_class(classname) return self.get_factory_by_class(klass)(*args, **kwargs)
[ "def", "factory", "(", "self", ",", "classname", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "klass", "=", "self", ".", "load_class", "(", "classname", ")", "return", "self", ".", "get_factory_by_class", "(", "klass", ")", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Creates an instance of class looking for it in each module registered. You can add needed params to instance the class. :param classname: Class name you want to create an instance. :type classname: str :return: An instance of classname :rtype: object
[ "Creates", "an", "instance", "of", "class", "looking", "for", "it", "in", "each", "module", "registered", ".", "You", "can", "add", "needed", "params", "to", "instance", "the", "class", "." ]
0d7895e3c84a0c197d804ce31305c5cba4c512e4
https://github.com/alfred82santa/dirty-loader/blob/0d7895e3c84a0c197d804ce31305c5cba4c512e4/dirty_loader/__init__.py#L105-L118
246,140
alfred82santa/dirty-loader
dirty_loader/__init__.py
Loader.get_factory_by_class
def get_factory_by_class(self, klass): """ Returns a custom factory for class. By default it will return the class itself. :param klass: Class type :type klass: type :return: Class factory :rtype: callable """ for check, factory in self._factories.items(): if klass is check: return factory(self, klass) for check, factory in self._factories.items(): if issubclass(klass, check): return factory(self, klass) return klass
python
def get_factory_by_class(self, klass): """ Returns a custom factory for class. By default it will return the class itself. :param klass: Class type :type klass: type :return: Class factory :rtype: callable """ for check, factory in self._factories.items(): if klass is check: return factory(self, klass) for check, factory in self._factories.items(): if issubclass(klass, check): return factory(self, klass) return klass
[ "def", "get_factory_by_class", "(", "self", ",", "klass", ")", ":", "for", "check", ",", "factory", "in", "self", ".", "_factories", ".", "items", "(", ")", ":", "if", "klass", "is", "check", ":", "return", "factory", "(", "self", ",", "klass", ")", "for", "check", ",", "factory", "in", "self", ".", "_factories", ".", "items", "(", ")", ":", "if", "issubclass", "(", "klass", ",", "check", ")", ":", "return", "factory", "(", "self", ",", "klass", ")", "return", "klass" ]
Returns a custom factory for class. By default it will return the class itself. :param klass: Class type :type klass: type :return: Class factory :rtype: callable
[ "Returns", "a", "custom", "factory", "for", "class", ".", "By", "default", "it", "will", "return", "the", "class", "itself", "." ]
0d7895e3c84a0c197d804ce31305c5cba4c512e4
https://github.com/alfred82santa/dirty-loader/blob/0d7895e3c84a0c197d804ce31305c5cba4c512e4/dirty_loader/__init__.py#L120-L135
246,141
alfred82santa/dirty-loader
dirty_loader/__init__.py
LoaderNamespace.register_module
def register_module(self, module, namespace=None): """ Register a module. :param module: must be a string or a module object to register. :type module: str :param namespace: Namespace tag. If it is None module will be used as namespace tag :type namespace: str """ namespace = namespace if namespace is not None else module \ if isinstance(module, str) else module.__name__ self.register_namespace(namespace, module)
python
def register_module(self, module, namespace=None): """ Register a module. :param module: must be a string or a module object to register. :type module: str :param namespace: Namespace tag. If it is None module will be used as namespace tag :type namespace: str """ namespace = namespace if namespace is not None else module \ if isinstance(module, str) else module.__name__ self.register_namespace(namespace, module)
[ "def", "register_module", "(", "self", ",", "module", ",", "namespace", "=", "None", ")", ":", "namespace", "=", "namespace", "if", "namespace", "is", "not", "None", "else", "module", "if", "isinstance", "(", "module", ",", "str", ")", "else", "module", ".", "__name__", "self", ".", "register_namespace", "(", "namespace", ",", "module", ")" ]
Register a module. :param module: must be a string or a module object to register. :type module: str :param namespace: Namespace tag. If it is None module will be used as namespace tag :type namespace: str
[ "Register", "a", "module", "." ]
0d7895e3c84a0c197d804ce31305c5cba4c512e4
https://github.com/alfred82santa/dirty-loader/blob/0d7895e3c84a0c197d804ce31305c5cba4c512e4/dirty_loader/__init__.py#L262-L273
246,142
alfred82santa/dirty-loader
dirty_loader/__init__.py
LoaderNamespace.register_namespace
def register_namespace(self, namespace, module): """ Register a namespace. :param namespace: Namespace tag. :type namespace: str :param module: must be a string or a module object to register. :type module: str """ if namespace in self._namespaces: raise AlreadyRegisteredError("Namespace '{0}' is already registered on loader.".format(namespace)) self._namespaces[namespace] = module
python
def register_namespace(self, namespace, module): """ Register a namespace. :param namespace: Namespace tag. :type namespace: str :param module: must be a string or a module object to register. :type module: str """ if namespace in self._namespaces: raise AlreadyRegisteredError("Namespace '{0}' is already registered on loader.".format(namespace)) self._namespaces[namespace] = module
[ "def", "register_namespace", "(", "self", ",", "namespace", ",", "module", ")", ":", "if", "namespace", "in", "self", ".", "_namespaces", ":", "raise", "AlreadyRegisteredError", "(", "\"Namespace '{0}' is already registered on loader.\"", ".", "format", "(", "namespace", ")", ")", "self", ".", "_namespaces", "[", "namespace", "]", "=", "module" ]
Register a namespace. :param namespace: Namespace tag. :type namespace: str :param module: must be a string or a module object to register. :type module: str
[ "Register", "a", "namespace", "." ]
0d7895e3c84a0c197d804ce31305c5cba4c512e4
https://github.com/alfred82santa/dirty-loader/blob/0d7895e3c84a0c197d804ce31305c5cba4c512e4/dirty_loader/__init__.py#L275-L287
246,143
alfred82santa/dirty-loader
dirty_loader/__init__.py
LoaderNamespace.unregister_namespace
def unregister_namespace(self, namespace): """ Unregister a namespace. :param namespace: Namespace tag. :type namespace: str """ if namespace not in self._namespaces: raise NoRegisteredError("Namespace '{0}' is not registered on loader.".format(namespace)) del self._namespaces[namespace]
python
def unregister_namespace(self, namespace): """ Unregister a namespace. :param namespace: Namespace tag. :type namespace: str """ if namespace not in self._namespaces: raise NoRegisteredError("Namespace '{0}' is not registered on loader.".format(namespace)) del self._namespaces[namespace]
[ "def", "unregister_namespace", "(", "self", ",", "namespace", ")", ":", "if", "namespace", "not", "in", "self", ".", "_namespaces", ":", "raise", "NoRegisteredError", "(", "\"Namespace '{0}' is not registered on loader.\"", ".", "format", "(", "namespace", ")", ")", "del", "self", ".", "_namespaces", "[", "namespace", "]" ]
Unregister a namespace. :param namespace: Namespace tag. :type namespace: str
[ "Unregister", "a", "namespace", "." ]
0d7895e3c84a0c197d804ce31305c5cba4c512e4
https://github.com/alfred82santa/dirty-loader/blob/0d7895e3c84a0c197d804ce31305c5cba4c512e4/dirty_loader/__init__.py#L303-L313
246,144
alfred82santa/aio-service-client
service_client/__init__.py
ServiceClient.close
def close(self): """ Close service client and its plugins. """ self._execute_plugin_hooks_sync(hook='close') if not self.session.closed: ensure_future(self.session.close(), loop=self.loop)
python
def close(self): """ Close service client and its plugins. """ self._execute_plugin_hooks_sync(hook='close') if not self.session.closed: ensure_future(self.session.close(), loop=self.loop)
[ "def", "close", "(", "self", ")", ":", "self", ".", "_execute_plugin_hooks_sync", "(", "hook", "=", "'close'", ")", "if", "not", "self", ".", "session", ".", "closed", ":", "ensure_future", "(", "self", ".", "session", ".", "close", "(", ")", ",", "loop", "=", "self", ".", "loop", ")" ]
Close service client and its plugins.
[ "Close", "service", "client", "and", "its", "plugins", "." ]
dd9ad49e23067b22178534915aa23ba24f6ff39b
https://github.com/alfred82santa/aio-service-client/blob/dd9ad49e23067b22178534915aa23ba24f6ff39b/service_client/__init__.py#L222-L229
246,145
gabrielfalcao/dominic
dominic/xpath/__init__.py
api
def api(f): """Decorator for functions and methods that are part of the external module API and that can throw XPathError exceptions. The call stack for these exceptions can be very large, and not very interesting to the user. This decorator rethrows XPathErrors to trim the stack. """ def api_function(*args, **kwargs): try: return f(*args, **kwargs) except XPathError, e: raise e api_function.__name__ = f.__name__ api_function.__doc__ = f.__doc__ return api_function
python
def api(f): """Decorator for functions and methods that are part of the external module API and that can throw XPathError exceptions. The call stack for these exceptions can be very large, and not very interesting to the user. This decorator rethrows XPathErrors to trim the stack. """ def api_function(*args, **kwargs): try: return f(*args, **kwargs) except XPathError, e: raise e api_function.__name__ = f.__name__ api_function.__doc__ = f.__doc__ return api_function
[ "def", "api", "(", "f", ")", ":", "def", "api_function", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "XPathError", ",", "e", ":", "raise", "e", "api_function", ".", "__name__", "=", "f", ".", "__name__", "api_function", ".", "__doc__", "=", "f", ".", "__doc__", "return", "api_function" ]
Decorator for functions and methods that are part of the external module API and that can throw XPathError exceptions. The call stack for these exceptions can be very large, and not very interesting to the user. This decorator rethrows XPathErrors to trim the stack.
[ "Decorator", "for", "functions", "and", "methods", "that", "are", "part", "of", "the", "external", "module", "API", "and", "that", "can", "throw", "XPathError", "exceptions", "." ]
a42f418fc288f3b70cb95847b405eaf7b83bb3a0
https://github.com/gabrielfalcao/dominic/blob/a42f418fc288f3b70cb95847b405eaf7b83bb3a0/dominic/xpath/__init__.py#L10-L26
246,146
tomokinakamaru/mapletree
mapletree/defaults/routings/routetree.py
RouteTree.get
def get(self, path, strict): """ Gets the item for `path`. If `strict` is true, this method returns `None` when matching path is not found. Otherwise, this returns the result item of prefix searching. :param path: Path to get :param strict: Searching mode :type path: list :type strict: bool """ item, pathinfo = self._get(path, strict) if item is None: if strict: return None, pathinfo else: return self._item, pathinfo else: return item, pathinfo
python
def get(self, path, strict): """ Gets the item for `path`. If `strict` is true, this method returns `None` when matching path is not found. Otherwise, this returns the result item of prefix searching. :param path: Path to get :param strict: Searching mode :type path: list :type strict: bool """ item, pathinfo = self._get(path, strict) if item is None: if strict: return None, pathinfo else: return self._item, pathinfo else: return item, pathinfo
[ "def", "get", "(", "self", ",", "path", ",", "strict", ")", ":", "item", ",", "pathinfo", "=", "self", ".", "_get", "(", "path", ",", "strict", ")", "if", "item", "is", "None", ":", "if", "strict", ":", "return", "None", ",", "pathinfo", "else", ":", "return", "self", ".", "_item", ",", "pathinfo", "else", ":", "return", "item", ",", "pathinfo" ]
Gets the item for `path`. If `strict` is true, this method returns `None` when matching path is not found. Otherwise, this returns the result item of prefix searching. :param path: Path to get :param strict: Searching mode :type path: list :type strict: bool
[ "Gets", "the", "item", "for", "path", ".", "If", "strict", "is", "true", "this", "method", "returns", "None", "when", "matching", "path", "is", "not", "found", ".", "Otherwise", "this", "returns", "the", "result", "item", "of", "prefix", "searching", "." ]
19ec68769ef2c1cd2e4164ed8623e0c4280279bb
https://github.com/tomokinakamaru/mapletree/blob/19ec68769ef2c1cd2e4164ed8623e0c4280279bb/mapletree/defaults/routings/routetree.py#L25-L45
246,147
tomokinakamaru/mapletree
mapletree/defaults/routings/routetree.py
RouteTree.set
def set(self, path, item, replace): """ Sets item for `path` and returns the item. Replaces existing item with `item` when `replace` is true :param path: Path for item :param item: New item :param replace: Updating mode :type path: list :type item: object :type replace: bool """ if len(path) == 0: if self._item is None or replace: self._item = item return self._item else: head, tail = path[0], path[1:] if head.startswith(':'): default = (head[1:], self.__class__()) _, rtree = self._subtrees.setdefault(self._WILDCARD, default) return rtree.set(tail, item, replace) else: rtree = self._subtrees.setdefault(head, self.__class__()) return rtree.set(tail, item, replace)
python
def set(self, path, item, replace): """ Sets item for `path` and returns the item. Replaces existing item with `item` when `replace` is true :param path: Path for item :param item: New item :param replace: Updating mode :type path: list :type item: object :type replace: bool """ if len(path) == 0: if self._item is None or replace: self._item = item return self._item else: head, tail = path[0], path[1:] if head.startswith(':'): default = (head[1:], self.__class__()) _, rtree = self._subtrees.setdefault(self._WILDCARD, default) return rtree.set(tail, item, replace) else: rtree = self._subtrees.setdefault(head, self.__class__()) return rtree.set(tail, item, replace)
[ "def", "set", "(", "self", ",", "path", ",", "item", ",", "replace", ")", ":", "if", "len", "(", "path", ")", "==", "0", ":", "if", "self", ".", "_item", "is", "None", "or", "replace", ":", "self", ".", "_item", "=", "item", "return", "self", ".", "_item", "else", ":", "head", ",", "tail", "=", "path", "[", "0", "]", ",", "path", "[", "1", ":", "]", "if", "head", ".", "startswith", "(", "':'", ")", ":", "default", "=", "(", "head", "[", "1", ":", "]", ",", "self", ".", "__class__", "(", ")", ")", "_", ",", "rtree", "=", "self", ".", "_subtrees", ".", "setdefault", "(", "self", ".", "_WILDCARD", ",", "default", ")", "return", "rtree", ".", "set", "(", "tail", ",", "item", ",", "replace", ")", "else", ":", "rtree", "=", "self", ".", "_subtrees", ".", "setdefault", "(", "head", ",", "self", ".", "__class__", "(", ")", ")", "return", "rtree", ".", "set", "(", "tail", ",", "item", ",", "replace", ")" ]
Sets item for `path` and returns the item. Replaces existing item with `item` when `replace` is true :param path: Path for item :param item: New item :param replace: Updating mode :type path: list :type item: object :type replace: bool
[ "Sets", "item", "for", "path", "and", "returns", "the", "item", ".", "Replaces", "existing", "item", "with", "item", "when", "replace", "is", "true" ]
19ec68769ef2c1cd2e4164ed8623e0c4280279bb
https://github.com/tomokinakamaru/mapletree/blob/19ec68769ef2c1cd2e4164ed8623e0c4280279bb/mapletree/defaults/routings/routetree.py#L47-L74
246,148
knagra/farnsworth
events/ajax.py
build_ajax_rsvps
def build_ajax_rsvps(event, user_profile): """Return link and list strings for a given event.""" if user_profile in event.rsvps.all(): link_string = True else: link_string = False if not event.rsvps.all().count(): list_string = 'No RSVPs.' else: list_string = 'RSVPs:' for counter, profile in enumerate(event.rsvps.all()): if counter > 0: list_string += ',' list_string += \ ' <a class="page_link" title="View Profile" href="{url}">' \ '{name}</a>'.format( url=reverse( 'member_profile', kwargs={'targetUsername': profile.user.username} ), name='You' if profile.user == user_profile.user \ else profile.user.get_full_name(), ) return (link_string, list_string)
python
def build_ajax_rsvps(event, user_profile): """Return link and list strings for a given event.""" if user_profile in event.rsvps.all(): link_string = True else: link_string = False if not event.rsvps.all().count(): list_string = 'No RSVPs.' else: list_string = 'RSVPs:' for counter, profile in enumerate(event.rsvps.all()): if counter > 0: list_string += ',' list_string += \ ' <a class="page_link" title="View Profile" href="{url}">' \ '{name}</a>'.format( url=reverse( 'member_profile', kwargs={'targetUsername': profile.user.username} ), name='You' if profile.user == user_profile.user \ else profile.user.get_full_name(), ) return (link_string, list_string)
[ "def", "build_ajax_rsvps", "(", "event", ",", "user_profile", ")", ":", "if", "user_profile", "in", "event", ".", "rsvps", ".", "all", "(", ")", ":", "link_string", "=", "True", "else", ":", "link_string", "=", "False", "if", "not", "event", ".", "rsvps", ".", "all", "(", ")", ".", "count", "(", ")", ":", "list_string", "=", "'No RSVPs.'", "else", ":", "list_string", "=", "'RSVPs:'", "for", "counter", ",", "profile", "in", "enumerate", "(", "event", ".", "rsvps", ".", "all", "(", ")", ")", ":", "if", "counter", ">", "0", ":", "list_string", "+=", "','", "list_string", "+=", "' <a class=\"page_link\" title=\"View Profile\" href=\"{url}\">'", "'{name}</a>'", ".", "format", "(", "url", "=", "reverse", "(", "'member_profile'", ",", "kwargs", "=", "{", "'targetUsername'", ":", "profile", ".", "user", ".", "username", "}", ")", ",", "name", "=", "'You'", "if", "profile", ".", "user", "==", "user_profile", ".", "user", "else", "profile", ".", "user", ".", "get_full_name", "(", ")", ",", ")", "return", "(", "link_string", ",", "list_string", ")" ]
Return link and list strings for a given event.
[ "Return", "link", "and", "list", "strings", "for", "a", "given", "event", "." ]
1b6589f0d9fea154f0a1e2231ed906764ed26d26
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/events/ajax.py#L12-L37
246,149
jmgilman/Neolib
neolib/pyamf/remoting/client/__init__.py
RequestWrapper.setResponse
def setResponse(self, response): """ A response has been received by the gateway """ self.response = response self.result = self.response.body if isinstance(self.result, remoting.ErrorFault): self.result.raiseException()
python
def setResponse(self, response): """ A response has been received by the gateway """ self.response = response self.result = self.response.body if isinstance(self.result, remoting.ErrorFault): self.result.raiseException()
[ "def", "setResponse", "(", "self", ",", "response", ")", ":", "self", ".", "response", "=", "response", "self", ".", "result", "=", "self", ".", "response", ".", "body", "if", "isinstance", "(", "self", ".", "result", ",", "remoting", ".", "ErrorFault", ")", ":", "self", ".", "result", ".", "raiseException", "(", ")" ]
A response has been received by the gateway
[ "A", "response", "has", "been", "received", "by", "the", "gateway" ]
228fafeaed0f3195676137732384a14820ae285c
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/remoting/client/__init__.py#L152-L160
246,150
jmgilman/Neolib
neolib/pyamf/remoting/client/__init__.py
RemotingService.addHeader
def addHeader(self, name, value, must_understand=False): """ Sets a persistent header to send with each request. @param name: Header name. """ self.headers[name] = value self.headers.set_required(name, must_understand)
python
def addHeader(self, name, value, must_understand=False): """ Sets a persistent header to send with each request. @param name: Header name. """ self.headers[name] = value self.headers.set_required(name, must_understand)
[ "def", "addHeader", "(", "self", ",", "name", ",", "value", ",", "must_understand", "=", "False", ")", ":", "self", ".", "headers", "[", "name", "]", "=", "value", "self", ".", "headers", ".", "set_required", "(", "name", ",", "must_understand", ")" ]
Sets a persistent header to send with each request. @param name: Header name.
[ "Sets", "a", "persistent", "header", "to", "send", "with", "each", "request", "." ]
228fafeaed0f3195676137732384a14820ae285c
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/remoting/client/__init__.py#L253-L260
246,151
jmgilman/Neolib
neolib/pyamf/remoting/client/__init__.py
RemotingService.getRequest
def getRequest(self, id_): """ Gets a request based on the id. :raise LookupError: Request not found. """ for request in self.requests: if request.id == id_: return request raise LookupError("Request %r not found" % (id_,))
python
def getRequest(self, id_): """ Gets a request based on the id. :raise LookupError: Request not found. """ for request in self.requests: if request.id == id_: return request raise LookupError("Request %r not found" % (id_,))
[ "def", "getRequest", "(", "self", ",", "id_", ")", ":", "for", "request", "in", "self", ".", "requests", ":", "if", "request", ".", "id", "==", "id_", ":", "return", "request", "raise", "LookupError", "(", "\"Request %r not found\"", "%", "(", "id_", ",", ")", ")" ]
Gets a request based on the id. :raise LookupError: Request not found.
[ "Gets", "a", "request", "based", "on", "the", "id", "." ]
228fafeaed0f3195676137732384a14820ae285c
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/remoting/client/__init__.py#L286-L296
246,152
jmgilman/Neolib
neolib/pyamf/remoting/client/__init__.py
RemotingService.addRequest
def addRequest(self, service, *args): """ Adds a request to be sent to the remoting gateway. """ wrapper = RequestWrapper(self, '/%d' % self.request_number, service, *args) self.request_number += 1 self.requests.append(wrapper) if self.logger: self.logger.debug('Adding request %s%r', wrapper.service, args) return wrapper
python
def addRequest(self, service, *args): """ Adds a request to be sent to the remoting gateway. """ wrapper = RequestWrapper(self, '/%d' % self.request_number, service, *args) self.request_number += 1 self.requests.append(wrapper) if self.logger: self.logger.debug('Adding request %s%r', wrapper.service, args) return wrapper
[ "def", "addRequest", "(", "self", ",", "service", ",", "*", "args", ")", ":", "wrapper", "=", "RequestWrapper", "(", "self", ",", "'/%d'", "%", "self", ".", "request_number", ",", "service", ",", "*", "args", ")", "self", ".", "request_number", "+=", "1", "self", ".", "requests", ".", "append", "(", "wrapper", ")", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "debug", "(", "'Adding request %s%r'", ",", "wrapper", ".", "service", ",", "args", ")", "return", "wrapper" ]
Adds a request to be sent to the remoting gateway.
[ "Adds", "a", "request", "to", "be", "sent", "to", "the", "remoting", "gateway", "." ]
228fafeaed0f3195676137732384a14820ae285c
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/remoting/client/__init__.py#L298-L311
246,153
jmgilman/Neolib
neolib/pyamf/remoting/client/__init__.py
RemotingService.removeRequest
def removeRequest(self, service, *args): """ Removes a request from the pending request list. """ if isinstance(service, RequestWrapper): if self.logger: self.logger.debug('Removing request: %s', self.requests[self.requests.index(service)]) del self.requests[self.requests.index(service)] return for request in self.requests: if request.service == service and request.args == args: if self.logger: self.logger.debug('Removing request: %s', self.requests[self.requests.index(request)]) del self.requests[self.requests.index(request)] return raise LookupError("Request not found")
python
def removeRequest(self, service, *args): """ Removes a request from the pending request list. """ if isinstance(service, RequestWrapper): if self.logger: self.logger.debug('Removing request: %s', self.requests[self.requests.index(service)]) del self.requests[self.requests.index(service)] return for request in self.requests: if request.service == service and request.args == args: if self.logger: self.logger.debug('Removing request: %s', self.requests[self.requests.index(request)]) del self.requests[self.requests.index(request)] return raise LookupError("Request not found")
[ "def", "removeRequest", "(", "self", ",", "service", ",", "*", "args", ")", ":", "if", "isinstance", "(", "service", ",", "RequestWrapper", ")", ":", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "debug", "(", "'Removing request: %s'", ",", "self", ".", "requests", "[", "self", ".", "requests", ".", "index", "(", "service", ")", "]", ")", "del", "self", ".", "requests", "[", "self", ".", "requests", ".", "index", "(", "service", ")", "]", "return", "for", "request", "in", "self", ".", "requests", ":", "if", "request", ".", "service", "==", "service", "and", "request", ".", "args", "==", "args", ":", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "debug", "(", "'Removing request: %s'", ",", "self", ".", "requests", "[", "self", ".", "requests", ".", "index", "(", "request", ")", "]", ")", "del", "self", ".", "requests", "[", "self", ".", "requests", ".", "index", "(", "request", ")", "]", "return", "raise", "LookupError", "(", "\"Request not found\"", ")" ]
Removes a request from the pending request list.
[ "Removes", "a", "request", "from", "the", "pending", "request", "list", "." ]
228fafeaed0f3195676137732384a14820ae285c
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/remoting/client/__init__.py#L313-L335
246,154
jmgilman/Neolib
neolib/pyamf/remoting/client/__init__.py
RemotingService.execute_single
def execute_single(self, request): """ Builds, sends and handles the response to a single request, returning the response. """ if self.logger: self.logger.debug('Executing single request: %s', request) self.removeRequest(request) body = remoting.encode(self.getAMFRequest([request]), strict=self.strict) http_request = urllib2.Request(self._root_url, body.getvalue(), self._get_execute_headers()) if self.proxy_args: http_request.set_proxy(*self.proxy_args) envelope = self._getResponse(http_request) return envelope[request.id]
python
def execute_single(self, request): """ Builds, sends and handles the response to a single request, returning the response. """ if self.logger: self.logger.debug('Executing single request: %s', request) self.removeRequest(request) body = remoting.encode(self.getAMFRequest([request]), strict=self.strict) http_request = urllib2.Request(self._root_url, body.getvalue(), self._get_execute_headers()) if self.proxy_args: http_request.set_proxy(*self.proxy_args) envelope = self._getResponse(http_request) return envelope[request.id]
[ "def", "execute_single", "(", "self", ",", "request", ")", ":", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "debug", "(", "'Executing single request: %s'", ",", "request", ")", "self", ".", "removeRequest", "(", "request", ")", "body", "=", "remoting", ".", "encode", "(", "self", ".", "getAMFRequest", "(", "[", "request", "]", ")", ",", "strict", "=", "self", ".", "strict", ")", "http_request", "=", "urllib2", ".", "Request", "(", "self", ".", "_root_url", ",", "body", ".", "getvalue", "(", ")", ",", "self", ".", "_get_execute_headers", "(", ")", ")", "if", "self", ".", "proxy_args", ":", "http_request", ".", "set_proxy", "(", "*", "self", ".", "proxy_args", ")", "envelope", "=", "self", ".", "_getResponse", "(", "http_request", ")", "return", "envelope", "[", "request", ".", "id", "]" ]
Builds, sends and handles the response to a single request, returning the response.
[ "Builds", "sends", "and", "handles", "the", "response", "to", "a", "single", "request", "returning", "the", "response", "." ]
228fafeaed0f3195676137732384a14820ae285c
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/remoting/client/__init__.py#L370-L390
246,155
jmgilman/Neolib
neolib/pyamf/remoting/client/__init__.py
RemotingService._getResponse
def _getResponse(self, http_request): """ Gets and handles the HTTP response from the remote gateway. """ if self.logger: self.logger.debug('Sending POST request to %s', self._root_url) try: fbh = self.opener(http_request) except urllib2.URLError, e: if self.logger: self.logger.exception('Failed request for %s', self._root_url) raise remoting.RemotingError(str(e)) http_message = fbh.info() content_encoding = http_message.getheader('Content-Encoding') content_length = http_message.getheader('Content-Length') or -1 content_type = http_message.getheader('Content-Type') server = http_message.getheader('Server') if self.logger: self.logger.debug('Content-Type: %r', content_type) self.logger.debug('Content-Encoding: %r', content_encoding) self.logger.debug('Content-Length: %r', content_length) self.logger.debug('Server: %r', server) if content_type != remoting.CONTENT_TYPE: if self.logger: self.logger.debug('Body = %s', fbh.read()) raise remoting.RemotingError('Incorrect MIME type received. ' '(got: %s)' % (content_type,)) bytes = fbh.read(int(content_length)) if self.logger: self.logger.debug('Read %d bytes for the response', len(bytes)) if content_encoding and content_encoding.strip().lower() == 'gzip': if not GzipFile: raise remoting.RemotingError( 'Decompression of Content-Encoding: %s not available.' % ( content_encoding,)) compressedstream = StringIO(bytes) gzipper = GzipFile(fileobj=compressedstream) bytes = gzipper.read() gzipper.close() response = remoting.decode(bytes, strict=self.strict) if self.logger: self.logger.debug('Response: %s', response) if remoting.APPEND_TO_GATEWAY_URL in response.headers: self.original_url += response.headers[remoting.APPEND_TO_GATEWAY_URL] self._setUrl(self.original_url) elif remoting.REPLACE_GATEWAY_URL in response.headers: self.original_url = response.headers[remoting.REPLACE_GATEWAY_URL] self._setUrl(self.original_url) if remoting.REQUEST_PERSISTENT_HEADER in response.headers: data = response.headers[remoting.REQUEST_PERSISTENT_HEADER] for k, v in data.iteritems(): self.headers[k] = v return response
python
def _getResponse(self, http_request): """ Gets and handles the HTTP response from the remote gateway. """ if self.logger: self.logger.debug('Sending POST request to %s', self._root_url) try: fbh = self.opener(http_request) except urllib2.URLError, e: if self.logger: self.logger.exception('Failed request for %s', self._root_url) raise remoting.RemotingError(str(e)) http_message = fbh.info() content_encoding = http_message.getheader('Content-Encoding') content_length = http_message.getheader('Content-Length') or -1 content_type = http_message.getheader('Content-Type') server = http_message.getheader('Server') if self.logger: self.logger.debug('Content-Type: %r', content_type) self.logger.debug('Content-Encoding: %r', content_encoding) self.logger.debug('Content-Length: %r', content_length) self.logger.debug('Server: %r', server) if content_type != remoting.CONTENT_TYPE: if self.logger: self.logger.debug('Body = %s', fbh.read()) raise remoting.RemotingError('Incorrect MIME type received. ' '(got: %s)' % (content_type,)) bytes = fbh.read(int(content_length)) if self.logger: self.logger.debug('Read %d bytes for the response', len(bytes)) if content_encoding and content_encoding.strip().lower() == 'gzip': if not GzipFile: raise remoting.RemotingError( 'Decompression of Content-Encoding: %s not available.' % ( content_encoding,)) compressedstream = StringIO(bytes) gzipper = GzipFile(fileobj=compressedstream) bytes = gzipper.read() gzipper.close() response = remoting.decode(bytes, strict=self.strict) if self.logger: self.logger.debug('Response: %s', response) if remoting.APPEND_TO_GATEWAY_URL in response.headers: self.original_url += response.headers[remoting.APPEND_TO_GATEWAY_URL] self._setUrl(self.original_url) elif remoting.REPLACE_GATEWAY_URL in response.headers: self.original_url = response.headers[remoting.REPLACE_GATEWAY_URL] self._setUrl(self.original_url) if remoting.REQUEST_PERSISTENT_HEADER in response.headers: data = response.headers[remoting.REQUEST_PERSISTENT_HEADER] for k, v in data.iteritems(): self.headers[k] = v return response
[ "def", "_getResponse", "(", "self", ",", "http_request", ")", ":", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "debug", "(", "'Sending POST request to %s'", ",", "self", ".", "_root_url", ")", "try", ":", "fbh", "=", "self", ".", "opener", "(", "http_request", ")", "except", "urllib2", ".", "URLError", ",", "e", ":", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "exception", "(", "'Failed request for %s'", ",", "self", ".", "_root_url", ")", "raise", "remoting", ".", "RemotingError", "(", "str", "(", "e", ")", ")", "http_message", "=", "fbh", ".", "info", "(", ")", "content_encoding", "=", "http_message", ".", "getheader", "(", "'Content-Encoding'", ")", "content_length", "=", "http_message", ".", "getheader", "(", "'Content-Length'", ")", "or", "-", "1", "content_type", "=", "http_message", ".", "getheader", "(", "'Content-Type'", ")", "server", "=", "http_message", ".", "getheader", "(", "'Server'", ")", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "debug", "(", "'Content-Type: %r'", ",", "content_type", ")", "self", ".", "logger", ".", "debug", "(", "'Content-Encoding: %r'", ",", "content_encoding", ")", "self", ".", "logger", ".", "debug", "(", "'Content-Length: %r'", ",", "content_length", ")", "self", ".", "logger", ".", "debug", "(", "'Server: %r'", ",", "server", ")", "if", "content_type", "!=", "remoting", ".", "CONTENT_TYPE", ":", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "debug", "(", "'Body = %s'", ",", "fbh", ".", "read", "(", ")", ")", "raise", "remoting", ".", "RemotingError", "(", "'Incorrect MIME type received. '", "'(got: %s)'", "%", "(", "content_type", ",", ")", ")", "bytes", "=", "fbh", ".", "read", "(", "int", "(", "content_length", ")", ")", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "debug", "(", "'Read %d bytes for the response'", ",", "len", "(", "bytes", ")", ")", "if", "content_encoding", "and", "content_encoding", ".", "strip", "(", ")", ".", "lower", "(", ")", "==", "'gzip'", ":", "if", "not", "GzipFile", ":", "raise", "remoting", ".", "RemotingError", "(", "'Decompression of Content-Encoding: %s not available.'", "%", "(", "content_encoding", ",", ")", ")", "compressedstream", "=", "StringIO", "(", "bytes", ")", "gzipper", "=", "GzipFile", "(", "fileobj", "=", "compressedstream", ")", "bytes", "=", "gzipper", ".", "read", "(", ")", "gzipper", ".", "close", "(", ")", "response", "=", "remoting", ".", "decode", "(", "bytes", ",", "strict", "=", "self", ".", "strict", ")", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "debug", "(", "'Response: %s'", ",", "response", ")", "if", "remoting", ".", "APPEND_TO_GATEWAY_URL", "in", "response", ".", "headers", ":", "self", ".", "original_url", "+=", "response", ".", "headers", "[", "remoting", ".", "APPEND_TO_GATEWAY_URL", "]", "self", ".", "_setUrl", "(", "self", ".", "original_url", ")", "elif", "remoting", ".", "REPLACE_GATEWAY_URL", "in", "response", ".", "headers", ":", "self", ".", "original_url", "=", "response", ".", "headers", "[", "remoting", ".", "REPLACE_GATEWAY_URL", "]", "self", ".", "_setUrl", "(", "self", ".", "original_url", ")", "if", "remoting", ".", "REQUEST_PERSISTENT_HEADER", "in", "response", ".", "headers", ":", "data", "=", "response", ".", "headers", "[", "remoting", ".", "REQUEST_PERSISTENT_HEADER", "]", "for", "k", ",", "v", "in", "data", ".", "iteritems", "(", ")", ":", "self", ".", "headers", "[", "k", "]", "=", "v", "return", "response" ]
Gets and handles the HTTP response from the remote gateway.
[ "Gets", "and", "handles", "the", "HTTP", "response", "from", "the", "remote", "gateway", "." ]
228fafeaed0f3195676137732384a14820ae285c
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/remoting/client/__init__.py#L415-L487
246,156
jmgilman/Neolib
neolib/pyamf/remoting/client/__init__.py
RemotingService.setCredentials
def setCredentials(self, username, password): """ Sets authentication credentials for accessing the remote gateway. """ self.addHeader('Credentials', dict(userid=username.decode('utf-8'), password=password.decode('utf-8')), True)
python
def setCredentials(self, username, password): """ Sets authentication credentials for accessing the remote gateway. """ self.addHeader('Credentials', dict(userid=username.decode('utf-8'), password=password.decode('utf-8')), True)
[ "def", "setCredentials", "(", "self", ",", "username", ",", "password", ")", ":", "self", ".", "addHeader", "(", "'Credentials'", ",", "dict", "(", "userid", "=", "username", ".", "decode", "(", "'utf-8'", ")", ",", "password", "=", "password", ".", "decode", "(", "'utf-8'", ")", ")", ",", "True", ")" ]
Sets authentication credentials for accessing the remote gateway.
[ "Sets", "authentication", "credentials", "for", "accessing", "the", "remote", "gateway", "." ]
228fafeaed0f3195676137732384a14820ae285c
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/remoting/client/__init__.py#L489-L494
246,157
neuroticnerd/armory
armory/gevent.py
patch_gevent_hub
def patch_gevent_hub(): """ This patches the error handler in the gevent Hub object. """ from gevent.hub import Hub def patched_handle_error(self, context, etype, value, tb): """ Patched to not print KeyboardInterrupt exceptions. """ if isinstance(value, str): value = etype(value) not_error = issubclass(etype, self.NOT_ERROR) system_error = issubclass(etype, self.SYSTEM_ERROR) if not not_error and not issubclass(etype, KeyboardInterrupt): self.print_exception(context, etype, value, tb) if context is None or system_error: self.handle_system_error(etype, value) Hub._original_handle_error = Hub.handle_error Hub.handle_error = patched_handle_error
python
def patch_gevent_hub(): """ This patches the error handler in the gevent Hub object. """ from gevent.hub import Hub def patched_handle_error(self, context, etype, value, tb): """ Patched to not print KeyboardInterrupt exceptions. """ if isinstance(value, str): value = etype(value) not_error = issubclass(etype, self.NOT_ERROR) system_error = issubclass(etype, self.SYSTEM_ERROR) if not not_error and not issubclass(etype, KeyboardInterrupt): self.print_exception(context, etype, value, tb) if context is None or system_error: self.handle_system_error(etype, value) Hub._original_handle_error = Hub.handle_error Hub.handle_error = patched_handle_error
[ "def", "patch_gevent_hub", "(", ")", ":", "from", "gevent", ".", "hub", "import", "Hub", "def", "patched_handle_error", "(", "self", ",", "context", ",", "etype", ",", "value", ",", "tb", ")", ":", "\"\"\" Patched to not print KeyboardInterrupt exceptions. \"\"\"", "if", "isinstance", "(", "value", ",", "str", ")", ":", "value", "=", "etype", "(", "value", ")", "not_error", "=", "issubclass", "(", "etype", ",", "self", ".", "NOT_ERROR", ")", "system_error", "=", "issubclass", "(", "etype", ",", "self", ".", "SYSTEM_ERROR", ")", "if", "not", "not_error", "and", "not", "issubclass", "(", "etype", ",", "KeyboardInterrupt", ")", ":", "self", ".", "print_exception", "(", "context", ",", "etype", ",", "value", ",", "tb", ")", "if", "context", "is", "None", "or", "system_error", ":", "self", ".", "handle_system_error", "(", "etype", ",", "value", ")", "Hub", ".", "_original_handle_error", "=", "Hub", ".", "handle_error", "Hub", ".", "handle_error", "=", "patched_handle_error" ]
This patches the error handler in the gevent Hub object.
[ "This", "patches", "the", "error", "handler", "in", "the", "gevent", "Hub", "object", "." ]
d37c5ca1dbdd60dddb968e35f0bbe4bc1299dca1
https://github.com/neuroticnerd/armory/blob/d37c5ca1dbdd60dddb968e35f0bbe4bc1299dca1/armory/gevent.py#L15-L31
246,158
abe-winter/pg13-py
pg13/scope.py
col2name
def col2name(col_item): "helper for SyntheticTable.columns. takes something from SelectX.cols, returns a string column name" if isinstance(col_item, sqparse2.NameX): return col_item.name elif isinstance(col_item, sqparse2.AliasX): return col_item.alias else: raise TypeError(type(col_item), col_item)
python
def col2name(col_item): "helper for SyntheticTable.columns. takes something from SelectX.cols, returns a string column name" if isinstance(col_item, sqparse2.NameX): return col_item.name elif isinstance(col_item, sqparse2.AliasX): return col_item.alias else: raise TypeError(type(col_item), col_item)
[ "def", "col2name", "(", "col_item", ")", ":", "if", "isinstance", "(", "col_item", ",", "sqparse2", ".", "NameX", ")", ":", "return", "col_item", ".", "name", "elif", "isinstance", "(", "col_item", ",", "sqparse2", ".", "AliasX", ")", ":", "return", "col_item", ".", "alias", "else", ":", "raise", "TypeError", "(", "type", "(", "col_item", ")", ",", "col_item", ")" ]
helper for SyntheticTable.columns. takes something from SelectX.cols, returns a string column name
[ "helper", "for", "SyntheticTable", ".", "columns", ".", "takes", "something", "from", "SelectX", ".", "cols", "returns", "a", "string", "column", "name" ]
c78806f99f35541a8756987e86edca3438aa97f5
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/scope.py#L9-L13
246,159
abe-winter/pg13-py
pg13/scope.py
Scope.add
def add(self, name, target): "target should be a Table or SyntheticTable" if not isinstance(target, (table.Table, SyntheticTable)): raise TypeError(type(target), target) if name in self: # note: this is critical for avoiding cycles raise ScopeCollisionError('scope already has', name) self.names[name] = target
python
def add(self, name, target): "target should be a Table or SyntheticTable" if not isinstance(target, (table.Table, SyntheticTable)): raise TypeError(type(target), target) if name in self: # note: this is critical for avoiding cycles raise ScopeCollisionError('scope already has', name) self.names[name] = target
[ "def", "add", "(", "self", ",", "name", ",", "target", ")", ":", "if", "not", "isinstance", "(", "target", ",", "(", "table", ".", "Table", ",", "SyntheticTable", ")", ")", ":", "raise", "TypeError", "(", "type", "(", "target", ")", ",", "target", ")", "if", "name", "in", "self", ":", "# note: this is critical for avoiding cycles", "raise", "ScopeCollisionError", "(", "'scope already has'", ",", "name", ")", "self", ".", "names", "[", "name", "]", "=", "target" ]
target should be a Table or SyntheticTable
[ "target", "should", "be", "a", "Table", "or", "SyntheticTable" ]
c78806f99f35541a8756987e86edca3438aa97f5
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/scope.py#L34-L41
246,160
Tinche/django-bower-cache
registry/views.py
PackagesRetrieveView.clone_from_upstream
def clone_from_upstream(pkg_name, repo_url): """Clone a non-existent package using the upstream registry.""" msg = "Spawning a cloning task for %s from upstream due to API req." LOG.info(msg % pkg_name) upstream_url = settings.UPSTREAM_BOWER_REGISTRY upstream_pkg = bowerlib.get_package(upstream_url, pkg_name) if upstream_pkg is None: raise Http404 task = tasks.clone_repo.delay(pkg_name, upstream_pkg['url']) try: result = task.get(timeout=5) except tasks.TimeoutError: # Not done yet. What to return? raise ServiceUnavailable return result.to_package(repo_url)
python
def clone_from_upstream(pkg_name, repo_url): """Clone a non-existent package using the upstream registry.""" msg = "Spawning a cloning task for %s from upstream due to API req." LOG.info(msg % pkg_name) upstream_url = settings.UPSTREAM_BOWER_REGISTRY upstream_pkg = bowerlib.get_package(upstream_url, pkg_name) if upstream_pkg is None: raise Http404 task = tasks.clone_repo.delay(pkg_name, upstream_pkg['url']) try: result = task.get(timeout=5) except tasks.TimeoutError: # Not done yet. What to return? raise ServiceUnavailable return result.to_package(repo_url)
[ "def", "clone_from_upstream", "(", "pkg_name", ",", "repo_url", ")", ":", "msg", "=", "\"Spawning a cloning task for %s from upstream due to API req.\"", "LOG", ".", "info", "(", "msg", "%", "pkg_name", ")", "upstream_url", "=", "settings", ".", "UPSTREAM_BOWER_REGISTRY", "upstream_pkg", "=", "bowerlib", ".", "get_package", "(", "upstream_url", ",", "pkg_name", ")", "if", "upstream_pkg", "is", "None", ":", "raise", "Http404", "task", "=", "tasks", ".", "clone_repo", ".", "delay", "(", "pkg_name", ",", "upstream_pkg", "[", "'url'", "]", ")", "try", ":", "result", "=", "task", ".", "get", "(", "timeout", "=", "5", ")", "except", "tasks", ".", "TimeoutError", ":", "# Not done yet. What to return?", "raise", "ServiceUnavailable", "return", "result", ".", "to_package", "(", "repo_url", ")" ]
Clone a non-existent package using the upstream registry.
[ "Clone", "a", "non", "-", "existent", "package", "using", "the", "upstream", "registry", "." ]
5245b2ee80c33c09d85ce0bf8f047825d9df2118
https://github.com/Tinche/django-bower-cache/blob/5245b2ee80c33c09d85ce0bf8f047825d9df2118/registry/views.py#L79-L97
246,161
testing-cabal/systemfixtures
systemfixtures/executable.py
allocate_port
def allocate_port(): """Allocate an unused port. There is a small race condition here (between the time we allocate the port, and the time it actually gets used), but for the purposes for which this function gets used it isn't a problem in practice. """ sock = socket.socket() try: sock.bind(("localhost", 0)) return get_port(sock) finally: sock.close()
python
def allocate_port(): """Allocate an unused port. There is a small race condition here (between the time we allocate the port, and the time it actually gets used), but for the purposes for which this function gets used it isn't a problem in practice. """ sock = socket.socket() try: sock.bind(("localhost", 0)) return get_port(sock) finally: sock.close()
[ "def", "allocate_port", "(", ")", ":", "sock", "=", "socket", ".", "socket", "(", ")", "try", ":", "sock", ".", "bind", "(", "(", "\"localhost\"", ",", "0", ")", ")", "return", "get_port", "(", "sock", ")", "finally", ":", "sock", ".", "close", "(", ")" ]
Allocate an unused port. There is a small race condition here (between the time we allocate the port, and the time it actually gets used), but for the purposes for which this function gets used it isn't a problem in practice.
[ "Allocate", "an", "unused", "port", "." ]
adf1b822bf83dc2a2f6bf7b85b5d8055e5e6ccd4
https://github.com/testing-cabal/systemfixtures/blob/adf1b822bf83dc2a2f6bf7b85b5d8055e5e6ccd4/systemfixtures/executable.py#L115-L127
246,162
testing-cabal/systemfixtures
systemfixtures/executable.py
FakeExecutable.spawn
def spawn(self): """Spawn the fake executable using subprocess.Popen.""" self._process = subprocess.Popen( [self.path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) self.addCleanup(self._process_kill)
python
def spawn(self): """Spawn the fake executable using subprocess.Popen.""" self._process = subprocess.Popen( [self.path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) self.addCleanup(self._process_kill)
[ "def", "spawn", "(", "self", ")", ":", "self", ".", "_process", "=", "subprocess", ".", "Popen", "(", "[", "self", ".", "path", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", "self", ".", "addCleanup", "(", "self", ".", "_process_kill", ")" ]
Spawn the fake executable using subprocess.Popen.
[ "Spawn", "the", "fake", "executable", "using", "subprocess", ".", "Popen", "." ]
adf1b822bf83dc2a2f6bf7b85b5d8055e5e6ccd4
https://github.com/testing-cabal/systemfixtures/blob/adf1b822bf83dc2a2f6bf7b85b5d8055e5e6ccd4/systemfixtures/executable.py#L34-L38
246,163
testing-cabal/systemfixtures
systemfixtures/executable.py
FakeExecutable.listen
def listen(self, port=None): """Make the fake executable listen to the specified port. Possible values for 'port' are: - None: Allocate immediately a free port and instruct the fake executable to use it when it's invoked. This is subject to a race condition, if that port that was free when listen() was invoked later becomes used before the fake executable had chance to bind to it. However it has the advantage of exposing the free port as FakeExecutable.port instance variable, that can easily be consumed by tests. - An integer: Listen to this specific port. """ if port is None: port = allocate_port() self.port = port self.line("import socket") self.line("sock = socket.socket()") self.line("sock.bind(('localhost', {}))".format(self.port)) self.log("listening: %d" % self.port) self.line("sock.listen(0)")
python
def listen(self, port=None): """Make the fake executable listen to the specified port. Possible values for 'port' are: - None: Allocate immediately a free port and instruct the fake executable to use it when it's invoked. This is subject to a race condition, if that port that was free when listen() was invoked later becomes used before the fake executable had chance to bind to it. However it has the advantage of exposing the free port as FakeExecutable.port instance variable, that can easily be consumed by tests. - An integer: Listen to this specific port. """ if port is None: port = allocate_port() self.port = port self.line("import socket") self.line("sock = socket.socket()") self.line("sock.bind(('localhost', {}))".format(self.port)) self.log("listening: %d" % self.port) self.line("sock.listen(0)")
[ "def", "listen", "(", "self", ",", "port", "=", "None", ")", ":", "if", "port", "is", "None", ":", "port", "=", "allocate_port", "(", ")", "self", ".", "port", "=", "port", "self", ".", "line", "(", "\"import socket\"", ")", "self", ".", "line", "(", "\"sock = socket.socket()\"", ")", "self", ".", "line", "(", "\"sock.bind(('localhost', {}))\"", ".", "format", "(", "self", ".", "port", ")", ")", "self", ".", "log", "(", "\"listening: %d\"", "%", "self", ".", "port", ")", "self", ".", "line", "(", "\"sock.listen(0)\"", ")" ]
Make the fake executable listen to the specified port. Possible values for 'port' are: - None: Allocate immediately a free port and instruct the fake executable to use it when it's invoked. This is subject to a race condition, if that port that was free when listen() was invoked later becomes used before the fake executable had chance to bind to it. However it has the advantage of exposing the free port as FakeExecutable.port instance variable, that can easily be consumed by tests. - An integer: Listen to this specific port.
[ "Make", "the", "fake", "executable", "listen", "to", "the", "specified", "port", "." ]
adf1b822bf83dc2a2f6bf7b85b5d8055e5e6ccd4
https://github.com/testing-cabal/systemfixtures/blob/adf1b822bf83dc2a2f6bf7b85b5d8055e5e6ccd4/systemfixtures/executable.py#L59-L81
246,164
testing-cabal/systemfixtures
systemfixtures/executable.py
FakeExecutable._process_kill
def _process_kill(self): """Kill the fake executable process if it's still running.""" if self._process.poll() is None: # pragma: no cover self._process.kill() self._process.wait(timeout=5)
python
def _process_kill(self): """Kill the fake executable process if it's still running.""" if self._process.poll() is None: # pragma: no cover self._process.kill() self._process.wait(timeout=5)
[ "def", "_process_kill", "(", "self", ")", ":", "if", "self", ".", "_process", ".", "poll", "(", ")", "is", "None", ":", "# pragma: no cover", "self", ".", "_process", ".", "kill", "(", ")", "self", ".", "_process", ".", "wait", "(", "timeout", "=", "5", ")" ]
Kill the fake executable process if it's still running.
[ "Kill", "the", "fake", "executable", "process", "if", "it", "s", "still", "running", "." ]
adf1b822bf83dc2a2f6bf7b85b5d8055e5e6ccd4
https://github.com/testing-cabal/systemfixtures/blob/adf1b822bf83dc2a2f6bf7b85b5d8055e5e6ccd4/systemfixtures/executable.py#L87-L91
246,165
testing-cabal/systemfixtures
systemfixtures/executable.py
FakeExecutable._process_info
def _process_info(self): """Return details about the fake process.""" if not self._process: return [] output, error = self._process.communicate(timeout=5) if error is None: error = b"" output = output.decode("utf-8").strip() error = error.decode("utf-8").strip() info = (u"returncode: %r\n" u"output:\n%s\n" u"error:\n%s\n" % (self._process.returncode, output, error)) return [info.encode("utf-8")]
python
def _process_info(self): """Return details about the fake process.""" if not self._process: return [] output, error = self._process.communicate(timeout=5) if error is None: error = b"" output = output.decode("utf-8").strip() error = error.decode("utf-8").strip() info = (u"returncode: %r\n" u"output:\n%s\n" u"error:\n%s\n" % (self._process.returncode, output, error)) return [info.encode("utf-8")]
[ "def", "_process_info", "(", "self", ")", ":", "if", "not", "self", ".", "_process", ":", "return", "[", "]", "output", ",", "error", "=", "self", ".", "_process", ".", "communicate", "(", "timeout", "=", "5", ")", "if", "error", "is", "None", ":", "error", "=", "b\"\"", "output", "=", "output", ".", "decode", "(", "\"utf-8\"", ")", ".", "strip", "(", ")", "error", "=", "error", ".", "decode", "(", "\"utf-8\"", ")", ".", "strip", "(", ")", "info", "=", "(", "u\"returncode: %r\\n\"", "u\"output:\\n%s\\n\"", "u\"error:\\n%s\\n\"", "%", "(", "self", ".", "_process", ".", "returncode", ",", "output", ",", "error", ")", ")", "return", "[", "info", ".", "encode", "(", "\"utf-8\"", ")", "]" ]
Return details about the fake process.
[ "Return", "details", "about", "the", "fake", "process", "." ]
adf1b822bf83dc2a2f6bf7b85b5d8055e5e6ccd4
https://github.com/testing-cabal/systemfixtures/blob/adf1b822bf83dc2a2f6bf7b85b5d8055e5e6ccd4/systemfixtures/executable.py#L93-L106
246,166
aganezov/gos
gos/tasks.py
TaskLoader.load_tasks_from_file
def load_tasks_from_file(self, file_path): """ Imports specified python module and returns subclasses of BaseTask from it :param file_path: a fully qualified file path for a python module to import CustomTasks from :type file_path: `str` :return: a dict of CustomTasks, where key is CustomTask.name, and value is a CustomClass task itself :rtype: `dict` """ file_name, module_path, objects = Loader.import_custom_python_file(file_path) result = {} for entry in objects: try: if issubclass(entry, BaseTask): if entry.__name__ != BaseTask.__name__ and entry.name == BaseTask.name: raise GOSTaskException("Class {class_name} form file {file_name} does not have a unique `name` class field. " "All custom tasks must have a unique `name` class field for them, tat is used for future reference" "".format(class_name=entry.name, file_name=os.path.join(module_path, file_name))) result[entry.name] = entry except TypeError: continue return result
python
def load_tasks_from_file(self, file_path): """ Imports specified python module and returns subclasses of BaseTask from it :param file_path: a fully qualified file path for a python module to import CustomTasks from :type file_path: `str` :return: a dict of CustomTasks, where key is CustomTask.name, and value is a CustomClass task itself :rtype: `dict` """ file_name, module_path, objects = Loader.import_custom_python_file(file_path) result = {} for entry in objects: try: if issubclass(entry, BaseTask): if entry.__name__ != BaseTask.__name__ and entry.name == BaseTask.name: raise GOSTaskException("Class {class_name} form file {file_name} does not have a unique `name` class field. " "All custom tasks must have a unique `name` class field for them, tat is used for future reference" "".format(class_name=entry.name, file_name=os.path.join(module_path, file_name))) result[entry.name] = entry except TypeError: continue return result
[ "def", "load_tasks_from_file", "(", "self", ",", "file_path", ")", ":", "file_name", ",", "module_path", ",", "objects", "=", "Loader", ".", "import_custom_python_file", "(", "file_path", ")", "result", "=", "{", "}", "for", "entry", "in", "objects", ":", "try", ":", "if", "issubclass", "(", "entry", ",", "BaseTask", ")", ":", "if", "entry", ".", "__name__", "!=", "BaseTask", ".", "__name__", "and", "entry", ".", "name", "==", "BaseTask", ".", "name", ":", "raise", "GOSTaskException", "(", "\"Class {class_name} form file {file_name} does not have a unique `name` class field. \"", "\"All custom tasks must have a unique `name` class field for them, tat is used for future reference\"", "\"\"", ".", "format", "(", "class_name", "=", "entry", ".", "name", ",", "file_name", "=", "os", ".", "path", ".", "join", "(", "module_path", ",", "file_name", ")", ")", ")", "result", "[", "entry", ".", "name", "]", "=", "entry", "except", "TypeError", ":", "continue", "return", "result" ]
Imports specified python module and returns subclasses of BaseTask from it :param file_path: a fully qualified file path for a python module to import CustomTasks from :type file_path: `str` :return: a dict of CustomTasks, where key is CustomTask.name, and value is a CustomClass task itself :rtype: `dict`
[ "Imports", "specified", "python", "module", "and", "returns", "subclasses", "of", "BaseTask", "from", "it" ]
fb4d210284f3037c5321250cb95f3901754feb6b
https://github.com/aganezov/gos/blob/fb4d210284f3037c5321250cb95f3901754feb6b/gos/tasks.py#L18-L38
246,167
aganezov/gos
gos/tasks.py
TaskLoader.load_tasks_from_dir
def load_tasks_from_dir(self, dir_path, propagate_exceptions=False): """ Imports all python modules in specified directories and returns subclasses of BaseTask from them :param propagate_exceptions: a flag that indicates if exceptions from single file import shall be raised during the whole directory lookup :param dir_path: fully qualified directory path, where all python modules will be search for subclasses of BaseTask :type dir_path: `str` :return: a dict of CustomTasks, where key is CustomTask.name, and value is a CustomClass task itself :rtype: `dict` """ if not os.path.exists(dir_path): raise GOSTaskException() if os.path.isfile(dir_path): raise GOSTaskException() result = {} for file_basename in os.listdir(dir_path): full_file_path = os.path.join(dir_path, file_basename) try: result.update(self.load_tasks_from_file(full_file_path)) except (GOSTaskException, GOSIOException): if propagate_exceptions: raise return result
python
def load_tasks_from_dir(self, dir_path, propagate_exceptions=False): """ Imports all python modules in specified directories and returns subclasses of BaseTask from them :param propagate_exceptions: a flag that indicates if exceptions from single file import shall be raised during the whole directory lookup :param dir_path: fully qualified directory path, where all python modules will be search for subclasses of BaseTask :type dir_path: `str` :return: a dict of CustomTasks, where key is CustomTask.name, and value is a CustomClass task itself :rtype: `dict` """ if not os.path.exists(dir_path): raise GOSTaskException() if os.path.isfile(dir_path): raise GOSTaskException() result = {} for file_basename in os.listdir(dir_path): full_file_path = os.path.join(dir_path, file_basename) try: result.update(self.load_tasks_from_file(full_file_path)) except (GOSTaskException, GOSIOException): if propagate_exceptions: raise return result
[ "def", "load_tasks_from_dir", "(", "self", ",", "dir_path", ",", "propagate_exceptions", "=", "False", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "dir_path", ")", ":", "raise", "GOSTaskException", "(", ")", "if", "os", ".", "path", ".", "isfile", "(", "dir_path", ")", ":", "raise", "GOSTaskException", "(", ")", "result", "=", "{", "}", "for", "file_basename", "in", "os", ".", "listdir", "(", "dir_path", ")", ":", "full_file_path", "=", "os", ".", "path", ".", "join", "(", "dir_path", ",", "file_basename", ")", "try", ":", "result", ".", "update", "(", "self", ".", "load_tasks_from_file", "(", "full_file_path", ")", ")", "except", "(", "GOSTaskException", ",", "GOSIOException", ")", ":", "if", "propagate_exceptions", ":", "raise", "return", "result" ]
Imports all python modules in specified directories and returns subclasses of BaseTask from them :param propagate_exceptions: a flag that indicates if exceptions from single file import shall be raised during the whole directory lookup :param dir_path: fully qualified directory path, where all python modules will be search for subclasses of BaseTask :type dir_path: `str` :return: a dict of CustomTasks, where key is CustomTask.name, and value is a CustomClass task itself :rtype: `dict`
[ "Imports", "all", "python", "modules", "in", "specified", "directories", "and", "returns", "subclasses", "of", "BaseTask", "from", "them" ]
fb4d210284f3037c5321250cb95f3901754feb6b
https://github.com/aganezov/gos/blob/fb4d210284f3037c5321250cb95f3901754feb6b/gos/tasks.py#L40-L62
246,168
aganezov/gos
gos/tasks.py
TaskLoader.load_tasks
def load_tasks(self, paths, propagate_exception=False): """ Loads all subclasses of BaseTask from modules that are contained in supplied directory paths or direct module paths :param propagate_exception: a flag that indicates if exceptions from single file import shall be raised during the whole directory lookup :param paths: an iterable of fully qualified paths to python modules / directories, from where we import subclasses of BaseClass :type paths: `iterable`(`str`) :return: a dict of CustomTasks, where key is CustomTask.name, and value is a CustomClass task itself :rtype: `dict` """ try: result = {} for path in paths: try: if os.path.isdir(path): result.update(self.load_tasks_from_dir(dir_path=path, propagate_exceptions=propagate_exception)) elif os.path.isfile(path): result.update(self.load_tasks_from_file(file_path=path)) except (GOSTaskException, GOSIOException): if propagate_exception: raise return result except TypeError: raise GOSTaskException("Argument for `load_tasks` method must be iterable")
python
def load_tasks(self, paths, propagate_exception=False): """ Loads all subclasses of BaseTask from modules that are contained in supplied directory paths or direct module paths :param propagate_exception: a flag that indicates if exceptions from single file import shall be raised during the whole directory lookup :param paths: an iterable of fully qualified paths to python modules / directories, from where we import subclasses of BaseClass :type paths: `iterable`(`str`) :return: a dict of CustomTasks, where key is CustomTask.name, and value is a CustomClass task itself :rtype: `dict` """ try: result = {} for path in paths: try: if os.path.isdir(path): result.update(self.load_tasks_from_dir(dir_path=path, propagate_exceptions=propagate_exception)) elif os.path.isfile(path): result.update(self.load_tasks_from_file(file_path=path)) except (GOSTaskException, GOSIOException): if propagate_exception: raise return result except TypeError: raise GOSTaskException("Argument for `load_tasks` method must be iterable")
[ "def", "load_tasks", "(", "self", ",", "paths", ",", "propagate_exception", "=", "False", ")", ":", "try", ":", "result", "=", "{", "}", "for", "path", "in", "paths", ":", "try", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "result", ".", "update", "(", "self", ".", "load_tasks_from_dir", "(", "dir_path", "=", "path", ",", "propagate_exceptions", "=", "propagate_exception", ")", ")", "elif", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "result", ".", "update", "(", "self", ".", "load_tasks_from_file", "(", "file_path", "=", "path", ")", ")", "except", "(", "GOSTaskException", ",", "GOSIOException", ")", ":", "if", "propagate_exception", ":", "raise", "return", "result", "except", "TypeError", ":", "raise", "GOSTaskException", "(", "\"Argument for `load_tasks` method must be iterable\"", ")" ]
Loads all subclasses of BaseTask from modules that are contained in supplied directory paths or direct module paths :param propagate_exception: a flag that indicates if exceptions from single file import shall be raised during the whole directory lookup :param paths: an iterable of fully qualified paths to python modules / directories, from where we import subclasses of BaseClass :type paths: `iterable`(`str`) :return: a dict of CustomTasks, where key is CustomTask.name, and value is a CustomClass task itself :rtype: `dict`
[ "Loads", "all", "subclasses", "of", "BaseTask", "from", "modules", "that", "are", "contained", "in", "supplied", "directory", "paths", "or", "direct", "module", "paths" ]
fb4d210284f3037c5321250cb95f3901754feb6b
https://github.com/aganezov/gos/blob/fb4d210284f3037c5321250cb95f3901754feb6b/gos/tasks.py#L64-L87
246,169
relekang/rmoq
rmoq/base.py
Mock.activate
def activate(self, prefix=None, backend=None): """ A decorator used to activate the mocker. :param prefix: :param backend: An instance of a storage backend. """ if isinstance(prefix, compat.string_types): self.prefix = prefix if isinstance(backend, RmoqStorageBackend): self.backend = backend def activate(func): if isinstance(func, type): return self._decorate_class(func) def wrapper(*args, **kwargs): with self: return func(*args, **kwargs) return wrapper return activate
python
def activate(self, prefix=None, backend=None): """ A decorator used to activate the mocker. :param prefix: :param backend: An instance of a storage backend. """ if isinstance(prefix, compat.string_types): self.prefix = prefix if isinstance(backend, RmoqStorageBackend): self.backend = backend def activate(func): if isinstance(func, type): return self._decorate_class(func) def wrapper(*args, **kwargs): with self: return func(*args, **kwargs) return wrapper return activate
[ "def", "activate", "(", "self", ",", "prefix", "=", "None", ",", "backend", "=", "None", ")", ":", "if", "isinstance", "(", "prefix", ",", "compat", ".", "string_types", ")", ":", "self", ".", "prefix", "=", "prefix", "if", "isinstance", "(", "backend", ",", "RmoqStorageBackend", ")", ":", "self", ".", "backend", "=", "backend", "def", "activate", "(", "func", ")", ":", "if", "isinstance", "(", "func", ",", "type", ")", ":", "return", "self", ".", "_decorate_class", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "self", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper", "return", "activate" ]
A decorator used to activate the mocker. :param prefix: :param backend: An instance of a storage backend.
[ "A", "decorator", "used", "to", "activate", "the", "mocker", "." ]
61fd2a221e247b7aca87492f10c3bc3894536260
https://github.com/relekang/rmoq/blob/61fd2a221e247b7aca87492f10c3bc3894536260/rmoq/base.py#L38-L61
246,170
roaet/wafflehaus.neutron
wafflehaus/neutron/nova_interaction/__init__.py
NovaInteraction._process_call
def _process_call(self, req, resource): """This is were all callbacks are made and the req is processed.""" if resource == "ports": if req.method.upper() in ('PUT', 'POST'): # Pass the request back to be processed by other filters # and Neutron first resp = req.get_response(self.app) if resp.status_code not in (200, 204): return resp resp_body = resp.json # Variables for Nova Call, obtained from Neutron response action = "create" address = resp_body['port']['mac_address'] fixed_ips = resp_body['port']['fixed_ips'] instance_id = resp_body['port']['instance_id'] network_id = resp_body['port']['network_id'] port_id = resp_body['port']['id'] tenant_id = resp_body['port']['tenant_id'] elif req.method.upper() == "DELETE": action = "delete" port_id = req.path.split("/") port_id = port_id[port_id.index("ports") + 1] # DELETEs do not have all the port info that we need, so a # call to Neutron must be made first. neutron_conn = NeutronConn(log=self.log, port=self.neutron_port, url=self.neutron_url, verify_ssl=self.neutron_verify_ssl) status, neutron_resp = neutron_conn.ports(port_id=port_id) if isinstance(neutron_resp, Exception): return neutron_resp elif status not in (200, 204): resp = Response() resp.status = 500 new_body = {"neutron_callback": {"port_id": port_id, "status": "error", "error": neutron_resp}} resp.body = json.dumps(new_body) return resp # Now that we have the port info, we can make the variables # for the Nova Call address = neutron_resp['port']['mac_address'] fixed_ips = neutron_resp['port']['fixed_ips'] instance_id = neutron_resp['port']['instance_id'] network_id = neutron_resp['port']['network_id'] tenant_id = neutron_resp['port']['tenant_id'] # Port info saved, now send the request back to processed by # other filters and Neutron resp = req.get_response(self.app) if resp.status_code not in (200, 204): return resp else: new_body = resp.json new_body['neutron_callback'] = {"port_id": port_id, "status": "success"} resp.body = json.dumps(new_body) nova_conn = NovaConn(log=self.log, url=self.nova_url, verify_ssl=self.nova_verify_ssl) status, nova_resp = nova_conn.admin_virtual_interfaces( action=action, address=address, fixed_ips=fixed_ips, network_id=network_id, port_id=port_id, tenant_id=tenant_id, instance_id=instance_id) if isinstance(nova_resp, Exception): return nova_resp elif status not in (200, 204): # We'll likely want to provide the customer with a call here # such as virtual-interface-delete/virtual-interface-update resp.status = 500 new_body = resp.json new_body['nova_callback'] = {"instance_id": instance_id, "status": "error", "error": nova_resp} resp.body = json.dumps(new_body) else: new_body = resp.json new_body['nova_callback'] = {"instance_id": instance_id, "status": "success"} resp.body = json.dumps(new_body) return resp elif resource == "ip_addresses": pass # Insert logic to call Nova for ip_addresses changes here return resp
python
def _process_call(self, req, resource): """This is were all callbacks are made and the req is processed.""" if resource == "ports": if req.method.upper() in ('PUT', 'POST'): # Pass the request back to be processed by other filters # and Neutron first resp = req.get_response(self.app) if resp.status_code not in (200, 204): return resp resp_body = resp.json # Variables for Nova Call, obtained from Neutron response action = "create" address = resp_body['port']['mac_address'] fixed_ips = resp_body['port']['fixed_ips'] instance_id = resp_body['port']['instance_id'] network_id = resp_body['port']['network_id'] port_id = resp_body['port']['id'] tenant_id = resp_body['port']['tenant_id'] elif req.method.upper() == "DELETE": action = "delete" port_id = req.path.split("/") port_id = port_id[port_id.index("ports") + 1] # DELETEs do not have all the port info that we need, so a # call to Neutron must be made first. neutron_conn = NeutronConn(log=self.log, port=self.neutron_port, url=self.neutron_url, verify_ssl=self.neutron_verify_ssl) status, neutron_resp = neutron_conn.ports(port_id=port_id) if isinstance(neutron_resp, Exception): return neutron_resp elif status not in (200, 204): resp = Response() resp.status = 500 new_body = {"neutron_callback": {"port_id": port_id, "status": "error", "error": neutron_resp}} resp.body = json.dumps(new_body) return resp # Now that we have the port info, we can make the variables # for the Nova Call address = neutron_resp['port']['mac_address'] fixed_ips = neutron_resp['port']['fixed_ips'] instance_id = neutron_resp['port']['instance_id'] network_id = neutron_resp['port']['network_id'] tenant_id = neutron_resp['port']['tenant_id'] # Port info saved, now send the request back to processed by # other filters and Neutron resp = req.get_response(self.app) if resp.status_code not in (200, 204): return resp else: new_body = resp.json new_body['neutron_callback'] = {"port_id": port_id, "status": "success"} resp.body = json.dumps(new_body) nova_conn = NovaConn(log=self.log, url=self.nova_url, verify_ssl=self.nova_verify_ssl) status, nova_resp = nova_conn.admin_virtual_interfaces( action=action, address=address, fixed_ips=fixed_ips, network_id=network_id, port_id=port_id, tenant_id=tenant_id, instance_id=instance_id) if isinstance(nova_resp, Exception): return nova_resp elif status not in (200, 204): # We'll likely want to provide the customer with a call here # such as virtual-interface-delete/virtual-interface-update resp.status = 500 new_body = resp.json new_body['nova_callback'] = {"instance_id": instance_id, "status": "error", "error": nova_resp} resp.body = json.dumps(new_body) else: new_body = resp.json new_body['nova_callback'] = {"instance_id": instance_id, "status": "success"} resp.body = json.dumps(new_body) return resp elif resource == "ip_addresses": pass # Insert logic to call Nova for ip_addresses changes here return resp
[ "def", "_process_call", "(", "self", ",", "req", ",", "resource", ")", ":", "if", "resource", "==", "\"ports\"", ":", "if", "req", ".", "method", ".", "upper", "(", ")", "in", "(", "'PUT'", ",", "'POST'", ")", ":", "# Pass the request back to be processed by other filters", "# and Neutron first", "resp", "=", "req", ".", "get_response", "(", "self", ".", "app", ")", "if", "resp", ".", "status_code", "not", "in", "(", "200", ",", "204", ")", ":", "return", "resp", "resp_body", "=", "resp", ".", "json", "# Variables for Nova Call, obtained from Neutron response", "action", "=", "\"create\"", "address", "=", "resp_body", "[", "'port'", "]", "[", "'mac_address'", "]", "fixed_ips", "=", "resp_body", "[", "'port'", "]", "[", "'fixed_ips'", "]", "instance_id", "=", "resp_body", "[", "'port'", "]", "[", "'instance_id'", "]", "network_id", "=", "resp_body", "[", "'port'", "]", "[", "'network_id'", "]", "port_id", "=", "resp_body", "[", "'port'", "]", "[", "'id'", "]", "tenant_id", "=", "resp_body", "[", "'port'", "]", "[", "'tenant_id'", "]", "elif", "req", ".", "method", ".", "upper", "(", ")", "==", "\"DELETE\"", ":", "action", "=", "\"delete\"", "port_id", "=", "req", ".", "path", ".", "split", "(", "\"/\"", ")", "port_id", "=", "port_id", "[", "port_id", ".", "index", "(", "\"ports\"", ")", "+", "1", "]", "# DELETEs do not have all the port info that we need, so a", "# call to Neutron must be made first.", "neutron_conn", "=", "NeutronConn", "(", "log", "=", "self", ".", "log", ",", "port", "=", "self", ".", "neutron_port", ",", "url", "=", "self", ".", "neutron_url", ",", "verify_ssl", "=", "self", ".", "neutron_verify_ssl", ")", "status", ",", "neutron_resp", "=", "neutron_conn", ".", "ports", "(", "port_id", "=", "port_id", ")", "if", "isinstance", "(", "neutron_resp", ",", "Exception", ")", ":", "return", "neutron_resp", "elif", "status", "not", "in", "(", "200", ",", "204", ")", ":", "resp", "=", "Response", "(", ")", "resp", ".", "status", "=", "500", "new_body", "=", "{", "\"neutron_callback\"", ":", "{", "\"port_id\"", ":", "port_id", ",", "\"status\"", ":", "\"error\"", ",", "\"error\"", ":", "neutron_resp", "}", "}", "resp", ".", "body", "=", "json", ".", "dumps", "(", "new_body", ")", "return", "resp", "# Now that we have the port info, we can make the variables", "# for the Nova Call", "address", "=", "neutron_resp", "[", "'port'", "]", "[", "'mac_address'", "]", "fixed_ips", "=", "neutron_resp", "[", "'port'", "]", "[", "'fixed_ips'", "]", "instance_id", "=", "neutron_resp", "[", "'port'", "]", "[", "'instance_id'", "]", "network_id", "=", "neutron_resp", "[", "'port'", "]", "[", "'network_id'", "]", "tenant_id", "=", "neutron_resp", "[", "'port'", "]", "[", "'tenant_id'", "]", "# Port info saved, now send the request back to processed by", "# other filters and Neutron", "resp", "=", "req", ".", "get_response", "(", "self", ".", "app", ")", "if", "resp", ".", "status_code", "not", "in", "(", "200", ",", "204", ")", ":", "return", "resp", "else", ":", "new_body", "=", "resp", ".", "json", "new_body", "[", "'neutron_callback'", "]", "=", "{", "\"port_id\"", ":", "port_id", ",", "\"status\"", ":", "\"success\"", "}", "resp", ".", "body", "=", "json", ".", "dumps", "(", "new_body", ")", "nova_conn", "=", "NovaConn", "(", "log", "=", "self", ".", "log", ",", "url", "=", "self", ".", "nova_url", ",", "verify_ssl", "=", "self", ".", "nova_verify_ssl", ")", "status", ",", "nova_resp", "=", "nova_conn", ".", "admin_virtual_interfaces", "(", "action", "=", "action", ",", "address", "=", "address", ",", "fixed_ips", "=", "fixed_ips", ",", "network_id", "=", "network_id", ",", "port_id", "=", "port_id", ",", "tenant_id", "=", "tenant_id", ",", "instance_id", "=", "instance_id", ")", "if", "isinstance", "(", "nova_resp", ",", "Exception", ")", ":", "return", "nova_resp", "elif", "status", "not", "in", "(", "200", ",", "204", ")", ":", "# We'll likely want to provide the customer with a call here", "# such as virtual-interface-delete/virtual-interface-update", "resp", ".", "status", "=", "500", "new_body", "=", "resp", ".", "json", "new_body", "[", "'nova_callback'", "]", "=", "{", "\"instance_id\"", ":", "instance_id", ",", "\"status\"", ":", "\"error\"", ",", "\"error\"", ":", "nova_resp", "}", "resp", ".", "body", "=", "json", ".", "dumps", "(", "new_body", ")", "else", ":", "new_body", "=", "resp", ".", "json", "new_body", "[", "'nova_callback'", "]", "=", "{", "\"instance_id\"", ":", "instance_id", ",", "\"status\"", ":", "\"success\"", "}", "resp", ".", "body", "=", "json", ".", "dumps", "(", "new_body", ")", "return", "resp", "elif", "resource", "==", "\"ip_addresses\"", ":", "pass", "# Insert logic to call Nova for ip_addresses changes here", "return", "resp" ]
This is were all callbacks are made and the req is processed.
[ "This", "is", "were", "all", "callbacks", "are", "made", "and", "the", "req", "is", "processed", "." ]
01f6d69ae759ec2f24f2f7cf9dcfa4a4734f7e1c
https://github.com/roaet/wafflehaus.neutron/blob/01f6d69ae759ec2f24f2f7cf9dcfa4a4734f7e1c/wafflehaus/neutron/nova_interaction/__init__.py#L42-L130
246,171
kalekundert/nonstdlib
nonstdlib/io.py
keep_on_one_line
def keep_on_one_line(): """ Keep all the output generated within a with-block on one line. Whenever a new line would be printed, instead reset the cursor to the beginning of the line and print the new line without a line break. """ class CondensedStream: def __init__(self): self.sys_stdout = sys.stdout def write(self, string): with swap_streams(self.sys_stdout): string = string.replace('\n', ' ') string = truncate_to_fit_terminal(string) if string.strip(): update(string) def flush(self): with swap_streams(self.sys_stdout): flush() with swap_streams(CondensedStream()): yield
python
def keep_on_one_line(): """ Keep all the output generated within a with-block on one line. Whenever a new line would be printed, instead reset the cursor to the beginning of the line and print the new line without a line break. """ class CondensedStream: def __init__(self): self.sys_stdout = sys.stdout def write(self, string): with swap_streams(self.sys_stdout): string = string.replace('\n', ' ') string = truncate_to_fit_terminal(string) if string.strip(): update(string) def flush(self): with swap_streams(self.sys_stdout): flush() with swap_streams(CondensedStream()): yield
[ "def", "keep_on_one_line", "(", ")", ":", "class", "CondensedStream", ":", "def", "__init__", "(", "self", ")", ":", "self", ".", "sys_stdout", "=", "sys", ".", "stdout", "def", "write", "(", "self", ",", "string", ")", ":", "with", "swap_streams", "(", "self", ".", "sys_stdout", ")", ":", "string", "=", "string", ".", "replace", "(", "'\\n'", ",", "' '", ")", "string", "=", "truncate_to_fit_terminal", "(", "string", ")", "if", "string", ".", "strip", "(", ")", ":", "update", "(", "string", ")", "def", "flush", "(", "self", ")", ":", "with", "swap_streams", "(", "self", ".", "sys_stdout", ")", ":", "flush", "(", ")", "with", "swap_streams", "(", "CondensedStream", "(", ")", ")", ":", "yield" ]
Keep all the output generated within a with-block on one line. Whenever a new line would be printed, instead reset the cursor to the beginning of the line and print the new line without a line break.
[ "Keep", "all", "the", "output", "generated", "within", "a", "with", "-", "block", "on", "one", "line", ".", "Whenever", "a", "new", "line", "would", "be", "printed", "instead", "reset", "the", "cursor", "to", "the", "beginning", "of", "the", "line", "and", "print", "the", "new", "line", "without", "a", "line", "break", "." ]
3abf4a4680056d6d97f2a5988972eb9392756fb6
https://github.com/kalekundert/nonstdlib/blob/3abf4a4680056d6d97f2a5988972eb9392756fb6/nonstdlib/io.py#L113-L138
246,172
kalekundert/nonstdlib
nonstdlib/io.py
write_color
def write_color(string, name, style='normal', when='auto'): """ Write the given colored string to standard out. """ write(color(string, name, style, when))
python
def write_color(string, name, style='normal', when='auto'): """ Write the given colored string to standard out. """ write(color(string, name, style, when))
[ "def", "write_color", "(", "string", ",", "name", ",", "style", "=", "'normal'", ",", "when", "=", "'auto'", ")", ":", "write", "(", "color", "(", "string", ",", "name", ",", "style", ",", "when", ")", ")" ]
Write the given colored string to standard out.
[ "Write", "the", "given", "colored", "string", "to", "standard", "out", "." ]
3abf4a4680056d6d97f2a5988972eb9392756fb6
https://github.com/kalekundert/nonstdlib/blob/3abf4a4680056d6d97f2a5988972eb9392756fb6/nonstdlib/io.py#L149-L151
246,173
kalekundert/nonstdlib
nonstdlib/io.py
update_color
def update_color(string, name, style='normal', when='auto'): """ Replace the existing line with the given colored string. """ clear() write_color(string, name, style, when)
python
def update_color(string, name, style='normal', when='auto'): """ Replace the existing line with the given colored string. """ clear() write_color(string, name, style, when)
[ "def", "update_color", "(", "string", ",", "name", ",", "style", "=", "'normal'", ",", "when", "=", "'auto'", ")", ":", "clear", "(", ")", "write_color", "(", "string", ",", "name", ",", "style", ",", "when", ")" ]
Replace the existing line with the given colored string.
[ "Replace", "the", "existing", "line", "with", "the", "given", "colored", "string", "." ]
3abf4a4680056d6d97f2a5988972eb9392756fb6
https://github.com/kalekundert/nonstdlib/blob/3abf4a4680056d6d97f2a5988972eb9392756fb6/nonstdlib/io.py#L158-L161
246,174
kalekundert/nonstdlib
nonstdlib/io.py
progress_color
def progress_color(current, total, name, style='normal', when='auto'): """ Display a simple, colored progress report. """ update_color('[%d/%d] ' % (current, total), name, style, when)
python
def progress_color(current, total, name, style='normal', when='auto'): """ Display a simple, colored progress report. """ update_color('[%d/%d] ' % (current, total), name, style, when)
[ "def", "progress_color", "(", "current", ",", "total", ",", "name", ",", "style", "=", "'normal'", ",", "when", "=", "'auto'", ")", ":", "update_color", "(", "'[%d/%d] '", "%", "(", "current", ",", "total", ")", ",", "name", ",", "style", ",", "when", ")" ]
Display a simple, colored progress report.
[ "Display", "a", "simple", "colored", "progress", "report", "." ]
3abf4a4680056d6d97f2a5988972eb9392756fb6
https://github.com/kalekundert/nonstdlib/blob/3abf4a4680056d6d97f2a5988972eb9392756fb6/nonstdlib/io.py#L167-L169
246,175
kalekundert/nonstdlib
nonstdlib/io.py
color
def color(string, name, style='normal', when='auto'): """ Change the color of the given string. """ if name not in colors: from .text import oxford_comma raise ValueError("unknown color '{}'.\nknown colors are: {}".format( name, oxford_comma(["'{}'".format(x) for x in sorted(colors)]))) if style not in styles: from .text import oxford_comma raise ValueError("unknown style '{}'.\nknown styles are: {}".format( style, oxford_comma(["'{}'".format(x) for x in sorted(styles)]))) prefix = '\033[%d;%dm' % (styles[style], colors[name]) suffix = '\033[%d;%dm' % (styles['normal'], colors['normal']) color_string = prefix + string + suffix if when == 'always': return color_string elif when == 'auto': return color_string if sys.stdout.isatty() else string elif when == 'never': return string else: raise ValueError("when must be one of: 'always', 'auto', 'never'")
python
def color(string, name, style='normal', when='auto'): """ Change the color of the given string. """ if name not in colors: from .text import oxford_comma raise ValueError("unknown color '{}'.\nknown colors are: {}".format( name, oxford_comma(["'{}'".format(x) for x in sorted(colors)]))) if style not in styles: from .text import oxford_comma raise ValueError("unknown style '{}'.\nknown styles are: {}".format( style, oxford_comma(["'{}'".format(x) for x in sorted(styles)]))) prefix = '\033[%d;%dm' % (styles[style], colors[name]) suffix = '\033[%d;%dm' % (styles['normal'], colors['normal']) color_string = prefix + string + suffix if when == 'always': return color_string elif when == 'auto': return color_string if sys.stdout.isatty() else string elif when == 'never': return string else: raise ValueError("when must be one of: 'always', 'auto', 'never'")
[ "def", "color", "(", "string", ",", "name", ",", "style", "=", "'normal'", ",", "when", "=", "'auto'", ")", ":", "if", "name", "not", "in", "colors", ":", "from", ".", "text", "import", "oxford_comma", "raise", "ValueError", "(", "\"unknown color '{}'.\\nknown colors are: {}\"", ".", "format", "(", "name", ",", "oxford_comma", "(", "[", "\"'{}'\"", ".", "format", "(", "x", ")", "for", "x", "in", "sorted", "(", "colors", ")", "]", ")", ")", ")", "if", "style", "not", "in", "styles", ":", "from", ".", "text", "import", "oxford_comma", "raise", "ValueError", "(", "\"unknown style '{}'.\\nknown styles are: {}\"", ".", "format", "(", "style", ",", "oxford_comma", "(", "[", "\"'{}'\"", ".", "format", "(", "x", ")", "for", "x", "in", "sorted", "(", "styles", ")", "]", ")", ")", ")", "prefix", "=", "'\\033[%d;%dm'", "%", "(", "styles", "[", "style", "]", ",", "colors", "[", "name", "]", ")", "suffix", "=", "'\\033[%d;%dm'", "%", "(", "styles", "[", "'normal'", "]", ",", "colors", "[", "'normal'", "]", ")", "color_string", "=", "prefix", "+", "string", "+", "suffix", "if", "when", "==", "'always'", ":", "return", "color_string", "elif", "when", "==", "'auto'", ":", "return", "color_string", "if", "sys", ".", "stdout", ".", "isatty", "(", ")", "else", "string", "elif", "when", "==", "'never'", ":", "return", "string", "else", ":", "raise", "ValueError", "(", "\"when must be one of: 'always', 'auto', 'never'\"", ")" ]
Change the color of the given string.
[ "Change", "the", "color", "of", "the", "given", "string", "." ]
3abf4a4680056d6d97f2a5988972eb9392756fb6
https://github.com/kalekundert/nonstdlib/blob/3abf4a4680056d6d97f2a5988972eb9392756fb6/nonstdlib/io.py#L171-L194
246,176
fstab50/metal
metal/chkrootkit.py
download
def download(objects): """ Retrieve remote file object """ def exists(object): if os.path.exists(TMPDIR + '/' + filename): return True else: msg = 'File object %s failed to download to %s. Exit' % (filename, TMPDIR) logger.warning(msg) stdout_message('%s: %s' % (inspect.stack()[0][3], msg)) return False try: for file_path in objects: filename = file_path.split('/')[-1] r = urllib.request.urlretrieve(file_path, TMPDIR + '/' + filename) if not exists(filename): return False except urllib.error.HTTPError as e: logger.exception( '%s: Failed to retrive file object: %s. Exception: %s, data: %s' % (inspect.stack()[0][3], file_path, str(e), e.read())) raise e return True
python
def download(objects): """ Retrieve remote file object """ def exists(object): if os.path.exists(TMPDIR + '/' + filename): return True else: msg = 'File object %s failed to download to %s. Exit' % (filename, TMPDIR) logger.warning(msg) stdout_message('%s: %s' % (inspect.stack()[0][3], msg)) return False try: for file_path in objects: filename = file_path.split('/')[-1] r = urllib.request.urlretrieve(file_path, TMPDIR + '/' + filename) if not exists(filename): return False except urllib.error.HTTPError as e: logger.exception( '%s: Failed to retrive file object: %s. Exception: %s, data: %s' % (inspect.stack()[0][3], file_path, str(e), e.read())) raise e return True
[ "def", "download", "(", "objects", ")", ":", "def", "exists", "(", "object", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "TMPDIR", "+", "'/'", "+", "filename", ")", ":", "return", "True", "else", ":", "msg", "=", "'File object %s failed to download to %s. Exit'", "%", "(", "filename", ",", "TMPDIR", ")", "logger", ".", "warning", "(", "msg", ")", "stdout_message", "(", "'%s: %s'", "%", "(", "inspect", ".", "stack", "(", ")", "[", "0", "]", "[", "3", "]", ",", "msg", ")", ")", "return", "False", "try", ":", "for", "file_path", "in", "objects", ":", "filename", "=", "file_path", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "r", "=", "urllib", ".", "request", ".", "urlretrieve", "(", "file_path", ",", "TMPDIR", "+", "'/'", "+", "filename", ")", "if", "not", "exists", "(", "filename", ")", ":", "return", "False", "except", "urllib", ".", "error", ".", "HTTPError", "as", "e", ":", "logger", ".", "exception", "(", "'%s: Failed to retrive file object: %s. Exception: %s, data: %s'", "%", "(", "inspect", ".", "stack", "(", ")", "[", "0", "]", "[", "3", "]", ",", "file_path", ",", "str", "(", "e", ")", ",", "e", ".", "read", "(", ")", ")", ")", "raise", "e", "return", "True" ]
Retrieve remote file object
[ "Retrieve", "remote", "file", "object" ]
0488bbdd516a508909267cc44191f632e21156ba
https://github.com/fstab50/metal/blob/0488bbdd516a508909267cc44191f632e21156ba/metal/chkrootkit.py#L73-L96
246,177
fstab50/metal
metal/chkrootkit.py
precheck
def precheck(): """ Pre-run dependency check """ binaries = ['make'] for bin in binaries: if not which(bin): msg = 'Dependency fail -- Unable to locate rquired binary: ' stdout_message('%s: %s' % (msg, ACCENT + bin + RESET)) return False elif not root(): return False return True
python
def precheck(): """ Pre-run dependency check """ binaries = ['make'] for bin in binaries: if not which(bin): msg = 'Dependency fail -- Unable to locate rquired binary: ' stdout_message('%s: %s' % (msg, ACCENT + bin + RESET)) return False elif not root(): return False return True
[ "def", "precheck", "(", ")", ":", "binaries", "=", "[", "'make'", "]", "for", "bin", "in", "binaries", ":", "if", "not", "which", "(", "bin", ")", ":", "msg", "=", "'Dependency fail -- Unable to locate rquired binary: '", "stdout_message", "(", "'%s: %s'", "%", "(", "msg", ",", "ACCENT", "+", "bin", "+", "RESET", ")", ")", "return", "False", "elif", "not", "root", "(", ")", ":", "return", "False", "return", "True" ]
Pre-run dependency check
[ "Pre", "-", "run", "dependency", "check" ]
0488bbdd516a508909267cc44191f632e21156ba
https://github.com/fstab50/metal/blob/0488bbdd516a508909267cc44191f632e21156ba/metal/chkrootkit.py#L189-L201
246,178
knagra/farnsworth
workshift/views.py
start_semester_view
def start_semester_view(request): """ Initiates a semester"s worth of workshift, with the option to copy workshift types from the previous semester. """ page_name = "Start Semester" year, season = utils.get_year_season() start_date, end_date = utils.get_semester_start_end(year, season) semester_form = SemesterForm( data=request.POST or None, initial={ "year": year, "season": season, "start_date": start_date.strftime(date_formats[0]), "end_date": end_date.strftime(date_formats[0]), }, prefix="semester", ) pool_forms = [] try: prev_semester = Semester.objects.latest("end_date") except Semester.DoesNotExist: pass else: pools = WorkshiftPool.objects.filter( semester=prev_semester, is_primary=False, ) for pool in pools: form = StartPoolForm( data=request.POST or None, initial={ "title": pool.title, "hours": pool.hours, }, prefix="pool-{}".format(pool.pk), ) pool_forms.append(form) if semester_form.is_valid() and all(i.is_valid() for i in pool_forms): # And save this semester semester = semester_form.save() for pool_form in pool_forms: pool_form.save(semester=semester) return HttpResponseRedirect(wurl("workshift:manage", sem_url=semester.sem_url)) return render_to_response("start_semester.html", { "page_name": page_name, "semester_form": semester_form, "pool_forms": pool_forms, }, context_instance=RequestContext(request))
python
def start_semester_view(request): """ Initiates a semester"s worth of workshift, with the option to copy workshift types from the previous semester. """ page_name = "Start Semester" year, season = utils.get_year_season() start_date, end_date = utils.get_semester_start_end(year, season) semester_form = SemesterForm( data=request.POST or None, initial={ "year": year, "season": season, "start_date": start_date.strftime(date_formats[0]), "end_date": end_date.strftime(date_formats[0]), }, prefix="semester", ) pool_forms = [] try: prev_semester = Semester.objects.latest("end_date") except Semester.DoesNotExist: pass else: pools = WorkshiftPool.objects.filter( semester=prev_semester, is_primary=False, ) for pool in pools: form = StartPoolForm( data=request.POST or None, initial={ "title": pool.title, "hours": pool.hours, }, prefix="pool-{}".format(pool.pk), ) pool_forms.append(form) if semester_form.is_valid() and all(i.is_valid() for i in pool_forms): # And save this semester semester = semester_form.save() for pool_form in pool_forms: pool_form.save(semester=semester) return HttpResponseRedirect(wurl("workshift:manage", sem_url=semester.sem_url)) return render_to_response("start_semester.html", { "page_name": page_name, "semester_form": semester_form, "pool_forms": pool_forms, }, context_instance=RequestContext(request))
[ "def", "start_semester_view", "(", "request", ")", ":", "page_name", "=", "\"Start Semester\"", "year", ",", "season", "=", "utils", ".", "get_year_season", "(", ")", "start_date", ",", "end_date", "=", "utils", ".", "get_semester_start_end", "(", "year", ",", "season", ")", "semester_form", "=", "SemesterForm", "(", "data", "=", "request", ".", "POST", "or", "None", ",", "initial", "=", "{", "\"year\"", ":", "year", ",", "\"season\"", ":", "season", ",", "\"start_date\"", ":", "start_date", ".", "strftime", "(", "date_formats", "[", "0", "]", ")", ",", "\"end_date\"", ":", "end_date", ".", "strftime", "(", "date_formats", "[", "0", "]", ")", ",", "}", ",", "prefix", "=", "\"semester\"", ",", ")", "pool_forms", "=", "[", "]", "try", ":", "prev_semester", "=", "Semester", ".", "objects", ".", "latest", "(", "\"end_date\"", ")", "except", "Semester", ".", "DoesNotExist", ":", "pass", "else", ":", "pools", "=", "WorkshiftPool", ".", "objects", ".", "filter", "(", "semester", "=", "prev_semester", ",", "is_primary", "=", "False", ",", ")", "for", "pool", "in", "pools", ":", "form", "=", "StartPoolForm", "(", "data", "=", "request", ".", "POST", "or", "None", ",", "initial", "=", "{", "\"title\"", ":", "pool", ".", "title", ",", "\"hours\"", ":", "pool", ".", "hours", ",", "}", ",", "prefix", "=", "\"pool-{}\"", ".", "format", "(", "pool", ".", "pk", ")", ",", ")", "pool_forms", ".", "append", "(", "form", ")", "if", "semester_form", ".", "is_valid", "(", ")", "and", "all", "(", "i", ".", "is_valid", "(", ")", "for", "i", "in", "pool_forms", ")", ":", "# And save this semester", "semester", "=", "semester_form", ".", "save", "(", ")", "for", "pool_form", "in", "pool_forms", ":", "pool_form", ".", "save", "(", "semester", "=", "semester", ")", "return", "HttpResponseRedirect", "(", "wurl", "(", "\"workshift:manage\"", ",", "sem_url", "=", "semester", ".", "sem_url", ")", ")", "return", "render_to_response", "(", "\"start_semester.html\"", ",", "{", "\"page_name\"", ":", "page_name", ",", "\"semester_form\"", ":", "semester_form", ",", "\"pool_forms\"", ":", "pool_forms", ",", "}", ",", "context_instance", "=", "RequestContext", "(", "request", ")", ")" ]
Initiates a semester"s worth of workshift, with the option to copy workshift types from the previous semester.
[ "Initiates", "a", "semester", "s", "worth", "of", "workshift", "with", "the", "option", "to", "copy", "workshift", "types", "from", "the", "previous", "semester", "." ]
1b6589f0d9fea154f0a1e2231ed906764ed26d26
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L196-L249
246,179
knagra/farnsworth
workshift/views.py
_is_preferred
def _is_preferred(instance, profile): """ Check if a user has marked an instance's workshift type as preferred. """ if not instance.weekly_workshift: return False if profile and profile.ratings.filter( workshift_type=instance.weekly_workshift.workshift_type, rating=WorkshiftRating.LIKE, ).count() == 0: return False return True
python
def _is_preferred(instance, profile): """ Check if a user has marked an instance's workshift type as preferred. """ if not instance.weekly_workshift: return False if profile and profile.ratings.filter( workshift_type=instance.weekly_workshift.workshift_type, rating=WorkshiftRating.LIKE, ).count() == 0: return False return True
[ "def", "_is_preferred", "(", "instance", ",", "profile", ")", ":", "if", "not", "instance", ".", "weekly_workshift", ":", "return", "False", "if", "profile", "and", "profile", ".", "ratings", ".", "filter", "(", "workshift_type", "=", "instance", ".", "weekly_workshift", ".", "workshift_type", ",", "rating", "=", "WorkshiftRating", ".", "LIKE", ",", ")", ".", "count", "(", ")", "==", "0", ":", "return", "False", "return", "True" ]
Check if a user has marked an instance's workshift type as preferred.
[ "Check", "if", "a", "user", "has", "marked", "an", "instance", "s", "workshift", "type", "as", "preferred", "." ]
1b6589f0d9fea154f0a1e2231ed906764ed26d26
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L540-L551
246,180
knagra/farnsworth
workshift/views.py
profile_view
def profile_view(request, semester, targetUsername, profile=None): """ Show the user their workshift history for the current semester as well as upcoming shifts. """ wprofile = get_object_or_404( WorkshiftProfile, user__username=targetUsername, semester=semester ) if wprofile == profile: page_name = "My Workshift Profile" else: page_name = "{}'s Workshift Profile".format(wprofile.user.get_full_name()) past_shifts = WorkshiftInstance.objects.filter( Q(workshifter=wprofile) | Q(liable=wprofile), closed=True, ) regular_shifts = RegularWorkshift.objects.filter( active=True, current_assignees=wprofile, ) assigned_instances = WorkshiftInstance.objects.filter( Q(workshifter=wprofile) | Q(liable=wprofile), closed=False, ).exclude( weekly_workshift__current_assignees=wprofile, ) pool_hours = wprofile.pool_hours.order_by( "-pool__is_primary", "pool__title", ) first_standing, second_standing, third_standing = \ any(pool_hours.first_date_standing for pool_hours in wprofile.pool_hours.all()), \ any(pool_hours.second_date_standing for pool_hours in wprofile.pool_hours.all()), \ any(pool_hours.third_date_standing for pool_hours in wprofile.pool_hours.all()) full_management = utils.can_manage(request.user, semester=semester) any_management = utils.can_manage(request.user, semester, any_pool=True) view_note = wprofile == profile or full_management return render_to_response("profile.html", { "page_name": page_name, "profile": wprofile, "view_note": view_note, "past_shifts": past_shifts, "regular_shifts": regular_shifts, "assigned_instances": assigned_instances, "pool_hours": pool_hours, "first_standing": first_standing, "second_standing": second_standing, "third_standing": third_standing, "can_edit": any_management, }, context_instance=RequestContext(request))
python
def profile_view(request, semester, targetUsername, profile=None): """ Show the user their workshift history for the current semester as well as upcoming shifts. """ wprofile = get_object_or_404( WorkshiftProfile, user__username=targetUsername, semester=semester ) if wprofile == profile: page_name = "My Workshift Profile" else: page_name = "{}'s Workshift Profile".format(wprofile.user.get_full_name()) past_shifts = WorkshiftInstance.objects.filter( Q(workshifter=wprofile) | Q(liable=wprofile), closed=True, ) regular_shifts = RegularWorkshift.objects.filter( active=True, current_assignees=wprofile, ) assigned_instances = WorkshiftInstance.objects.filter( Q(workshifter=wprofile) | Q(liable=wprofile), closed=False, ).exclude( weekly_workshift__current_assignees=wprofile, ) pool_hours = wprofile.pool_hours.order_by( "-pool__is_primary", "pool__title", ) first_standing, second_standing, third_standing = \ any(pool_hours.first_date_standing for pool_hours in wprofile.pool_hours.all()), \ any(pool_hours.second_date_standing for pool_hours in wprofile.pool_hours.all()), \ any(pool_hours.third_date_standing for pool_hours in wprofile.pool_hours.all()) full_management = utils.can_manage(request.user, semester=semester) any_management = utils.can_manage(request.user, semester, any_pool=True) view_note = wprofile == profile or full_management return render_to_response("profile.html", { "page_name": page_name, "profile": wprofile, "view_note": view_note, "past_shifts": past_shifts, "regular_shifts": regular_shifts, "assigned_instances": assigned_instances, "pool_hours": pool_hours, "first_standing": first_standing, "second_standing": second_standing, "third_standing": third_standing, "can_edit": any_management, }, context_instance=RequestContext(request))
[ "def", "profile_view", "(", "request", ",", "semester", ",", "targetUsername", ",", "profile", "=", "None", ")", ":", "wprofile", "=", "get_object_or_404", "(", "WorkshiftProfile", ",", "user__username", "=", "targetUsername", ",", "semester", "=", "semester", ")", "if", "wprofile", "==", "profile", ":", "page_name", "=", "\"My Workshift Profile\"", "else", ":", "page_name", "=", "\"{}'s Workshift Profile\"", ".", "format", "(", "wprofile", ".", "user", ".", "get_full_name", "(", ")", ")", "past_shifts", "=", "WorkshiftInstance", ".", "objects", ".", "filter", "(", "Q", "(", "workshifter", "=", "wprofile", ")", "|", "Q", "(", "liable", "=", "wprofile", ")", ",", "closed", "=", "True", ",", ")", "regular_shifts", "=", "RegularWorkshift", ".", "objects", ".", "filter", "(", "active", "=", "True", ",", "current_assignees", "=", "wprofile", ",", ")", "assigned_instances", "=", "WorkshiftInstance", ".", "objects", ".", "filter", "(", "Q", "(", "workshifter", "=", "wprofile", ")", "|", "Q", "(", "liable", "=", "wprofile", ")", ",", "closed", "=", "False", ",", ")", ".", "exclude", "(", "weekly_workshift__current_assignees", "=", "wprofile", ",", ")", "pool_hours", "=", "wprofile", ".", "pool_hours", ".", "order_by", "(", "\"-pool__is_primary\"", ",", "\"pool__title\"", ",", ")", "first_standing", ",", "second_standing", ",", "third_standing", "=", "any", "(", "pool_hours", ".", "first_date_standing", "for", "pool_hours", "in", "wprofile", ".", "pool_hours", ".", "all", "(", ")", ")", ",", "any", "(", "pool_hours", ".", "second_date_standing", "for", "pool_hours", "in", "wprofile", ".", "pool_hours", ".", "all", "(", ")", ")", ",", "any", "(", "pool_hours", ".", "third_date_standing", "for", "pool_hours", "in", "wprofile", ".", "pool_hours", ".", "all", "(", ")", ")", "full_management", "=", "utils", ".", "can_manage", "(", "request", ".", "user", ",", "semester", "=", "semester", ")", "any_management", "=", "utils", ".", "can_manage", "(", "request", ".", "user", ",", "semester", ",", "any_pool", "=", "True", ")", "view_note", "=", "wprofile", "==", "profile", "or", "full_management", "return", "render_to_response", "(", "\"profile.html\"", ",", "{", "\"page_name\"", ":", "page_name", ",", "\"profile\"", ":", "wprofile", ",", "\"view_note\"", ":", "view_note", ",", "\"past_shifts\"", ":", "past_shifts", ",", "\"regular_shifts\"", ":", "regular_shifts", ",", "\"assigned_instances\"", ":", "assigned_instances", ",", "\"pool_hours\"", ":", "pool_hours", ",", "\"first_standing\"", ":", "first_standing", ",", "\"second_standing\"", ":", "second_standing", ",", "\"third_standing\"", ":", "third_standing", ",", "\"can_edit\"", ":", "any_management", ",", "}", ",", "context_instance", "=", "RequestContext", "(", "request", ")", ")" ]
Show the user their workshift history for the current semester as well as upcoming shifts.
[ "Show", "the", "user", "their", "workshift", "history", "for", "the", "current", "semester", "as", "well", "as", "upcoming", "shifts", "." ]
1b6589f0d9fea154f0a1e2231ed906764ed26d26
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L651-L703
246,181
knagra/farnsworth
workshift/views.py
preferences_view
def preferences_view(request, semester, targetUsername, profile=None): """ Show the user their preferences for the given semester. """ # TODO: Change template to show descriptions in tooltip / ajax show box? wprofile = get_object_or_404( WorkshiftProfile, user__username=targetUsername, ) full_management = utils.can_manage(request.user, semester=semester) if wprofile.user != request.user and \ not full_management: messages.add_message( request, messages.ERROR, MESSAGES["ADMINS_ONLY"], ) return HttpResponseRedirect(semester.get_view_url()) rating_forms = [] for wtype in WorkshiftType.objects.filter(rateable=True): try: rating = wprofile.ratings.get(workshift_type=wtype) except WorkshiftRating.DoesNotExist: rating = WorkshiftRating(workshift_type=wtype) form = WorkshiftRatingForm( data=request.POST or None, prefix="rating-{}".format(wtype.pk), instance=rating, profile=wprofile, ) rating_forms.append(form) time_formset = TimeBlockFormSet( data=request.POST or None, prefix="time", profile=wprofile, ) note_form = ProfileNoteForm( data=request.POST or None, instance=wprofile, prefix="note", ) if all(i.is_valid() for i in rating_forms) and time_formset.is_valid() and \ note_form.is_valid(): for form in rating_forms: form.save() time_formset.save() note_form.save() if wprofile.preference_save_time is None: wprofile.preference_save_time = now() wprofile.save() messages.add_message( request, messages.INFO, "Preferences saved.", ) return HttpResponseRedirect(wurl( "workshift:preferences", sem_url=semester.sem_url, targetUsername=request.user.username, )) if wprofile == profile: page_name = "My Workshift Preferences" else: page_name = "{}'s Workshift Preferences".format( wprofile.user.get_full_name(), ) return render_to_response("preferences.html", { "page_name": page_name, "profile": wprofile, "rating_forms": rating_forms, "time_formset": time_formset, "note_form": note_form, }, context_instance=RequestContext(request))
python
def preferences_view(request, semester, targetUsername, profile=None): """ Show the user their preferences for the given semester. """ # TODO: Change template to show descriptions in tooltip / ajax show box? wprofile = get_object_or_404( WorkshiftProfile, user__username=targetUsername, ) full_management = utils.can_manage(request.user, semester=semester) if wprofile.user != request.user and \ not full_management: messages.add_message( request, messages.ERROR, MESSAGES["ADMINS_ONLY"], ) return HttpResponseRedirect(semester.get_view_url()) rating_forms = [] for wtype in WorkshiftType.objects.filter(rateable=True): try: rating = wprofile.ratings.get(workshift_type=wtype) except WorkshiftRating.DoesNotExist: rating = WorkshiftRating(workshift_type=wtype) form = WorkshiftRatingForm( data=request.POST or None, prefix="rating-{}".format(wtype.pk), instance=rating, profile=wprofile, ) rating_forms.append(form) time_formset = TimeBlockFormSet( data=request.POST or None, prefix="time", profile=wprofile, ) note_form = ProfileNoteForm( data=request.POST or None, instance=wprofile, prefix="note", ) if all(i.is_valid() for i in rating_forms) and time_formset.is_valid() and \ note_form.is_valid(): for form in rating_forms: form.save() time_formset.save() note_form.save() if wprofile.preference_save_time is None: wprofile.preference_save_time = now() wprofile.save() messages.add_message( request, messages.INFO, "Preferences saved.", ) return HttpResponseRedirect(wurl( "workshift:preferences", sem_url=semester.sem_url, targetUsername=request.user.username, )) if wprofile == profile: page_name = "My Workshift Preferences" else: page_name = "{}'s Workshift Preferences".format( wprofile.user.get_full_name(), ) return render_to_response("preferences.html", { "page_name": page_name, "profile": wprofile, "rating_forms": rating_forms, "time_formset": time_formset, "note_form": note_form, }, context_instance=RequestContext(request))
[ "def", "preferences_view", "(", "request", ",", "semester", ",", "targetUsername", ",", "profile", "=", "None", ")", ":", "# TODO: Change template to show descriptions in tooltip / ajax show box?", "wprofile", "=", "get_object_or_404", "(", "WorkshiftProfile", ",", "user__username", "=", "targetUsername", ",", ")", "full_management", "=", "utils", ".", "can_manage", "(", "request", ".", "user", ",", "semester", "=", "semester", ")", "if", "wprofile", ".", "user", "!=", "request", ".", "user", "and", "not", "full_management", ":", "messages", ".", "add_message", "(", "request", ",", "messages", ".", "ERROR", ",", "MESSAGES", "[", "\"ADMINS_ONLY\"", "]", ",", ")", "return", "HttpResponseRedirect", "(", "semester", ".", "get_view_url", "(", ")", ")", "rating_forms", "=", "[", "]", "for", "wtype", "in", "WorkshiftType", ".", "objects", ".", "filter", "(", "rateable", "=", "True", ")", ":", "try", ":", "rating", "=", "wprofile", ".", "ratings", ".", "get", "(", "workshift_type", "=", "wtype", ")", "except", "WorkshiftRating", ".", "DoesNotExist", ":", "rating", "=", "WorkshiftRating", "(", "workshift_type", "=", "wtype", ")", "form", "=", "WorkshiftRatingForm", "(", "data", "=", "request", ".", "POST", "or", "None", ",", "prefix", "=", "\"rating-{}\"", ".", "format", "(", "wtype", ".", "pk", ")", ",", "instance", "=", "rating", ",", "profile", "=", "wprofile", ",", ")", "rating_forms", ".", "append", "(", "form", ")", "time_formset", "=", "TimeBlockFormSet", "(", "data", "=", "request", ".", "POST", "or", "None", ",", "prefix", "=", "\"time\"", ",", "profile", "=", "wprofile", ",", ")", "note_form", "=", "ProfileNoteForm", "(", "data", "=", "request", ".", "POST", "or", "None", ",", "instance", "=", "wprofile", ",", "prefix", "=", "\"note\"", ",", ")", "if", "all", "(", "i", ".", "is_valid", "(", ")", "for", "i", "in", "rating_forms", ")", "and", "time_formset", ".", "is_valid", "(", ")", "and", "note_form", ".", "is_valid", "(", ")", ":", "for", "form", "in", "rating_forms", ":", "form", ".", "save", "(", ")", "time_formset", ".", "save", "(", ")", "note_form", ".", "save", "(", ")", "if", "wprofile", ".", "preference_save_time", "is", "None", ":", "wprofile", ".", "preference_save_time", "=", "now", "(", ")", "wprofile", ".", "save", "(", ")", "messages", ".", "add_message", "(", "request", ",", "messages", ".", "INFO", ",", "\"Preferences saved.\"", ",", ")", "return", "HttpResponseRedirect", "(", "wurl", "(", "\"workshift:preferences\"", ",", "sem_url", "=", "semester", ".", "sem_url", ",", "targetUsername", "=", "request", ".", "user", ".", "username", ",", ")", ")", "if", "wprofile", "==", "profile", ":", "page_name", "=", "\"My Workshift Preferences\"", "else", ":", "page_name", "=", "\"{}'s Workshift Preferences\"", ".", "format", "(", "wprofile", ".", "user", ".", "get_full_name", "(", ")", ",", ")", "return", "render_to_response", "(", "\"preferences.html\"", ",", "{", "\"page_name\"", ":", "page_name", ",", "\"profile\"", ":", "wprofile", ",", "\"rating_forms\"", ":", "rating_forms", ",", "\"time_formset\"", ":", "time_formset", ",", "\"note_form\"", ":", "note_form", ",", "}", ",", "context_instance", "=", "RequestContext", "(", "request", ")", ")" ]
Show the user their preferences for the given semester.
[ "Show", "the", "user", "their", "preferences", "for", "the", "given", "semester", "." ]
1b6589f0d9fea154f0a1e2231ed906764ed26d26
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L707-L784
246,182
knagra/farnsworth
workshift/views.py
adjust_hours_view
def adjust_hours_view(request, semester): """ Adjust members' workshift hours requirements. """ page_name = "Adjust Hours" pools = WorkshiftPool.objects.filter(semester=semester).order_by( "-is_primary", "title", ) workshifters = WorkshiftProfile.objects.filter(semester=semester) pool_hour_forms = [] for workshifter in workshifters: forms_list = [] for pool in pools: hours = workshifter.pool_hours.get(pool=pool) forms_list.append(( AdjustHoursForm( data=request.POST or None, prefix="pool_hours-{}".format(hours.pk), instance=hours, ), hours, )) pool_hour_forms.append(forms_list) if all( form.is_valid() for workshifter_forms in pool_hour_forms for form, pool_hours in workshifter_forms ): for workshifter_forms in pool_hour_forms: for form, pool_hours in workshifter_forms: form.save() messages.add_message(request, messages.INFO, "Updated hours.") return HttpResponseRedirect(wurl( "workshift:adjust_hours", sem_url=semester.sem_url, )) return render_to_response("adjust_hours.html", { "page_name": page_name, "pools": pools, "workshifters_tuples": zip(workshifters, pool_hour_forms), }, context_instance=RequestContext(request))
python
def adjust_hours_view(request, semester): """ Adjust members' workshift hours requirements. """ page_name = "Adjust Hours" pools = WorkshiftPool.objects.filter(semester=semester).order_by( "-is_primary", "title", ) workshifters = WorkshiftProfile.objects.filter(semester=semester) pool_hour_forms = [] for workshifter in workshifters: forms_list = [] for pool in pools: hours = workshifter.pool_hours.get(pool=pool) forms_list.append(( AdjustHoursForm( data=request.POST or None, prefix="pool_hours-{}".format(hours.pk), instance=hours, ), hours, )) pool_hour_forms.append(forms_list) if all( form.is_valid() for workshifter_forms in pool_hour_forms for form, pool_hours in workshifter_forms ): for workshifter_forms in pool_hour_forms: for form, pool_hours in workshifter_forms: form.save() messages.add_message(request, messages.INFO, "Updated hours.") return HttpResponseRedirect(wurl( "workshift:adjust_hours", sem_url=semester.sem_url, )) return render_to_response("adjust_hours.html", { "page_name": page_name, "pools": pools, "workshifters_tuples": zip(workshifters, pool_hour_forms), }, context_instance=RequestContext(request))
[ "def", "adjust_hours_view", "(", "request", ",", "semester", ")", ":", "page_name", "=", "\"Adjust Hours\"", "pools", "=", "WorkshiftPool", ".", "objects", ".", "filter", "(", "semester", "=", "semester", ")", ".", "order_by", "(", "\"-is_primary\"", ",", "\"title\"", ",", ")", "workshifters", "=", "WorkshiftProfile", ".", "objects", ".", "filter", "(", "semester", "=", "semester", ")", "pool_hour_forms", "=", "[", "]", "for", "workshifter", "in", "workshifters", ":", "forms_list", "=", "[", "]", "for", "pool", "in", "pools", ":", "hours", "=", "workshifter", ".", "pool_hours", ".", "get", "(", "pool", "=", "pool", ")", "forms_list", ".", "append", "(", "(", "AdjustHoursForm", "(", "data", "=", "request", ".", "POST", "or", "None", ",", "prefix", "=", "\"pool_hours-{}\"", ".", "format", "(", "hours", ".", "pk", ")", ",", "instance", "=", "hours", ",", ")", ",", "hours", ",", ")", ")", "pool_hour_forms", ".", "append", "(", "forms_list", ")", "if", "all", "(", "form", ".", "is_valid", "(", ")", "for", "workshifter_forms", "in", "pool_hour_forms", "for", "form", ",", "pool_hours", "in", "workshifter_forms", ")", ":", "for", "workshifter_forms", "in", "pool_hour_forms", ":", "for", "form", ",", "pool_hours", "in", "workshifter_forms", ":", "form", ".", "save", "(", ")", "messages", ".", "add_message", "(", "request", ",", "messages", ".", "INFO", ",", "\"Updated hours.\"", ")", "return", "HttpResponseRedirect", "(", "wurl", "(", "\"workshift:adjust_hours\"", ",", "sem_url", "=", "semester", ".", "sem_url", ",", ")", ")", "return", "render_to_response", "(", "\"adjust_hours.html\"", ",", "{", "\"page_name\"", ":", "page_name", ",", "\"pools\"", ":", "pools", ",", "\"workshifters_tuples\"", ":", "zip", "(", "workshifters", ",", "pool_hour_forms", ")", ",", "}", ",", "context_instance", "=", "RequestContext", "(", "request", ")", ")" ]
Adjust members' workshift hours requirements.
[ "Adjust", "members", "workshift", "hours", "requirements", "." ]
1b6589f0d9fea154f0a1e2231ed906764ed26d26
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L1025-L1069
246,183
knagra/farnsworth
workshift/views.py
add_workshifter_view
def add_workshifter_view(request, semester): """ Add a new member workshift profile, for people who join mid-semester. """ page_name = "Add Workshifter" existing = [ i.user.pk for i in WorkshiftProfile.objects.filter(semester=semester) ] users = User.objects.exclude( Q(pk__in=existing) | Q(is_active=False) | Q(userprofile__status=UserProfile.ALUMNUS) ) add_workshifter_forms = [] for user in users: form = AddWorkshifterForm( data=request.POST or None, prefix="user-{}".format(user.pk), user=user, semester=semester, ) add_workshifter_forms.append(form) if add_workshifter_forms and \ all(form.is_valid() for form in add_workshifter_forms): for form in add_workshifter_forms: form.save() messages.add_message( request, messages.INFO, "Workshifters added.", ) return HttpResponseRedirect(wurl( "workshift:manage", sem_url=semester.sem_url, )) return render_to_response("add_workshifter.html", { "page_name": page_name, "add_workshifter_forms": add_workshifter_forms, }, context_instance=RequestContext(request))
python
def add_workshifter_view(request, semester): """ Add a new member workshift profile, for people who join mid-semester. """ page_name = "Add Workshifter" existing = [ i.user.pk for i in WorkshiftProfile.objects.filter(semester=semester) ] users = User.objects.exclude( Q(pk__in=existing) | Q(is_active=False) | Q(userprofile__status=UserProfile.ALUMNUS) ) add_workshifter_forms = [] for user in users: form = AddWorkshifterForm( data=request.POST or None, prefix="user-{}".format(user.pk), user=user, semester=semester, ) add_workshifter_forms.append(form) if add_workshifter_forms and \ all(form.is_valid() for form in add_workshifter_forms): for form in add_workshifter_forms: form.save() messages.add_message( request, messages.INFO, "Workshifters added.", ) return HttpResponseRedirect(wurl( "workshift:manage", sem_url=semester.sem_url, )) return render_to_response("add_workshifter.html", { "page_name": page_name, "add_workshifter_forms": add_workshifter_forms, }, context_instance=RequestContext(request))
[ "def", "add_workshifter_view", "(", "request", ",", "semester", ")", ":", "page_name", "=", "\"Add Workshifter\"", "existing", "=", "[", "i", ".", "user", ".", "pk", "for", "i", "in", "WorkshiftProfile", ".", "objects", ".", "filter", "(", "semester", "=", "semester", ")", "]", "users", "=", "User", ".", "objects", ".", "exclude", "(", "Q", "(", "pk__in", "=", "existing", ")", "|", "Q", "(", "is_active", "=", "False", ")", "|", "Q", "(", "userprofile__status", "=", "UserProfile", ".", "ALUMNUS", ")", ")", "add_workshifter_forms", "=", "[", "]", "for", "user", "in", "users", ":", "form", "=", "AddWorkshifterForm", "(", "data", "=", "request", ".", "POST", "or", "None", ",", "prefix", "=", "\"user-{}\"", ".", "format", "(", "user", ".", "pk", ")", ",", "user", "=", "user", ",", "semester", "=", "semester", ",", ")", "add_workshifter_forms", ".", "append", "(", "form", ")", "if", "add_workshifter_forms", "and", "all", "(", "form", ".", "is_valid", "(", ")", "for", "form", "in", "add_workshifter_forms", ")", ":", "for", "form", "in", "add_workshifter_forms", ":", "form", ".", "save", "(", ")", "messages", ".", "add_message", "(", "request", ",", "messages", ".", "INFO", ",", "\"Workshifters added.\"", ",", ")", "return", "HttpResponseRedirect", "(", "wurl", "(", "\"workshift:manage\"", ",", "sem_url", "=", "semester", ".", "sem_url", ",", ")", ")", "return", "render_to_response", "(", "\"add_workshifter.html\"", ",", "{", "\"page_name\"", ":", "page_name", ",", "\"add_workshifter_forms\"", ":", "add_workshifter_forms", ",", "}", ",", "context_instance", "=", "RequestContext", "(", "request", ")", ")" ]
Add a new member workshift profile, for people who join mid-semester.
[ "Add", "a", "new", "member", "workshift", "profile", "for", "people", "who", "join", "mid", "-", "semester", "." ]
1b6589f0d9fea154f0a1e2231ed906764ed26d26
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L1074-L1116
246,184
knagra/farnsworth
workshift/views.py
fill_shifts_view
def fill_shifts_view(request, semester): """ Allows managers to quickly fill in the default workshifts for a few given workshift pools. """ page_name = "Fill Shifts" fill_regular_shifts_form = None fill_social_shifts_form = None fill_humor_shifts_form = None fill_bathroom_shifts_form = None fill_hi_shifts_form = None reset_all_shifts_form = None managers = Manager.objects.filter(incumbent__user=request.user) admin = utils.can_manage(request.user, semester=semester) if admin: fill_regular_shifts_form = FillRegularShiftsForm( data=request.POST, semester=semester, ) fill_humor_shifts_form = FillHumorShiftsForm( data=request.POST, semester=semester, ) fill_bathroom_shifts_form = FillBathroomShiftsForm( data=request.POST, semester=semester, ) reset_all_shifts_form = ResetAllShiftsForm( data=request.POST, semester=semester, ) # XXX: BAD! We should filter by pool owners? By Manager bool flags? By # arbitrary django permissions? if admin or managers.filter(title="Social Manager"): fill_social_shifts_form = FillSocialShiftsForm( data=request.POST, semester=semester, ) # XXX: See above if admin or managers.filter(title="Maintenance Manager"): fill_hi_shifts_form = FillHIShiftsForm( data=request.POST, semester=semester, ) fill_forms = [ fill_regular_shifts_form, fill_social_shifts_form, fill_humor_shifts_form, fill_bathroom_shifts_form, fill_hi_shifts_form, reset_all_shifts_form, ] fill_forms = [ form for form in fill_forms if form is not None ] for form in fill_forms: if form and form.is_valid(): count = form.save() messages.add_message( request, messages.INFO, "{} {} {}".format( form.message, count, p.plural("workshift", count), ), ) return HttpResponseRedirect(wurl( "workshift:fill_shifts", sem_url=semester.sem_url, )) return render_to_response("fill_shifts.html", { "page_name": page_name, "forms": fill_forms, }, context_instance=RequestContext(request))
python
def fill_shifts_view(request, semester): """ Allows managers to quickly fill in the default workshifts for a few given workshift pools. """ page_name = "Fill Shifts" fill_regular_shifts_form = None fill_social_shifts_form = None fill_humor_shifts_form = None fill_bathroom_shifts_form = None fill_hi_shifts_form = None reset_all_shifts_form = None managers = Manager.objects.filter(incumbent__user=request.user) admin = utils.can_manage(request.user, semester=semester) if admin: fill_regular_shifts_form = FillRegularShiftsForm( data=request.POST, semester=semester, ) fill_humor_shifts_form = FillHumorShiftsForm( data=request.POST, semester=semester, ) fill_bathroom_shifts_form = FillBathroomShiftsForm( data=request.POST, semester=semester, ) reset_all_shifts_form = ResetAllShiftsForm( data=request.POST, semester=semester, ) # XXX: BAD! We should filter by pool owners? By Manager bool flags? By # arbitrary django permissions? if admin or managers.filter(title="Social Manager"): fill_social_shifts_form = FillSocialShiftsForm( data=request.POST, semester=semester, ) # XXX: See above if admin or managers.filter(title="Maintenance Manager"): fill_hi_shifts_form = FillHIShiftsForm( data=request.POST, semester=semester, ) fill_forms = [ fill_regular_shifts_form, fill_social_shifts_form, fill_humor_shifts_form, fill_bathroom_shifts_form, fill_hi_shifts_form, reset_all_shifts_form, ] fill_forms = [ form for form in fill_forms if form is not None ] for form in fill_forms: if form and form.is_valid(): count = form.save() messages.add_message( request, messages.INFO, "{} {} {}".format( form.message, count, p.plural("workshift", count), ), ) return HttpResponseRedirect(wurl( "workshift:fill_shifts", sem_url=semester.sem_url, )) return render_to_response("fill_shifts.html", { "page_name": page_name, "forms": fill_forms, }, context_instance=RequestContext(request))
[ "def", "fill_shifts_view", "(", "request", ",", "semester", ")", ":", "page_name", "=", "\"Fill Shifts\"", "fill_regular_shifts_form", "=", "None", "fill_social_shifts_form", "=", "None", "fill_humor_shifts_form", "=", "None", "fill_bathroom_shifts_form", "=", "None", "fill_hi_shifts_form", "=", "None", "reset_all_shifts_form", "=", "None", "managers", "=", "Manager", ".", "objects", ".", "filter", "(", "incumbent__user", "=", "request", ".", "user", ")", "admin", "=", "utils", ".", "can_manage", "(", "request", ".", "user", ",", "semester", "=", "semester", ")", "if", "admin", ":", "fill_regular_shifts_form", "=", "FillRegularShiftsForm", "(", "data", "=", "request", ".", "POST", ",", "semester", "=", "semester", ",", ")", "fill_humor_shifts_form", "=", "FillHumorShiftsForm", "(", "data", "=", "request", ".", "POST", ",", "semester", "=", "semester", ",", ")", "fill_bathroom_shifts_form", "=", "FillBathroomShiftsForm", "(", "data", "=", "request", ".", "POST", ",", "semester", "=", "semester", ",", ")", "reset_all_shifts_form", "=", "ResetAllShiftsForm", "(", "data", "=", "request", ".", "POST", ",", "semester", "=", "semester", ",", ")", "# XXX: BAD! We should filter by pool owners? By Manager bool flags? By", "# arbitrary django permissions?", "if", "admin", "or", "managers", ".", "filter", "(", "title", "=", "\"Social Manager\"", ")", ":", "fill_social_shifts_form", "=", "FillSocialShiftsForm", "(", "data", "=", "request", ".", "POST", ",", "semester", "=", "semester", ",", ")", "# XXX: See above", "if", "admin", "or", "managers", ".", "filter", "(", "title", "=", "\"Maintenance Manager\"", ")", ":", "fill_hi_shifts_form", "=", "FillHIShiftsForm", "(", "data", "=", "request", ".", "POST", ",", "semester", "=", "semester", ",", ")", "fill_forms", "=", "[", "fill_regular_shifts_form", ",", "fill_social_shifts_form", ",", "fill_humor_shifts_form", ",", "fill_bathroom_shifts_form", ",", "fill_hi_shifts_form", ",", "reset_all_shifts_form", ",", "]", "fill_forms", "=", "[", "form", "for", "form", "in", "fill_forms", "if", "form", "is", "not", "None", "]", "for", "form", "in", "fill_forms", ":", "if", "form", "and", "form", ".", "is_valid", "(", ")", ":", "count", "=", "form", ".", "save", "(", ")", "messages", ".", "add_message", "(", "request", ",", "messages", ".", "INFO", ",", "\"{} {} {}\"", ".", "format", "(", "form", ".", "message", ",", "count", ",", "p", ".", "plural", "(", "\"workshift\"", ",", "count", ")", ",", ")", ",", ")", "return", "HttpResponseRedirect", "(", "wurl", "(", "\"workshift:fill_shifts\"", ",", "sem_url", "=", "semester", ".", "sem_url", ",", ")", ")", "return", "render_to_response", "(", "\"fill_shifts.html\"", ",", "{", "\"page_name\"", ":", "page_name", ",", "\"forms\"", ":", "fill_forms", ",", "}", ",", "context_instance", "=", "RequestContext", "(", "request", ")", ")" ]
Allows managers to quickly fill in the default workshifts for a few given workshift pools.
[ "Allows", "managers", "to", "quickly", "fill", "in", "the", "default", "workshifts", "for", "a", "few", "given", "workshift", "pools", "." ]
1b6589f0d9fea154f0a1e2231ed906764ed26d26
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L1151-L1228
246,185
knagra/farnsworth
workshift/views.py
add_shift_view
def add_shift_view(request, semester): """ View for the workshift manager to create new types of workshifts. """ page_name = "Add Workshift" any_management = utils.can_manage(request.user, semester, any_pool=True) if not any_management: messages.add_message( request, messages.ERROR, MESSAGES["ADMINS_ONLY"], ) return HttpResponseRedirect(semester.get_view_url()) # Check what pools this person can manage pools = WorkshiftPool.objects.filter(semester=semester) full_management = utils.can_manage(request.user, semester=semester) if not full_management: pools = pools.filter(managers__incumbent__user=request.user) # Forms add_type_form = WorkshiftTypeForm( data=request.POST if "add_type" in request.POST else None, prefix="type", ) shifts_formset = RegularWorkshiftFormSet( data=request.POST if "add_type" in request.POST else None, prefix="shifts", queryset=RegularWorkshift.objects.none(), pools=pools, ) if add_type_form.is_valid() and shifts_formset.is_valid(): wtype = add_type_form.save() shifts_formset.save(workshift_type=wtype) return HttpResponseRedirect(wurl( "workshift:manage", sem_url=semester.sem_url, )) add_instance_form = WorkshiftInstanceForm( data=request.POST if "add_instance" in request.POST else None, pools=pools, semester=semester, ) if add_instance_form.is_valid(): add_instance_form.save() return HttpResponseRedirect(wurl( "workshift:manage", sem_url=semester.sem_url, )) return render_to_response("add_shift.html", { "page_name": page_name, "add_type_form": add_type_form, "shifts_formset": shifts_formset, "add_instance_form": add_instance_form, }, context_instance=RequestContext(request))
python
def add_shift_view(request, semester): """ View for the workshift manager to create new types of workshifts. """ page_name = "Add Workshift" any_management = utils.can_manage(request.user, semester, any_pool=True) if not any_management: messages.add_message( request, messages.ERROR, MESSAGES["ADMINS_ONLY"], ) return HttpResponseRedirect(semester.get_view_url()) # Check what pools this person can manage pools = WorkshiftPool.objects.filter(semester=semester) full_management = utils.can_manage(request.user, semester=semester) if not full_management: pools = pools.filter(managers__incumbent__user=request.user) # Forms add_type_form = WorkshiftTypeForm( data=request.POST if "add_type" in request.POST else None, prefix="type", ) shifts_formset = RegularWorkshiftFormSet( data=request.POST if "add_type" in request.POST else None, prefix="shifts", queryset=RegularWorkshift.objects.none(), pools=pools, ) if add_type_form.is_valid() and shifts_formset.is_valid(): wtype = add_type_form.save() shifts_formset.save(workshift_type=wtype) return HttpResponseRedirect(wurl( "workshift:manage", sem_url=semester.sem_url, )) add_instance_form = WorkshiftInstanceForm( data=request.POST if "add_instance" in request.POST else None, pools=pools, semester=semester, ) if add_instance_form.is_valid(): add_instance_form.save() return HttpResponseRedirect(wurl( "workshift:manage", sem_url=semester.sem_url, )) return render_to_response("add_shift.html", { "page_name": page_name, "add_type_form": add_type_form, "shifts_formset": shifts_formset, "add_instance_form": add_instance_form, }, context_instance=RequestContext(request))
[ "def", "add_shift_view", "(", "request", ",", "semester", ")", ":", "page_name", "=", "\"Add Workshift\"", "any_management", "=", "utils", ".", "can_manage", "(", "request", ".", "user", ",", "semester", ",", "any_pool", "=", "True", ")", "if", "not", "any_management", ":", "messages", ".", "add_message", "(", "request", ",", "messages", ".", "ERROR", ",", "MESSAGES", "[", "\"ADMINS_ONLY\"", "]", ",", ")", "return", "HttpResponseRedirect", "(", "semester", ".", "get_view_url", "(", ")", ")", "# Check what pools this person can manage", "pools", "=", "WorkshiftPool", ".", "objects", ".", "filter", "(", "semester", "=", "semester", ")", "full_management", "=", "utils", ".", "can_manage", "(", "request", ".", "user", ",", "semester", "=", "semester", ")", "if", "not", "full_management", ":", "pools", "=", "pools", ".", "filter", "(", "managers__incumbent__user", "=", "request", ".", "user", ")", "# Forms", "add_type_form", "=", "WorkshiftTypeForm", "(", "data", "=", "request", ".", "POST", "if", "\"add_type\"", "in", "request", ".", "POST", "else", "None", ",", "prefix", "=", "\"type\"", ",", ")", "shifts_formset", "=", "RegularWorkshiftFormSet", "(", "data", "=", "request", ".", "POST", "if", "\"add_type\"", "in", "request", ".", "POST", "else", "None", ",", "prefix", "=", "\"shifts\"", ",", "queryset", "=", "RegularWorkshift", ".", "objects", ".", "none", "(", ")", ",", "pools", "=", "pools", ",", ")", "if", "add_type_form", ".", "is_valid", "(", ")", "and", "shifts_formset", ".", "is_valid", "(", ")", ":", "wtype", "=", "add_type_form", ".", "save", "(", ")", "shifts_formset", ".", "save", "(", "workshift_type", "=", "wtype", ")", "return", "HttpResponseRedirect", "(", "wurl", "(", "\"workshift:manage\"", ",", "sem_url", "=", "semester", ".", "sem_url", ",", ")", ")", "add_instance_form", "=", "WorkshiftInstanceForm", "(", "data", "=", "request", ".", "POST", "if", "\"add_instance\"", "in", "request", ".", "POST", "else", "None", ",", "pools", "=", "pools", ",", "semester", "=", "semester", ",", ")", "if", "add_instance_form", ".", "is_valid", "(", ")", ":", "add_instance_form", ".", "save", "(", ")", "return", "HttpResponseRedirect", "(", "wurl", "(", "\"workshift:manage\"", ",", "sem_url", "=", "semester", ".", "sem_url", ",", ")", ")", "return", "render_to_response", "(", "\"add_shift.html\"", ",", "{", "\"page_name\"", ":", "page_name", ",", "\"add_type_form\"", ":", "add_type_form", ",", "\"shifts_formset\"", ":", "shifts_formset", ",", "\"add_instance_form\"", ":", "add_instance_form", ",", "}", ",", "context_instance", "=", "RequestContext", "(", "request", ")", ")" ]
View for the workshift manager to create new types of workshifts.
[ "View", "for", "the", "workshift", "manager", "to", "create", "new", "types", "of", "workshifts", "." ]
1b6589f0d9fea154f0a1e2231ed906764ed26d26
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L1233-L1292
246,186
knagra/farnsworth
workshift/views.py
shift_view
def shift_view(request, semester, pk, profile=None): """ View the details of a particular RegularWorkshift. """ shift = get_object_or_404(RegularWorkshift, pk=pk) page_name = shift.workshift_type.title if shift.is_manager_shift: president = Manager.objects.filter( incumbent__user=request.user, president=True, ).count() > 0 can_edit = request.user.is_superuser or president else: can_edit = utils.can_manage( request.user, semester=semester, pool=shift.pool, ) instances = WorkshiftInstance.objects.filter( weekly_workshift=shift, date__gte=localtime(now()).date(), ) instance_tuples = [ ( instance, _get_forms(profile, instance, request, undo=can_edit), ) for instance in instances ] # Save any forms that were submitted all_forms = [form for instance, forms in instance_tuples for form in forms] for form in all_forms: if form.is_valid(): form.save() return HttpResponseRedirect(shift.get_view_url()) else: for error in form.errors.values(): messages.add_message(request, messages.ERROR, error) return render_to_response("view_shift.html", { "page_name": page_name, "shift": shift, "instance_tuples": instance_tuples, "can_edit": can_edit, }, context_instance=RequestContext(request))
python
def shift_view(request, semester, pk, profile=None): """ View the details of a particular RegularWorkshift. """ shift = get_object_or_404(RegularWorkshift, pk=pk) page_name = shift.workshift_type.title if shift.is_manager_shift: president = Manager.objects.filter( incumbent__user=request.user, president=True, ).count() > 0 can_edit = request.user.is_superuser or president else: can_edit = utils.can_manage( request.user, semester=semester, pool=shift.pool, ) instances = WorkshiftInstance.objects.filter( weekly_workshift=shift, date__gte=localtime(now()).date(), ) instance_tuples = [ ( instance, _get_forms(profile, instance, request, undo=can_edit), ) for instance in instances ] # Save any forms that were submitted all_forms = [form for instance, forms in instance_tuples for form in forms] for form in all_forms: if form.is_valid(): form.save() return HttpResponseRedirect(shift.get_view_url()) else: for error in form.errors.values(): messages.add_message(request, messages.ERROR, error) return render_to_response("view_shift.html", { "page_name": page_name, "shift": shift, "instance_tuples": instance_tuples, "can_edit": can_edit, }, context_instance=RequestContext(request))
[ "def", "shift_view", "(", "request", ",", "semester", ",", "pk", ",", "profile", "=", "None", ")", ":", "shift", "=", "get_object_or_404", "(", "RegularWorkshift", ",", "pk", "=", "pk", ")", "page_name", "=", "shift", ".", "workshift_type", ".", "title", "if", "shift", ".", "is_manager_shift", ":", "president", "=", "Manager", ".", "objects", ".", "filter", "(", "incumbent__user", "=", "request", ".", "user", ",", "president", "=", "True", ",", ")", ".", "count", "(", ")", ">", "0", "can_edit", "=", "request", ".", "user", ".", "is_superuser", "or", "president", "else", ":", "can_edit", "=", "utils", ".", "can_manage", "(", "request", ".", "user", ",", "semester", "=", "semester", ",", "pool", "=", "shift", ".", "pool", ",", ")", "instances", "=", "WorkshiftInstance", ".", "objects", ".", "filter", "(", "weekly_workshift", "=", "shift", ",", "date__gte", "=", "localtime", "(", "now", "(", ")", ")", ".", "date", "(", ")", ",", ")", "instance_tuples", "=", "[", "(", "instance", ",", "_get_forms", "(", "profile", ",", "instance", ",", "request", ",", "undo", "=", "can_edit", ")", ",", ")", "for", "instance", "in", "instances", "]", "# Save any forms that were submitted", "all_forms", "=", "[", "form", "for", "instance", ",", "forms", "in", "instance_tuples", "for", "form", "in", "forms", "]", "for", "form", "in", "all_forms", ":", "if", "form", ".", "is_valid", "(", ")", ":", "form", ".", "save", "(", ")", "return", "HttpResponseRedirect", "(", "shift", ".", "get_view_url", "(", ")", ")", "else", ":", "for", "error", "in", "form", ".", "errors", ".", "values", "(", ")", ":", "messages", ".", "add_message", "(", "request", ",", "messages", ".", "ERROR", ",", "error", ")", "return", "render_to_response", "(", "\"view_shift.html\"", ",", "{", "\"page_name\"", ":", "page_name", ",", "\"shift\"", ":", "shift", ",", "\"instance_tuples\"", ":", "instance_tuples", ",", "\"can_edit\"", ":", "can_edit", ",", "}", ",", "context_instance", "=", "RequestContext", "(", "request", ")", ")" ]
View the details of a particular RegularWorkshift.
[ "View", "the", "details", "of", "a", "particular", "RegularWorkshift", "." ]
1b6589f0d9fea154f0a1e2231ed906764ed26d26
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L1440-L1487
246,187
knagra/farnsworth
workshift/views.py
edit_shift_view
def edit_shift_view(request, semester, pk, profile=None): """ View for a manager to edit the details of a particular RegularWorkshift. """ shift = get_object_or_404(RegularWorkshift, pk=pk) if shift.is_manager_shift: # XXX: Bad way of doing this, we should make manager_shift point to # the related Manager object directly try: manager = Manager.objects.get(title=shift.workshift_type.title) except Manager.DoesNotExist: pass else: return HttpResponseRedirect(manager.get_edit_url()) if not utils.can_manage(request.user, semester=semester, pool=shift.pool): messages.add_message( request, messages.ERROR, MESSAGES["ADMINS_ONLY"], ) return HttpResponseRedirect(semester.get_view_url()) edit_form = RegularWorkshiftForm( data=request.POST if "edit" in request.POST else None, instance=shift, semester=semester, ) if "delete" in request.POST: # Open instances are deleted automatically shift.delete() return HttpResponseRedirect(wurl( "workshift:manage", sem_url=semester.sem_url, )) elif edit_form.is_valid(): shift = edit_form.save() return HttpResponseRedirect(shift.get_view_url()) page_name = "Edit {}".format(shift) return render_to_response("edit_shift.html", { "page_name": page_name, "shift": shift, "edit_form": edit_form, }, context_instance=RequestContext(request))
python
def edit_shift_view(request, semester, pk, profile=None): """ View for a manager to edit the details of a particular RegularWorkshift. """ shift = get_object_or_404(RegularWorkshift, pk=pk) if shift.is_manager_shift: # XXX: Bad way of doing this, we should make manager_shift point to # the related Manager object directly try: manager = Manager.objects.get(title=shift.workshift_type.title) except Manager.DoesNotExist: pass else: return HttpResponseRedirect(manager.get_edit_url()) if not utils.can_manage(request.user, semester=semester, pool=shift.pool): messages.add_message( request, messages.ERROR, MESSAGES["ADMINS_ONLY"], ) return HttpResponseRedirect(semester.get_view_url()) edit_form = RegularWorkshiftForm( data=request.POST if "edit" in request.POST else None, instance=shift, semester=semester, ) if "delete" in request.POST: # Open instances are deleted automatically shift.delete() return HttpResponseRedirect(wurl( "workshift:manage", sem_url=semester.sem_url, )) elif edit_form.is_valid(): shift = edit_form.save() return HttpResponseRedirect(shift.get_view_url()) page_name = "Edit {}".format(shift) return render_to_response("edit_shift.html", { "page_name": page_name, "shift": shift, "edit_form": edit_form, }, context_instance=RequestContext(request))
[ "def", "edit_shift_view", "(", "request", ",", "semester", ",", "pk", ",", "profile", "=", "None", ")", ":", "shift", "=", "get_object_or_404", "(", "RegularWorkshift", ",", "pk", "=", "pk", ")", "if", "shift", ".", "is_manager_shift", ":", "# XXX: Bad way of doing this, we should make manager_shift point to", "# the related Manager object directly", "try", ":", "manager", "=", "Manager", ".", "objects", ".", "get", "(", "title", "=", "shift", ".", "workshift_type", ".", "title", ")", "except", "Manager", ".", "DoesNotExist", ":", "pass", "else", ":", "return", "HttpResponseRedirect", "(", "manager", ".", "get_edit_url", "(", ")", ")", "if", "not", "utils", ".", "can_manage", "(", "request", ".", "user", ",", "semester", "=", "semester", ",", "pool", "=", "shift", ".", "pool", ")", ":", "messages", ".", "add_message", "(", "request", ",", "messages", ".", "ERROR", ",", "MESSAGES", "[", "\"ADMINS_ONLY\"", "]", ",", ")", "return", "HttpResponseRedirect", "(", "semester", ".", "get_view_url", "(", ")", ")", "edit_form", "=", "RegularWorkshiftForm", "(", "data", "=", "request", ".", "POST", "if", "\"edit\"", "in", "request", ".", "POST", "else", "None", ",", "instance", "=", "shift", ",", "semester", "=", "semester", ",", ")", "if", "\"delete\"", "in", "request", ".", "POST", ":", "# Open instances are deleted automatically", "shift", ".", "delete", "(", ")", "return", "HttpResponseRedirect", "(", "wurl", "(", "\"workshift:manage\"", ",", "sem_url", "=", "semester", ".", "sem_url", ",", ")", ")", "elif", "edit_form", ".", "is_valid", "(", ")", ":", "shift", "=", "edit_form", ".", "save", "(", ")", "return", "HttpResponseRedirect", "(", "shift", ".", "get_view_url", "(", ")", ")", "page_name", "=", "\"Edit {}\"", ".", "format", "(", "shift", ")", "return", "render_to_response", "(", "\"edit_shift.html\"", ",", "{", "\"page_name\"", ":", "page_name", ",", "\"shift\"", ":", "shift", ",", "\"edit_form\"", ":", "edit_form", ",", "}", ",", "context_instance", "=", "RequestContext", "(", "request", ")", ")" ]
View for a manager to edit the details of a particular RegularWorkshift.
[ "View", "for", "a", "manager", "to", "edit", "the", "details", "of", "a", "particular", "RegularWorkshift", "." ]
1b6589f0d9fea154f0a1e2231ed906764ed26d26
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L1491-L1538
246,188
knagra/farnsworth
workshift/views.py
instance_view
def instance_view(request, semester, pk, profile=None): """ View the details of a particular WorkshiftInstance. """ instance = get_object_or_404(WorkshiftInstance, pk=pk) page_name = instance.title management = utils.can_manage( request.user, semester=semester, pool=instance.pool, ) interact_forms = _get_forms( profile, instance, request, undo=management, prefix="interact", ) note_form = NoteForm( data=request.POST or None, prefix="note", ) # Save any forms that were submitted if note_form.is_valid(): for form in interact_forms: if form.is_valid(): note = note_form.save() form.save(note=note) return HttpResponseRedirect(instance.get_view_url()) else: for error in form.errors.values(): messages.add_message(request, messages.ERROR, error) edit_hours_form = None if instance.weekly_workshift and instance.weekly_workshift.is_manager_shift: president = Manager.objects.filter( incumbent__user=request.user, president=True ).count() > 0 can_edit = request.user.is_superuser or president else: can_edit = utils.can_manage( request.user, semester=instance.pool.semester, pool=instance.pool, ) if can_edit: edit_hours_form = EditHoursForm( data=request.POST if "edit_hours" in request.POST else None, instance=instance, profile=profile, ) if edit_hours_form.is_valid(): edit_hours_form.save() messages.add_message( request, messages.INFO, "Updated instance's hours.", ) return HttpResponseRedirect(instance.get_view_url()) return render_to_response("view_instance.html", { "page_name": page_name, "can_edit": can_edit, "instance": instance, "interact_forms": interact_forms, "note_form": note_form, "edit_hours_form": edit_hours_form, }, context_instance=RequestContext(request))
python
def instance_view(request, semester, pk, profile=None): """ View the details of a particular WorkshiftInstance. """ instance = get_object_or_404(WorkshiftInstance, pk=pk) page_name = instance.title management = utils.can_manage( request.user, semester=semester, pool=instance.pool, ) interact_forms = _get_forms( profile, instance, request, undo=management, prefix="interact", ) note_form = NoteForm( data=request.POST or None, prefix="note", ) # Save any forms that were submitted if note_form.is_valid(): for form in interact_forms: if form.is_valid(): note = note_form.save() form.save(note=note) return HttpResponseRedirect(instance.get_view_url()) else: for error in form.errors.values(): messages.add_message(request, messages.ERROR, error) edit_hours_form = None if instance.weekly_workshift and instance.weekly_workshift.is_manager_shift: president = Manager.objects.filter( incumbent__user=request.user, president=True ).count() > 0 can_edit = request.user.is_superuser or president else: can_edit = utils.can_manage( request.user, semester=instance.pool.semester, pool=instance.pool, ) if can_edit: edit_hours_form = EditHoursForm( data=request.POST if "edit_hours" in request.POST else None, instance=instance, profile=profile, ) if edit_hours_form.is_valid(): edit_hours_form.save() messages.add_message( request, messages.INFO, "Updated instance's hours.", ) return HttpResponseRedirect(instance.get_view_url()) return render_to_response("view_instance.html", { "page_name": page_name, "can_edit": can_edit, "instance": instance, "interact_forms": interact_forms, "note_form": note_form, "edit_hours_form": edit_hours_form, }, context_instance=RequestContext(request))
[ "def", "instance_view", "(", "request", ",", "semester", ",", "pk", ",", "profile", "=", "None", ")", ":", "instance", "=", "get_object_or_404", "(", "WorkshiftInstance", ",", "pk", "=", "pk", ")", "page_name", "=", "instance", ".", "title", "management", "=", "utils", ".", "can_manage", "(", "request", ".", "user", ",", "semester", "=", "semester", ",", "pool", "=", "instance", ".", "pool", ",", ")", "interact_forms", "=", "_get_forms", "(", "profile", ",", "instance", ",", "request", ",", "undo", "=", "management", ",", "prefix", "=", "\"interact\"", ",", ")", "note_form", "=", "NoteForm", "(", "data", "=", "request", ".", "POST", "or", "None", ",", "prefix", "=", "\"note\"", ",", ")", "# Save any forms that were submitted", "if", "note_form", ".", "is_valid", "(", ")", ":", "for", "form", "in", "interact_forms", ":", "if", "form", ".", "is_valid", "(", ")", ":", "note", "=", "note_form", ".", "save", "(", ")", "form", ".", "save", "(", "note", "=", "note", ")", "return", "HttpResponseRedirect", "(", "instance", ".", "get_view_url", "(", ")", ")", "else", ":", "for", "error", "in", "form", ".", "errors", ".", "values", "(", ")", ":", "messages", ".", "add_message", "(", "request", ",", "messages", ".", "ERROR", ",", "error", ")", "edit_hours_form", "=", "None", "if", "instance", ".", "weekly_workshift", "and", "instance", ".", "weekly_workshift", ".", "is_manager_shift", ":", "president", "=", "Manager", ".", "objects", ".", "filter", "(", "incumbent__user", "=", "request", ".", "user", ",", "president", "=", "True", ")", ".", "count", "(", ")", ">", "0", "can_edit", "=", "request", ".", "user", ".", "is_superuser", "or", "president", "else", ":", "can_edit", "=", "utils", ".", "can_manage", "(", "request", ".", "user", ",", "semester", "=", "instance", ".", "pool", ".", "semester", ",", "pool", "=", "instance", ".", "pool", ",", ")", "if", "can_edit", ":", "edit_hours_form", "=", "EditHoursForm", "(", "data", "=", "request", ".", "POST", "if", "\"edit_hours\"", "in", "request", ".", "POST", "else", "None", ",", "instance", "=", "instance", ",", "profile", "=", "profile", ",", ")", "if", "edit_hours_form", ".", "is_valid", "(", ")", ":", "edit_hours_form", ".", "save", "(", ")", "messages", ".", "add_message", "(", "request", ",", "messages", ".", "INFO", ",", "\"Updated instance's hours.\"", ",", ")", "return", "HttpResponseRedirect", "(", "instance", ".", "get_view_url", "(", ")", ")", "return", "render_to_response", "(", "\"view_instance.html\"", ",", "{", "\"page_name\"", ":", "page_name", ",", "\"can_edit\"", ":", "can_edit", ",", "\"instance\"", ":", "instance", ",", "\"interact_forms\"", ":", "interact_forms", ",", "\"note_form\"", ":", "note_form", ",", "\"edit_hours_form\"", ":", "edit_hours_form", ",", "}", ",", "context_instance", "=", "RequestContext", "(", "request", ")", ")" ]
View the details of a particular WorkshiftInstance.
[ "View", "the", "details", "of", "a", "particular", "WorkshiftInstance", "." ]
1b6589f0d9fea154f0a1e2231ed906764ed26d26
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L1542-L1609
246,189
knagra/farnsworth
workshift/views.py
edit_instance_view
def edit_instance_view(request, semester, pk, profile=None): """ View for a manager to edit the details of a particular WorkshiftInstance. """ instance = get_object_or_404(WorkshiftInstance, pk=pk) if instance.weekly_workshift and instance.weekly_workshift.is_manager_shift: president = Manager.objects.filter( incumbent__user=request.user, president=True ).count() > 0 can_edit = request.user.is_superuser or president message = MESSAGES["PRESIDENTS_ONLY"] else: can_edit = utils.can_manage( request.user, semester=semester, pool=instance.pool, ) message = MESSAGES["ADMINS_ONLY"] if not can_edit: messages.add_message(request, messages.ERROR, message) return HttpResponseRedirect(semester.get_view_url()) page_name = "Edit " + instance.title edit_form = WorkshiftInstanceForm( data=request.POST if "edit" in request.POST else None, instance=instance, semester=semester, edit_hours=False, ) if "delete" in request.POST: instance.delete() return HttpResponseRedirect(wurl( "workshift:manage", sem_url=semester.sem_url, )) elif edit_form.is_valid(): instance = edit_form.save() return HttpResponseRedirect(instance.get_view_url()) return render_to_response("edit_instance.html", { "page_name": page_name, "instance": instance, "edit_form": edit_form, }, context_instance=RequestContext(request))
python
def edit_instance_view(request, semester, pk, profile=None): """ View for a manager to edit the details of a particular WorkshiftInstance. """ instance = get_object_or_404(WorkshiftInstance, pk=pk) if instance.weekly_workshift and instance.weekly_workshift.is_manager_shift: president = Manager.objects.filter( incumbent__user=request.user, president=True ).count() > 0 can_edit = request.user.is_superuser or president message = MESSAGES["PRESIDENTS_ONLY"] else: can_edit = utils.can_manage( request.user, semester=semester, pool=instance.pool, ) message = MESSAGES["ADMINS_ONLY"] if not can_edit: messages.add_message(request, messages.ERROR, message) return HttpResponseRedirect(semester.get_view_url()) page_name = "Edit " + instance.title edit_form = WorkshiftInstanceForm( data=request.POST if "edit" in request.POST else None, instance=instance, semester=semester, edit_hours=False, ) if "delete" in request.POST: instance.delete() return HttpResponseRedirect(wurl( "workshift:manage", sem_url=semester.sem_url, )) elif edit_form.is_valid(): instance = edit_form.save() return HttpResponseRedirect(instance.get_view_url()) return render_to_response("edit_instance.html", { "page_name": page_name, "instance": instance, "edit_form": edit_form, }, context_instance=RequestContext(request))
[ "def", "edit_instance_view", "(", "request", ",", "semester", ",", "pk", ",", "profile", "=", "None", ")", ":", "instance", "=", "get_object_or_404", "(", "WorkshiftInstance", ",", "pk", "=", "pk", ")", "if", "instance", ".", "weekly_workshift", "and", "instance", ".", "weekly_workshift", ".", "is_manager_shift", ":", "president", "=", "Manager", ".", "objects", ".", "filter", "(", "incumbent__user", "=", "request", ".", "user", ",", "president", "=", "True", ")", ".", "count", "(", ")", ">", "0", "can_edit", "=", "request", ".", "user", ".", "is_superuser", "or", "president", "message", "=", "MESSAGES", "[", "\"PRESIDENTS_ONLY\"", "]", "else", ":", "can_edit", "=", "utils", ".", "can_manage", "(", "request", ".", "user", ",", "semester", "=", "semester", ",", "pool", "=", "instance", ".", "pool", ",", ")", "message", "=", "MESSAGES", "[", "\"ADMINS_ONLY\"", "]", "if", "not", "can_edit", ":", "messages", ".", "add_message", "(", "request", ",", "messages", ".", "ERROR", ",", "message", ")", "return", "HttpResponseRedirect", "(", "semester", ".", "get_view_url", "(", ")", ")", "page_name", "=", "\"Edit \"", "+", "instance", ".", "title", "edit_form", "=", "WorkshiftInstanceForm", "(", "data", "=", "request", ".", "POST", "if", "\"edit\"", "in", "request", ".", "POST", "else", "None", ",", "instance", "=", "instance", ",", "semester", "=", "semester", ",", "edit_hours", "=", "False", ",", ")", "if", "\"delete\"", "in", "request", ".", "POST", ":", "instance", ".", "delete", "(", ")", "return", "HttpResponseRedirect", "(", "wurl", "(", "\"workshift:manage\"", ",", "sem_url", "=", "semester", ".", "sem_url", ",", ")", ")", "elif", "edit_form", ".", "is_valid", "(", ")", ":", "instance", "=", "edit_form", ".", "save", "(", ")", "return", "HttpResponseRedirect", "(", "instance", ".", "get_view_url", "(", ")", ")", "return", "render_to_response", "(", "\"edit_instance.html\"", ",", "{", "\"page_name\"", ":", "page_name", ",", "\"instance\"", ":", "instance", ",", "\"edit_form\"", ":", "edit_form", ",", "}", ",", "context_instance", "=", "RequestContext", "(", "request", ")", ")" ]
View for a manager to edit the details of a particular WorkshiftInstance.
[ "View", "for", "a", "manager", "to", "edit", "the", "details", "of", "a", "particular", "WorkshiftInstance", "." ]
1b6589f0d9fea154f0a1e2231ed906764ed26d26
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L1613-L1659
246,190
knagra/farnsworth
workshift/views.py
edit_type_view
def edit_type_view(request, semester, pk, profile=None): """ View for a manager to edit the details of a particular WorkshiftType. """ wtype = get_object_or_404(WorkshiftType, pk=pk) full_management = utils.can_manage(request.user, semester) any_management = utils.can_manage(request.user, semester, any_pool=True) if not any_management: messages.add_message( request, messages.ERROR, MESSAGES["ADMINS_ONLY"], ) return HttpResponseRedirect(semester.get_view_url()) if full_management: if "delete" in request.POST: messages.add_message( request, messages.INFO, "Workshift type deleted.", ) wtype.delete() return HttpResponseRedirect(wurl( "workshift:list_types", sem_url=semester.sem_url, )) edit_form = WorkshiftTypeForm( data=request.POST if "edit" in request.POST else None, instance=wtype, prefix="edit", read_only=not full_management, ) queryset = RegularWorkshift.objects.filter( workshift_type=wtype, ) if not full_management: queryset = queryset.filter( pool__managers__incumbent__user=request.user, ) shifts_formset = RegularWorkshiftFormSet( data=request.POST if "edit" in request.POST else None, prefix="shifts", queryset=queryset, ) if edit_form.is_valid() and shifts_formset.is_valid(): if full_management: wtype = edit_form.save() shifts_formset.save(wtype) return HttpResponseRedirect(wtype.get_view_url()) page_name = "Edit {}".format(wtype.title) return render_to_response("edit_type.html", { "page_name": page_name, "shift": wtype, "edit_form": edit_form, "shifts_formset": shifts_formset, }, context_instance=RequestContext(request))
python
def edit_type_view(request, semester, pk, profile=None): """ View for a manager to edit the details of a particular WorkshiftType. """ wtype = get_object_or_404(WorkshiftType, pk=pk) full_management = utils.can_manage(request.user, semester) any_management = utils.can_manage(request.user, semester, any_pool=True) if not any_management: messages.add_message( request, messages.ERROR, MESSAGES["ADMINS_ONLY"], ) return HttpResponseRedirect(semester.get_view_url()) if full_management: if "delete" in request.POST: messages.add_message( request, messages.INFO, "Workshift type deleted.", ) wtype.delete() return HttpResponseRedirect(wurl( "workshift:list_types", sem_url=semester.sem_url, )) edit_form = WorkshiftTypeForm( data=request.POST if "edit" in request.POST else None, instance=wtype, prefix="edit", read_only=not full_management, ) queryset = RegularWorkshift.objects.filter( workshift_type=wtype, ) if not full_management: queryset = queryset.filter( pool__managers__incumbent__user=request.user, ) shifts_formset = RegularWorkshiftFormSet( data=request.POST if "edit" in request.POST else None, prefix="shifts", queryset=queryset, ) if edit_form.is_valid() and shifts_formset.is_valid(): if full_management: wtype = edit_form.save() shifts_formset.save(wtype) return HttpResponseRedirect(wtype.get_view_url()) page_name = "Edit {}".format(wtype.title) return render_to_response("edit_type.html", { "page_name": page_name, "shift": wtype, "edit_form": edit_form, "shifts_formset": shifts_formset, }, context_instance=RequestContext(request))
[ "def", "edit_type_view", "(", "request", ",", "semester", ",", "pk", ",", "profile", "=", "None", ")", ":", "wtype", "=", "get_object_or_404", "(", "WorkshiftType", ",", "pk", "=", "pk", ")", "full_management", "=", "utils", ".", "can_manage", "(", "request", ".", "user", ",", "semester", ")", "any_management", "=", "utils", ".", "can_manage", "(", "request", ".", "user", ",", "semester", ",", "any_pool", "=", "True", ")", "if", "not", "any_management", ":", "messages", ".", "add_message", "(", "request", ",", "messages", ".", "ERROR", ",", "MESSAGES", "[", "\"ADMINS_ONLY\"", "]", ",", ")", "return", "HttpResponseRedirect", "(", "semester", ".", "get_view_url", "(", ")", ")", "if", "full_management", ":", "if", "\"delete\"", "in", "request", ".", "POST", ":", "messages", ".", "add_message", "(", "request", ",", "messages", ".", "INFO", ",", "\"Workshift type deleted.\"", ",", ")", "wtype", ".", "delete", "(", ")", "return", "HttpResponseRedirect", "(", "wurl", "(", "\"workshift:list_types\"", ",", "sem_url", "=", "semester", ".", "sem_url", ",", ")", ")", "edit_form", "=", "WorkshiftTypeForm", "(", "data", "=", "request", ".", "POST", "if", "\"edit\"", "in", "request", ".", "POST", "else", "None", ",", "instance", "=", "wtype", ",", "prefix", "=", "\"edit\"", ",", "read_only", "=", "not", "full_management", ",", ")", "queryset", "=", "RegularWorkshift", ".", "objects", ".", "filter", "(", "workshift_type", "=", "wtype", ",", ")", "if", "not", "full_management", ":", "queryset", "=", "queryset", ".", "filter", "(", "pool__managers__incumbent__user", "=", "request", ".", "user", ",", ")", "shifts_formset", "=", "RegularWorkshiftFormSet", "(", "data", "=", "request", ".", "POST", "if", "\"edit\"", "in", "request", ".", "POST", "else", "None", ",", "prefix", "=", "\"shifts\"", ",", "queryset", "=", "queryset", ",", ")", "if", "edit_form", ".", "is_valid", "(", ")", "and", "shifts_formset", ".", "is_valid", "(", ")", ":", "if", "full_management", ":", "wtype", "=", "edit_form", ".", "save", "(", ")", "shifts_formset", ".", "save", "(", "wtype", ")", "return", "HttpResponseRedirect", "(", "wtype", ".", "get_view_url", "(", ")", ")", "page_name", "=", "\"Edit {}\"", ".", "format", "(", "wtype", ".", "title", ")", "return", "render_to_response", "(", "\"edit_type.html\"", ",", "{", "\"page_name\"", ":", "page_name", ",", "\"shift\"", ":", "wtype", ",", "\"edit_form\"", ":", "edit_form", ",", "\"shifts_formset\"", ":", "shifts_formset", ",", "}", ",", "context_instance", "=", "RequestContext", "(", "request", ")", ")" ]
View for a manager to edit the details of a particular WorkshiftType.
[ "View", "for", "a", "manager", "to", "edit", "the", "details", "of", "a", "particular", "WorkshiftType", "." ]
1b6589f0d9fea154f0a1e2231ed906764ed26d26
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L1719-L1783
246,191
xtrementl/focus
focus/environment/__init__.py
_import_modules
def _import_modules(dir_path): """ Attempts to import modules in the specified directory path. `dir_path` Base directory path to attempt to import modules. """ def _import_module(module): """ Imports the specified module. """ # already loaded, skip if module in mods_loaded: return False __import__(module) mods_loaded.append(module) mods_loaded = [] # check if provided path exists if not os.path.isdir(dir_path): return try: # update import search path sys.path.insert(0, dir_path) # check for modules in the dir path for entry in os.listdir(dir_path): path = os.path.join(dir_path, entry) if os.path.isdir(path): # directory _import_module(entry) elif _RE_PY_EXT.search(entry): # python file if not _RE_INIT_PY.match(entry): # exclude init name = _RE_PY_EXT.sub('', entry) _import_module(name) finally: # remove inserted path sys.path.pop(0)
python
def _import_modules(dir_path): """ Attempts to import modules in the specified directory path. `dir_path` Base directory path to attempt to import modules. """ def _import_module(module): """ Imports the specified module. """ # already loaded, skip if module in mods_loaded: return False __import__(module) mods_loaded.append(module) mods_loaded = [] # check if provided path exists if not os.path.isdir(dir_path): return try: # update import search path sys.path.insert(0, dir_path) # check for modules in the dir path for entry in os.listdir(dir_path): path = os.path.join(dir_path, entry) if os.path.isdir(path): # directory _import_module(entry) elif _RE_PY_EXT.search(entry): # python file if not _RE_INIT_PY.match(entry): # exclude init name = _RE_PY_EXT.sub('', entry) _import_module(name) finally: # remove inserted path sys.path.pop(0)
[ "def", "_import_modules", "(", "dir_path", ")", ":", "def", "_import_module", "(", "module", ")", ":", "\"\"\" Imports the specified module.\n \"\"\"", "# already loaded, skip", "if", "module", "in", "mods_loaded", ":", "return", "False", "__import__", "(", "module", ")", "mods_loaded", ".", "append", "(", "module", ")", "mods_loaded", "=", "[", "]", "# check if provided path exists", "if", "not", "os", ".", "path", ".", "isdir", "(", "dir_path", ")", ":", "return", "try", ":", "# update import search path", "sys", ".", "path", ".", "insert", "(", "0", ",", "dir_path", ")", "# check for modules in the dir path", "for", "entry", "in", "os", ".", "listdir", "(", "dir_path", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "dir_path", ",", "entry", ")", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "# directory", "_import_module", "(", "entry", ")", "elif", "_RE_PY_EXT", ".", "search", "(", "entry", ")", ":", "# python file", "if", "not", "_RE_INIT_PY", ".", "match", "(", "entry", ")", ":", "# exclude init", "name", "=", "_RE_PY_EXT", ".", "sub", "(", "''", ",", "entry", ")", "_import_module", "(", "name", ")", "finally", ":", "# remove inserted path", "sys", ".", "path", ".", "pop", "(", "0", ")" ]
Attempts to import modules in the specified directory path. `dir_path` Base directory path to attempt to import modules.
[ "Attempts", "to", "import", "modules", "in", "the", "specified", "directory", "path", "." ]
cbbbc0b49a7409f9e0dc899de5b7e057f50838e4
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/environment/__init__.py#L22-L62
246,192
xtrementl/focus
focus/environment/__init__.py
Environment._setup_directories
def _setup_directories(self): """ Creates data directory structure. * Raises a ``DirectorySetupFail`` exception if error occurs while creating directories. """ dirs = [self._data_dir] dirs += [os.path.join(self._data_dir, name) for name in self.DATA_SUBDIRS] for path in dirs: if not os.path.isdir(path): try: os.makedirs(path) # recursive mkdir os.chmod(path, 0755) # rwxr-xr-x except OSError: raise errors.DirectorySetupFail() return True
python
def _setup_directories(self): """ Creates data directory structure. * Raises a ``DirectorySetupFail`` exception if error occurs while creating directories. """ dirs = [self._data_dir] dirs += [os.path.join(self._data_dir, name) for name in self.DATA_SUBDIRS] for path in dirs: if not os.path.isdir(path): try: os.makedirs(path) # recursive mkdir os.chmod(path, 0755) # rwxr-xr-x except OSError: raise errors.DirectorySetupFail() return True
[ "def", "_setup_directories", "(", "self", ")", ":", "dirs", "=", "[", "self", ".", "_data_dir", "]", "dirs", "+=", "[", "os", ".", "path", ".", "join", "(", "self", ".", "_data_dir", ",", "name", ")", "for", "name", "in", "self", ".", "DATA_SUBDIRS", "]", "for", "path", "in", "dirs", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "try", ":", "os", ".", "makedirs", "(", "path", ")", "# recursive mkdir", "os", ".", "chmod", "(", "path", ",", "0755", ")", "# rwxr-xr-x", "except", "OSError", ":", "raise", "errors", ".", "DirectorySetupFail", "(", ")", "return", "True" ]
Creates data directory structure. * Raises a ``DirectorySetupFail`` exception if error occurs while creating directories.
[ "Creates", "data", "directory", "structure", "." ]
cbbbc0b49a7409f9e0dc899de5b7e057f50838e4
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/environment/__init__.py#L104-L123
246,193
xtrementl/focus
focus/environment/__init__.py
Environment._setup_task
def _setup_task(self, load): """ Sets up the ``Task`` object and loads active file for task. `load` Set to ``True`` to load task after setup. """ if not self._task: self._task = Task(self._data_dir) if load: self._task.load()
python
def _setup_task(self, load): """ Sets up the ``Task`` object and loads active file for task. `load` Set to ``True`` to load task after setup. """ if not self._task: self._task = Task(self._data_dir) if load: self._task.load()
[ "def", "_setup_task", "(", "self", ",", "load", ")", ":", "if", "not", "self", ".", "_task", ":", "self", ".", "_task", "=", "Task", "(", "self", ".", "_data_dir", ")", "if", "load", ":", "self", ".", "_task", ".", "load", "(", ")" ]
Sets up the ``Task`` object and loads active file for task. `load` Set to ``True`` to load task after setup.
[ "Sets", "up", "the", "Task", "object", "and", "loads", "active", "file", "for", "task", "." ]
cbbbc0b49a7409f9e0dc899de5b7e057f50838e4
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/environment/__init__.py#L125-L136
246,194
xtrementl/focus
focus/environment/__init__.py
Environment._load_plugins
def _load_plugins(self): """ Attempts to load plugin modules according to the order of available plugin directories. """ # import base plugin modules try: __import__('focus.plugin.modules') #import focus.plugin.modules except ImportError as exc: raise errors.PluginImport(unicode(exc)) # load user defined plugin modules try: user_plugin_dir = os.path.join(self._data_dir, 'plugins') _import_modules(user_plugin_dir) except Exception as exc: raise errors.UserPluginImport(unicode(exc))
python
def _load_plugins(self): """ Attempts to load plugin modules according to the order of available plugin directories. """ # import base plugin modules try: __import__('focus.plugin.modules') #import focus.plugin.modules except ImportError as exc: raise errors.PluginImport(unicode(exc)) # load user defined plugin modules try: user_plugin_dir = os.path.join(self._data_dir, 'plugins') _import_modules(user_plugin_dir) except Exception as exc: raise errors.UserPluginImport(unicode(exc))
[ "def", "_load_plugins", "(", "self", ")", ":", "# import base plugin modules", "try", ":", "__import__", "(", "'focus.plugin.modules'", ")", "#import focus.plugin.modules", "except", "ImportError", "as", "exc", ":", "raise", "errors", ".", "PluginImport", "(", "unicode", "(", "exc", ")", ")", "# load user defined plugin modules", "try", ":", "user_plugin_dir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_data_dir", ",", "'plugins'", ")", "_import_modules", "(", "user_plugin_dir", ")", "except", "Exception", "as", "exc", ":", "raise", "errors", ".", "UserPluginImport", "(", "unicode", "(", "exc", ")", ")" ]
Attempts to load plugin modules according to the order of available plugin directories.
[ "Attempts", "to", "load", "plugin", "modules", "according", "to", "the", "order", "of", "available", "plugin", "directories", "." ]
cbbbc0b49a7409f9e0dc899de5b7e057f50838e4
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/environment/__init__.py#L138-L156
246,195
xtrementl/focus
focus/environment/__init__.py
Environment.load
def load(self): """ Loads in resources needed for this environment, including loading a new or existing task, establishing directory structures, and importing plugin modules. """ self._setup_directories() self._load_plugins() self._setup_task(load=True) self._loaded = True
python
def load(self): """ Loads in resources needed for this environment, including loading a new or existing task, establishing directory structures, and importing plugin modules. """ self._setup_directories() self._load_plugins() self._setup_task(load=True) self._loaded = True
[ "def", "load", "(", "self", ")", ":", "self", ".", "_setup_directories", "(", ")", "self", ".", "_load_plugins", "(", ")", "self", ".", "_setup_task", "(", "load", "=", "True", ")", "self", ".", "_loaded", "=", "True" ]
Loads in resources needed for this environment, including loading a new or existing task, establishing directory structures, and importing plugin modules.
[ "Loads", "in", "resources", "needed", "for", "this", "environment", "including", "loading", "a", "new", "or", "existing", "task", "establishing", "directory", "structures", "and", "importing", "plugin", "modules", "." ]
cbbbc0b49a7409f9e0dc899de5b7e057f50838e4
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/environment/__init__.py#L158-L167
246,196
zakdoek/django-simple-resizer
simple_resizer/templatetags/simple_resizer.py
resize
def resize(image, width=None, height=None, crop=False, namespace="resized"): """ Returns the url of the resized image """ return resize_lazy(image=image, width=width, height=height, crop=crop, namespace=namespace, as_url=True)
python
def resize(image, width=None, height=None, crop=False, namespace="resized"): """ Returns the url of the resized image """ return resize_lazy(image=image, width=width, height=height, crop=crop, namespace=namespace, as_url=True)
[ "def", "resize", "(", "image", ",", "width", "=", "None", ",", "height", "=", "None", ",", "crop", "=", "False", ",", "namespace", "=", "\"resized\"", ")", ":", "return", "resize_lazy", "(", "image", "=", "image", ",", "width", "=", "width", ",", "height", "=", "height", ",", "crop", "=", "crop", ",", "namespace", "=", "namespace", ",", "as_url", "=", "True", ")" ]
Returns the url of the resized image
[ "Returns", "the", "url", "of", "the", "resized", "image" ]
5614eb1717948c65d179c3d1567439a8c90a4d44
https://github.com/zakdoek/django-simple-resizer/blob/5614eb1717948c65d179c3d1567439a8c90a4d44/simple_resizer/templatetags/simple_resizer.py#L13-L18
246,197
zakdoek/django-simple-resizer
simple_resizer/templatetags/simple_resizer.py
conditional_resize
def conditional_resize(image, ratio, width=None, height=None, upcrop=True, namespace="resized"): """ Crop the image based on a ratio If upcrop is true, crops the images that have a higher ratio than the given ratio, if false crops the images that have a lower ratio """ aspect = float(image.width) / float(image.height) crop = False if (aspect > ratio and upcrop) or (aspect <= ratio and not upcrop): crop = True return resize_lazy(image=image, width=width, height=height, crop=crop, namespace=namespace, as_url=True)
python
def conditional_resize(image, ratio, width=None, height=None, upcrop=True, namespace="resized"): """ Crop the image based on a ratio If upcrop is true, crops the images that have a higher ratio than the given ratio, if false crops the images that have a lower ratio """ aspect = float(image.width) / float(image.height) crop = False if (aspect > ratio and upcrop) or (aspect <= ratio and not upcrop): crop = True return resize_lazy(image=image, width=width, height=height, crop=crop, namespace=namespace, as_url=True)
[ "def", "conditional_resize", "(", "image", ",", "ratio", ",", "width", "=", "None", ",", "height", "=", "None", ",", "upcrop", "=", "True", ",", "namespace", "=", "\"resized\"", ")", ":", "aspect", "=", "float", "(", "image", ".", "width", ")", "/", "float", "(", "image", ".", "height", ")", "crop", "=", "False", "if", "(", "aspect", ">", "ratio", "and", "upcrop", ")", "or", "(", "aspect", "<=", "ratio", "and", "not", "upcrop", ")", ":", "crop", "=", "True", "return", "resize_lazy", "(", "image", "=", "image", ",", "width", "=", "width", ",", "height", "=", "height", ",", "crop", "=", "crop", ",", "namespace", "=", "namespace", ",", "as_url", "=", "True", ")" ]
Crop the image based on a ratio If upcrop is true, crops the images that have a higher ratio than the given ratio, if false crops the images that have a lower ratio
[ "Crop", "the", "image", "based", "on", "a", "ratio" ]
5614eb1717948c65d179c3d1567439a8c90a4d44
https://github.com/zakdoek/django-simple-resizer/blob/5614eb1717948c65d179c3d1567439a8c90a4d44/simple_resizer/templatetags/simple_resizer.py#L23-L38
246,198
thomasballinger/trellocardupdate
trellocardupdate/cli.py
choose
def choose(s, possibilities, threshold=.6): """ Returns the closest match to string s if exceeds threshold, else returns None """ if not possibilities: return None if s in possibilities: return s if s == '': return None startswith = [x for x in possibilities if x.lower().startswith(s.lower())] if len(startswith) == 1: return startswith[0] contained = [x for x in possibilities if s.lower() in x.lower()] if len(contained) == 1: return contained[0] best = max([(x, Levenshtein.jaro_winkler(s, x, .05)) for x in possibilities], key=itemgetter(1)) if best[1] < threshold: #print 'did you mean %s?' % best[0] return None return best[0]
python
def choose(s, possibilities, threshold=.6): """ Returns the closest match to string s if exceeds threshold, else returns None """ if not possibilities: return None if s in possibilities: return s if s == '': return None startswith = [x for x in possibilities if x.lower().startswith(s.lower())] if len(startswith) == 1: return startswith[0] contained = [x for x in possibilities if s.lower() in x.lower()] if len(contained) == 1: return contained[0] best = max([(x, Levenshtein.jaro_winkler(s, x, .05)) for x in possibilities], key=itemgetter(1)) if best[1] < threshold: #print 'did you mean %s?' % best[0] return None return best[0]
[ "def", "choose", "(", "s", ",", "possibilities", ",", "threshold", "=", ".6", ")", ":", "if", "not", "possibilities", ":", "return", "None", "if", "s", "in", "possibilities", ":", "return", "s", "if", "s", "==", "''", ":", "return", "None", "startswith", "=", "[", "x", "for", "x", "in", "possibilities", "if", "x", ".", "lower", "(", ")", ".", "startswith", "(", "s", ".", "lower", "(", ")", ")", "]", "if", "len", "(", "startswith", ")", "==", "1", ":", "return", "startswith", "[", "0", "]", "contained", "=", "[", "x", "for", "x", "in", "possibilities", "if", "s", ".", "lower", "(", ")", "in", "x", ".", "lower", "(", ")", "]", "if", "len", "(", "contained", ")", "==", "1", ":", "return", "contained", "[", "0", "]", "best", "=", "max", "(", "[", "(", "x", ",", "Levenshtein", ".", "jaro_winkler", "(", "s", ",", "x", ",", ".05", ")", ")", "for", "x", "in", "possibilities", "]", ",", "key", "=", "itemgetter", "(", "1", ")", ")", "if", "best", "[", "1", "]", "<", "threshold", ":", "#print 'did you mean %s?' % best[0]", "return", "None", "return", "best", "[", "0", "]" ]
Returns the closest match to string s if exceeds threshold, else returns None
[ "Returns", "the", "closest", "match", "to", "string", "s", "if", "exceeds", "threshold", "else", "returns", "None" ]
16a648fa15efef144c07cd56fcdb1d8920fac889
https://github.com/thomasballinger/trellocardupdate/blob/16a648fa15efef144c07cd56fcdb1d8920fac889/trellocardupdate/cli.py#L17-L32
246,199
ryanjdillon/pyotelem
pyotelem/dsp.py
normalized
def normalized(a, axis=-1, order=2): '''Return normalized vector for arbitrary axis Args ---- a: ndarray (n,3) Tri-axial vector data axis: int Axis index to overwhich to normalize order: int Order of nomalization to calculate Notes ----- This function was adapted from the following StackOverflow answer: http://stackoverflow.com/a/21032099/943773 ''' import numpy l2 = numpy.atleast_1d(numpy.linalg.norm(a, order, axis)) l2[l2==0] = 1 return a / numpy.expand_dims(l2, axis)
python
def normalized(a, axis=-1, order=2): '''Return normalized vector for arbitrary axis Args ---- a: ndarray (n,3) Tri-axial vector data axis: int Axis index to overwhich to normalize order: int Order of nomalization to calculate Notes ----- This function was adapted from the following StackOverflow answer: http://stackoverflow.com/a/21032099/943773 ''' import numpy l2 = numpy.atleast_1d(numpy.linalg.norm(a, order, axis)) l2[l2==0] = 1 return a / numpy.expand_dims(l2, axis)
[ "def", "normalized", "(", "a", ",", "axis", "=", "-", "1", ",", "order", "=", "2", ")", ":", "import", "numpy", "l2", "=", "numpy", ".", "atleast_1d", "(", "numpy", ".", "linalg", ".", "norm", "(", "a", ",", "order", ",", "axis", ")", ")", "l2", "[", "l2", "==", "0", "]", "=", "1", "return", "a", "/", "numpy", ".", "expand_dims", "(", "l2", ",", "axis", ")" ]
Return normalized vector for arbitrary axis Args ---- a: ndarray (n,3) Tri-axial vector data axis: int Axis index to overwhich to normalize order: int Order of nomalization to calculate Notes ----- This function was adapted from the following StackOverflow answer: http://stackoverflow.com/a/21032099/943773
[ "Return", "normalized", "vector", "for", "arbitrary", "axis" ]
816563a9c3feb3fa416f1c2921c6b75db34111ad
https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/dsp.py#L2-L24