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
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
SergeySatskiy/cdm-pythonparser | cdmpyparser.py | BriefModuleInfo._onGlobal | def _onGlobal(self, name, line, pos, absPosition, level):
"""Memorizes a global variable"""
# level is ignored
for item in self.globals:
if item.name == name:
return
self.globals.append(Global(name, line, pos, absPosition)) | python | def _onGlobal(self, name, line, pos, absPosition, level):
"""Memorizes a global variable"""
# level is ignored
for item in self.globals:
if item.name == name:
return
self.globals.append(Global(name, line, pos, absPosition)) | [
"def",
"_onGlobal",
"(",
"self",
",",
"name",
",",
"line",
",",
"pos",
",",
"absPosition",
",",
"level",
")",
":",
"# level is ignored",
"for",
"item",
"in",
"self",
".",
"globals",
":",
"if",
"item",
".",
"name",
"==",
"name",
":",
"return",
"self",
".",
"globals",
".",
"append",
"(",
"Global",
"(",
"name",
",",
"line",
",",
"pos",
",",
"absPosition",
")",
")"
] | Memorizes a global variable | [
"Memorizes",
"a",
"global",
"variable"
] | 7e933aca899b1853d744082313ffc3a8b1154505 | https://github.com/SergeySatskiy/cdm-pythonparser/blob/7e933aca899b1853d744082313ffc3a8b1154505/cdmpyparser.py#L492-L498 | train |
SergeySatskiy/cdm-pythonparser | cdmpyparser.py | BriefModuleInfo._onClass | def _onClass(self, name, line, pos, absPosition,
keywordLine, keywordPos,
colonLine, colonPos, level):
"""Memorizes a class"""
self.__flushLevel(level)
c = Class(name, line, pos, absPosition, keywordLine, keywordPos,
colonLine, colonPos)
if self.__lastDecorators is not None:
c.decorators = self.__lastDecorators
self.__lastDecorators = None
self.objectsStack.append(c) | python | def _onClass(self, name, line, pos, absPosition,
keywordLine, keywordPos,
colonLine, colonPos, level):
"""Memorizes a class"""
self.__flushLevel(level)
c = Class(name, line, pos, absPosition, keywordLine, keywordPos,
colonLine, colonPos)
if self.__lastDecorators is not None:
c.decorators = self.__lastDecorators
self.__lastDecorators = None
self.objectsStack.append(c) | [
"def",
"_onClass",
"(",
"self",
",",
"name",
",",
"line",
",",
"pos",
",",
"absPosition",
",",
"keywordLine",
",",
"keywordPos",
",",
"colonLine",
",",
"colonPos",
",",
"level",
")",
":",
"self",
".",
"__flushLevel",
"(",
"level",
")",
"c",
"=",
"Class",
"(",
"name",
",",
"line",
",",
"pos",
",",
"absPosition",
",",
"keywordLine",
",",
"keywordPos",
",",
"colonLine",
",",
"colonPos",
")",
"if",
"self",
".",
"__lastDecorators",
"is",
"not",
"None",
":",
"c",
".",
"decorators",
"=",
"self",
".",
"__lastDecorators",
"self",
".",
"__lastDecorators",
"=",
"None",
"self",
".",
"objectsStack",
".",
"append",
"(",
"c",
")"
] | Memorizes a class | [
"Memorizes",
"a",
"class"
] | 7e933aca899b1853d744082313ffc3a8b1154505 | https://github.com/SergeySatskiy/cdm-pythonparser/blob/7e933aca899b1853d744082313ffc3a8b1154505/cdmpyparser.py#L500-L510 | train |
SergeySatskiy/cdm-pythonparser | cdmpyparser.py | BriefModuleInfo._onWhat | def _onWhat(self, name, line, pos, absPosition):
"""Memorizes an imported item"""
self.__lastImport.what.append(ImportWhat(name, line, pos, absPosition)) | python | def _onWhat(self, name, line, pos, absPosition):
"""Memorizes an imported item"""
self.__lastImport.what.append(ImportWhat(name, line, pos, absPosition)) | [
"def",
"_onWhat",
"(",
"self",
",",
"name",
",",
"line",
",",
"pos",
",",
"absPosition",
")",
":",
"self",
".",
"__lastImport",
".",
"what",
".",
"append",
"(",
"ImportWhat",
"(",
"name",
",",
"line",
",",
"pos",
",",
"absPosition",
")",
")"
] | Memorizes an imported item | [
"Memorizes",
"an",
"imported",
"item"
] | 7e933aca899b1853d744082313ffc3a8b1154505 | https://github.com/SergeySatskiy/cdm-pythonparser/blob/7e933aca899b1853d744082313ffc3a8b1154505/cdmpyparser.py#L538-L540 | train |
SergeySatskiy/cdm-pythonparser | cdmpyparser.py | BriefModuleInfo._onClassAttribute | def _onClassAttribute(self, name, line, pos, absPosition, level):
"""Memorizes a class attribute"""
# A class must be on the top of the stack
attributes = self.objectsStack[level].classAttributes
for item in attributes:
if item.name == name:
return
attributes.append(ClassAttribute(name, line, pos, absPosition)) | python | def _onClassAttribute(self, name, line, pos, absPosition, level):
"""Memorizes a class attribute"""
# A class must be on the top of the stack
attributes = self.objectsStack[level].classAttributes
for item in attributes:
if item.name == name:
return
attributes.append(ClassAttribute(name, line, pos, absPosition)) | [
"def",
"_onClassAttribute",
"(",
"self",
",",
"name",
",",
"line",
",",
"pos",
",",
"absPosition",
",",
"level",
")",
":",
"# A class must be on the top of the stack",
"attributes",
"=",
"self",
".",
"objectsStack",
"[",
"level",
"]",
".",
"classAttributes",
"for",
"item",
"in",
"attributes",
":",
"if",
"item",
".",
"name",
"==",
"name",
":",
"return",
"attributes",
".",
"append",
"(",
"ClassAttribute",
"(",
"name",
",",
"line",
",",
"pos",
",",
"absPosition",
")",
")"
] | Memorizes a class attribute | [
"Memorizes",
"a",
"class",
"attribute"
] | 7e933aca899b1853d744082313ffc3a8b1154505 | https://github.com/SergeySatskiy/cdm-pythonparser/blob/7e933aca899b1853d744082313ffc3a8b1154505/cdmpyparser.py#L542-L549 | train |
SergeySatskiy/cdm-pythonparser | cdmpyparser.py | BriefModuleInfo._onInstanceAttribute | def _onInstanceAttribute(self, name, line, pos, absPosition, level):
"""Memorizes a class instance attribute"""
# Instance attributes may appear in member functions only so we already
# have a function on the stack of objects. To get the class object one
# more step is required so we -1 here.
attributes = self.objectsStack[level - 1].instanceAttributes
for item in attributes:
if item.name == name:
return
attributes.append(InstanceAttribute(name, line, pos, absPosition)) | python | def _onInstanceAttribute(self, name, line, pos, absPosition, level):
"""Memorizes a class instance attribute"""
# Instance attributes may appear in member functions only so we already
# have a function on the stack of objects. To get the class object one
# more step is required so we -1 here.
attributes = self.objectsStack[level - 1].instanceAttributes
for item in attributes:
if item.name == name:
return
attributes.append(InstanceAttribute(name, line, pos, absPosition)) | [
"def",
"_onInstanceAttribute",
"(",
"self",
",",
"name",
",",
"line",
",",
"pos",
",",
"absPosition",
",",
"level",
")",
":",
"# Instance attributes may appear in member functions only so we already",
"# have a function on the stack of objects. To get the class object one",
"# more step is required so we -1 here.",
"attributes",
"=",
"self",
".",
"objectsStack",
"[",
"level",
"-",
"1",
"]",
".",
"instanceAttributes",
"for",
"item",
"in",
"attributes",
":",
"if",
"item",
".",
"name",
"==",
"name",
":",
"return",
"attributes",
".",
"append",
"(",
"InstanceAttribute",
"(",
"name",
",",
"line",
",",
"pos",
",",
"absPosition",
")",
")"
] | Memorizes a class instance attribute | [
"Memorizes",
"a",
"class",
"instance",
"attribute"
] | 7e933aca899b1853d744082313ffc3a8b1154505 | https://github.com/SergeySatskiy/cdm-pythonparser/blob/7e933aca899b1853d744082313ffc3a8b1154505/cdmpyparser.py#L551-L560 | train |
SergeySatskiy/cdm-pythonparser | cdmpyparser.py | BriefModuleInfo._onArgument | def _onArgument(self, name, annotation):
"""Memorizes a function argument"""
self.objectsStack[-1].arguments.append(Argument(name, annotation)) | python | def _onArgument(self, name, annotation):
"""Memorizes a function argument"""
self.objectsStack[-1].arguments.append(Argument(name, annotation)) | [
"def",
"_onArgument",
"(",
"self",
",",
"name",
",",
"annotation",
")",
":",
"self",
".",
"objectsStack",
"[",
"-",
"1",
"]",
".",
"arguments",
".",
"append",
"(",
"Argument",
"(",
"name",
",",
"annotation",
")",
")"
] | Memorizes a function argument | [
"Memorizes",
"a",
"function",
"argument"
] | 7e933aca899b1853d744082313ffc3a8b1154505 | https://github.com/SergeySatskiy/cdm-pythonparser/blob/7e933aca899b1853d744082313ffc3a8b1154505/cdmpyparser.py#L583-L585 | train |
SergeySatskiy/cdm-pythonparser | cdmpyparser.py | BriefModuleInfo._onError | def _onError(self, message):
"""Memorizies a parser error message"""
self.isOK = False
if message.strip() != "":
self.errors.append(message) | python | def _onError(self, message):
"""Memorizies a parser error message"""
self.isOK = False
if message.strip() != "":
self.errors.append(message) | [
"def",
"_onError",
"(",
"self",
",",
"message",
")",
":",
"self",
".",
"isOK",
"=",
"False",
"if",
"message",
".",
"strip",
"(",
")",
"!=",
"\"\"",
":",
"self",
".",
"errors",
".",
"append",
"(",
"message",
")"
] | Memorizies a parser error message | [
"Memorizies",
"a",
"parser",
"error",
"message"
] | 7e933aca899b1853d744082313ffc3a8b1154505 | https://github.com/SergeySatskiy/cdm-pythonparser/blob/7e933aca899b1853d744082313ffc3a8b1154505/cdmpyparser.py#L596-L600 | train |
SergeySatskiy/cdm-pythonparser | cdmpyparser.py | BriefModuleInfo._onLexerError | def _onLexerError(self, message):
"""Memorizes a lexer error message"""
self.isOK = False
if message.strip() != "":
self.lexerErrors.append(message) | python | def _onLexerError(self, message):
"""Memorizes a lexer error message"""
self.isOK = False
if message.strip() != "":
self.lexerErrors.append(message) | [
"def",
"_onLexerError",
"(",
"self",
",",
"message",
")",
":",
"self",
".",
"isOK",
"=",
"False",
"if",
"message",
".",
"strip",
"(",
")",
"!=",
"\"\"",
":",
"self",
".",
"lexerErrors",
".",
"append",
"(",
"message",
")"
] | Memorizes a lexer error message | [
"Memorizes",
"a",
"lexer",
"error",
"message"
] | 7e933aca899b1853d744082313ffc3a8b1154505 | https://github.com/SergeySatskiy/cdm-pythonparser/blob/7e933aca899b1853d744082313ffc3a8b1154505/cdmpyparser.py#L602-L606 | train |
camptocamp/Studio | studio/lib/helpers.py | gen_mapname | def gen_mapname():
""" Generate a uniq mapfile pathname. """
filepath = None
while (filepath is None) or (os.path.exists(os.path.join(config['mapfiles_dir'], filepath))):
filepath = '%s.map' % _gen_string()
return filepath | python | def gen_mapname():
""" Generate a uniq mapfile pathname. """
filepath = None
while (filepath is None) or (os.path.exists(os.path.join(config['mapfiles_dir'], filepath))):
filepath = '%s.map' % _gen_string()
return filepath | [
"def",
"gen_mapname",
"(",
")",
":",
"filepath",
"=",
"None",
"while",
"(",
"filepath",
"is",
"None",
")",
"or",
"(",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"config",
"[",
"'mapfiles_dir'",
"]",
",",
"filepath",
")",
")",
")",
":",
"filepath",
"=",
"'%s.map'",
"%",
"_gen_string",
"(",
")",
"return",
"filepath"
] | Generate a uniq mapfile pathname. | [
"Generate",
"a",
"uniq",
"mapfile",
"pathname",
"."
] | 43cb7298434fb606b15136801b79b03571a2f27e | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/lib/helpers.py#L39-L44 | train |
camptocamp/Studio | studio/config/installer.py | StudioInstaller.config_content | def config_content(self, command, vars):
"""
Called by ``self.write_config``, this returns the text content
for the config file, given the provided variables.
"""
settable_vars = [
var('db_url', 'Database url for sqlite, postgres or mysql',
default='sqlite:///%(here)s/studio.db'),
var('ms_url','Url to the mapserv CGI',
default='http://localhost/cgi-bin/mapserv'),
var('admin_password','Password for default admin user',
default=secret.secret_string(length=8))
]
for svar in settable_vars:
if command.interactive:
prompt = 'Enter %s' % svar.full_description()
response = command.challenge(prompt, svar.default, svar.should_echo)
vars[svar.name] = response
else:
if not vars.has_key(svar.name):
vars[svar.name] = svar.default
vars['cookie_secret'] = secret.secret_string()
# call default pylons install
return super(StudioInstaller, self).config_content(command, vars) | python | def config_content(self, command, vars):
"""
Called by ``self.write_config``, this returns the text content
for the config file, given the provided variables.
"""
settable_vars = [
var('db_url', 'Database url for sqlite, postgres or mysql',
default='sqlite:///%(here)s/studio.db'),
var('ms_url','Url to the mapserv CGI',
default='http://localhost/cgi-bin/mapserv'),
var('admin_password','Password for default admin user',
default=secret.secret_string(length=8))
]
for svar in settable_vars:
if command.interactive:
prompt = 'Enter %s' % svar.full_description()
response = command.challenge(prompt, svar.default, svar.should_echo)
vars[svar.name] = response
else:
if not vars.has_key(svar.name):
vars[svar.name] = svar.default
vars['cookie_secret'] = secret.secret_string()
# call default pylons install
return super(StudioInstaller, self).config_content(command, vars) | [
"def",
"config_content",
"(",
"self",
",",
"command",
",",
"vars",
")",
":",
"settable_vars",
"=",
"[",
"var",
"(",
"'db_url'",
",",
"'Database url for sqlite, postgres or mysql'",
",",
"default",
"=",
"'sqlite:///%(here)s/studio.db'",
")",
",",
"var",
"(",
"'ms_url'",
",",
"'Url to the mapserv CGI'",
",",
"default",
"=",
"'http://localhost/cgi-bin/mapserv'",
")",
",",
"var",
"(",
"'admin_password'",
",",
"'Password for default admin user'",
",",
"default",
"=",
"secret",
".",
"secret_string",
"(",
"length",
"=",
"8",
")",
")",
"]",
"for",
"svar",
"in",
"settable_vars",
":",
"if",
"command",
".",
"interactive",
":",
"prompt",
"=",
"'Enter %s'",
"%",
"svar",
".",
"full_description",
"(",
")",
"response",
"=",
"command",
".",
"challenge",
"(",
"prompt",
",",
"svar",
".",
"default",
",",
"svar",
".",
"should_echo",
")",
"vars",
"[",
"svar",
".",
"name",
"]",
"=",
"response",
"else",
":",
"if",
"not",
"vars",
".",
"has_key",
"(",
"svar",
".",
"name",
")",
":",
"vars",
"[",
"svar",
".",
"name",
"]",
"=",
"svar",
".",
"default",
"vars",
"[",
"'cookie_secret'",
"]",
"=",
"secret",
".",
"secret_string",
"(",
")",
"# call default pylons install",
"return",
"super",
"(",
"StudioInstaller",
",",
"self",
")",
".",
"config_content",
"(",
"command",
",",
"vars",
")"
] | Called by ``self.write_config``, this returns the text content
for the config file, given the provided variables. | [
"Called",
"by",
"self",
".",
"write_config",
"this",
"returns",
"the",
"text",
"content",
"for",
"the",
"config",
"file",
"given",
"the",
"provided",
"variables",
"."
] | 43cb7298434fb606b15136801b79b03571a2f27e | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/config/installer.py#L29-L55 | train |
jpgxs/pyopsview | pyopsview/schema.py | SchemaField._resolve_definitions | def _resolve_definitions(self, schema, definitions):
"""Interpolates definitions from the top-level definitions key into the
schema. This is performed in a cut-down way similar to JSON schema.
"""
if not definitions:
return schema
if not isinstance(schema, dict):
return schema
ref = schema.pop('$ref', None)
if ref:
path = ref.split('/')[2:]
definition = definitions
for component in path:
definition = definitions[component]
if definition:
# Only update specified fields
for (key, val) in six.iteritems(definition):
if key not in schema:
schema[key] = val
for key in six.iterkeys(schema):
schema[key] = self._resolve_definitions(schema[key], definitions)
return schema | python | def _resolve_definitions(self, schema, definitions):
"""Interpolates definitions from the top-level definitions key into the
schema. This is performed in a cut-down way similar to JSON schema.
"""
if not definitions:
return schema
if not isinstance(schema, dict):
return schema
ref = schema.pop('$ref', None)
if ref:
path = ref.split('/')[2:]
definition = definitions
for component in path:
definition = definitions[component]
if definition:
# Only update specified fields
for (key, val) in six.iteritems(definition):
if key not in schema:
schema[key] = val
for key in six.iterkeys(schema):
schema[key] = self._resolve_definitions(schema[key], definitions)
return schema | [
"def",
"_resolve_definitions",
"(",
"self",
",",
"schema",
",",
"definitions",
")",
":",
"if",
"not",
"definitions",
":",
"return",
"schema",
"if",
"not",
"isinstance",
"(",
"schema",
",",
"dict",
")",
":",
"return",
"schema",
"ref",
"=",
"schema",
".",
"pop",
"(",
"'$ref'",
",",
"None",
")",
"if",
"ref",
":",
"path",
"=",
"ref",
".",
"split",
"(",
"'/'",
")",
"[",
"2",
":",
"]",
"definition",
"=",
"definitions",
"for",
"component",
"in",
"path",
":",
"definition",
"=",
"definitions",
"[",
"component",
"]",
"if",
"definition",
":",
"# Only update specified fields",
"for",
"(",
"key",
",",
"val",
")",
"in",
"six",
".",
"iteritems",
"(",
"definition",
")",
":",
"if",
"key",
"not",
"in",
"schema",
":",
"schema",
"[",
"key",
"]",
"=",
"val",
"for",
"key",
"in",
"six",
".",
"iterkeys",
"(",
"schema",
")",
":",
"schema",
"[",
"key",
"]",
"=",
"self",
".",
"_resolve_definitions",
"(",
"schema",
"[",
"key",
"]",
",",
"definitions",
")",
"return",
"schema"
] | Interpolates definitions from the top-level definitions key into the
schema. This is performed in a cut-down way similar to JSON schema. | [
"Interpolates",
"definitions",
"from",
"the",
"top",
"-",
"level",
"definitions",
"key",
"into",
"the",
"schema",
".",
"This",
"is",
"performed",
"in",
"a",
"cut",
"-",
"down",
"way",
"similar",
"to",
"JSON",
"schema",
"."
] | 5bbef35e463eda6dc67b0c34d3633a5a1c75a932 | https://github.com/jpgxs/pyopsview/blob/5bbef35e463eda6dc67b0c34d3633a5a1c75a932/pyopsview/schema.py#L181-L207 | train |
jpgxs/pyopsview | pyopsview/schema.py | SchemaField._get_serializer | def _get_serializer(self, _type):
"""Gets a serializer for a particular type. For primitives, returns the
serializer from the module-level serializers.
For arrays and objects, uses the special _get_T_serializer methods to
build the encoders and decoders.
"""
if _type in _serializers: # _serializers is module level
return _serializers[_type]
# array and object are special types
elif _type == 'array':
return self._get_array_serializer()
elif _type == 'object':
return self._get_object_serializer()
raise ValueError('Unknown type: {}'.format(_type)) | python | def _get_serializer(self, _type):
"""Gets a serializer for a particular type. For primitives, returns the
serializer from the module-level serializers.
For arrays and objects, uses the special _get_T_serializer methods to
build the encoders and decoders.
"""
if _type in _serializers: # _serializers is module level
return _serializers[_type]
# array and object are special types
elif _type == 'array':
return self._get_array_serializer()
elif _type == 'object':
return self._get_object_serializer()
raise ValueError('Unknown type: {}'.format(_type)) | [
"def",
"_get_serializer",
"(",
"self",
",",
"_type",
")",
":",
"if",
"_type",
"in",
"_serializers",
":",
"# _serializers is module level",
"return",
"_serializers",
"[",
"_type",
"]",
"# array and object are special types",
"elif",
"_type",
"==",
"'array'",
":",
"return",
"self",
".",
"_get_array_serializer",
"(",
")",
"elif",
"_type",
"==",
"'object'",
":",
"return",
"self",
".",
"_get_object_serializer",
"(",
")",
"raise",
"ValueError",
"(",
"'Unknown type: {}'",
".",
"format",
"(",
"_type",
")",
")"
] | Gets a serializer for a particular type. For primitives, returns the
serializer from the module-level serializers.
For arrays and objects, uses the special _get_T_serializer methods to
build the encoders and decoders. | [
"Gets",
"a",
"serializer",
"for",
"a",
"particular",
"type",
".",
"For",
"primitives",
"returns",
"the",
"serializer",
"from",
"the",
"module",
"-",
"level",
"serializers",
".",
"For",
"arrays",
"and",
"objects",
"uses",
"the",
"special",
"_get_T_serializer",
"methods",
"to",
"build",
"the",
"encoders",
"and",
"decoders",
"."
] | 5bbef35e463eda6dc67b0c34d3633a5a1c75a932 | https://github.com/jpgxs/pyopsview/blob/5bbef35e463eda6dc67b0c34d3633a5a1c75a932/pyopsview/schema.py#L209-L223 | train |
jpgxs/pyopsview | pyopsview/schema.py | SchemaField._get_array_serializer | def _get_array_serializer(self):
"""Gets the encoder and decoder for an array. Uses the 'items' key to
build the encoders and decoders for the specified type.
"""
if not self._items:
raise ValueError('Must specify \'items\' for \'array\' type')
field = SchemaField(self._items)
def encode(value, field=field):
if not isinstance(value, list):
value = [value]
return [field.encode(i) for i in value]
def decode(value, field=field):
return [field.decode(i) for i in value]
return (encode, decode) | python | def _get_array_serializer(self):
"""Gets the encoder and decoder for an array. Uses the 'items' key to
build the encoders and decoders for the specified type.
"""
if not self._items:
raise ValueError('Must specify \'items\' for \'array\' type')
field = SchemaField(self._items)
def encode(value, field=field):
if not isinstance(value, list):
value = [value]
return [field.encode(i) for i in value]
def decode(value, field=field):
return [field.decode(i) for i in value]
return (encode, decode) | [
"def",
"_get_array_serializer",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_items",
":",
"raise",
"ValueError",
"(",
"'Must specify \\'items\\' for \\'array\\' type'",
")",
"field",
"=",
"SchemaField",
"(",
"self",
".",
"_items",
")",
"def",
"encode",
"(",
"value",
",",
"field",
"=",
"field",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"value",
"=",
"[",
"value",
"]",
"return",
"[",
"field",
".",
"encode",
"(",
"i",
")",
"for",
"i",
"in",
"value",
"]",
"def",
"decode",
"(",
"value",
",",
"field",
"=",
"field",
")",
":",
"return",
"[",
"field",
".",
"decode",
"(",
"i",
")",
"for",
"i",
"in",
"value",
"]",
"return",
"(",
"encode",
",",
"decode",
")"
] | Gets the encoder and decoder for an array. Uses the 'items' key to
build the encoders and decoders for the specified type. | [
"Gets",
"the",
"encoder",
"and",
"decoder",
"for",
"an",
"array",
".",
"Uses",
"the",
"items",
"key",
"to",
"build",
"the",
"encoders",
"and",
"decoders",
"for",
"the",
"specified",
"type",
"."
] | 5bbef35e463eda6dc67b0c34d3633a5a1c75a932 | https://github.com/jpgxs/pyopsview/blob/5bbef35e463eda6dc67b0c34d3633a5a1c75a932/pyopsview/schema.py#L225-L243 | train |
jpgxs/pyopsview | pyopsview/schema.py | SchemaField.encode | def encode(self, value):
"""The encoder for this schema.
Tries each encoder in order of the types specified for this schema.
"""
if value is None and self._default is not None:
value = self._default
for encoder in self._encoders:
try:
return encoder(value)
except ValueError as ex:
pass
raise ValueError('Value \'{}\' is invalid. {}'
.format(value, ex.message)) | python | def encode(self, value):
"""The encoder for this schema.
Tries each encoder in order of the types specified for this schema.
"""
if value is None and self._default is not None:
value = self._default
for encoder in self._encoders:
try:
return encoder(value)
except ValueError as ex:
pass
raise ValueError('Value \'{}\' is invalid. {}'
.format(value, ex.message)) | [
"def",
"encode",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
"and",
"self",
".",
"_default",
"is",
"not",
"None",
":",
"value",
"=",
"self",
".",
"_default",
"for",
"encoder",
"in",
"self",
".",
"_encoders",
":",
"try",
":",
"return",
"encoder",
"(",
"value",
")",
"except",
"ValueError",
"as",
"ex",
":",
"pass",
"raise",
"ValueError",
"(",
"'Value \\'{}\\' is invalid. {}'",
".",
"format",
"(",
"value",
",",
"ex",
".",
"message",
")",
")"
] | The encoder for this schema.
Tries each encoder in order of the types specified for this schema. | [
"The",
"encoder",
"for",
"this",
"schema",
".",
"Tries",
"each",
"encoder",
"in",
"order",
"of",
"the",
"types",
"specified",
"for",
"this",
"schema",
"."
] | 5bbef35e463eda6dc67b0c34d3633a5a1c75a932 | https://github.com/jpgxs/pyopsview/blob/5bbef35e463eda6dc67b0c34d3633a5a1c75a932/pyopsview/schema.py#L360-L374 | train |
jpgxs/pyopsview | pyopsview/schema.py | SchemaField.decode | def decode(self, value):
"""The decoder for this schema.
Tries each decoder in order of the types specified for this schema.
"""
# Use the default value unless the field accepts None types
has_null_encoder = bool(encode_decode_null in self._decoders)
if value is None and self._default is not None and not has_null_encoder:
value = self._default
for decoder in self._decoders:
try:
return decoder(value)
except ValueError as ex:
pass
raise ValueError('Value \'{}\' is invalid. {}'
.format(value, ex.message)) | python | def decode(self, value):
"""The decoder for this schema.
Tries each decoder in order of the types specified for this schema.
"""
# Use the default value unless the field accepts None types
has_null_encoder = bool(encode_decode_null in self._decoders)
if value is None and self._default is not None and not has_null_encoder:
value = self._default
for decoder in self._decoders:
try:
return decoder(value)
except ValueError as ex:
pass
raise ValueError('Value \'{}\' is invalid. {}'
.format(value, ex.message)) | [
"def",
"decode",
"(",
"self",
",",
"value",
")",
":",
"# Use the default value unless the field accepts None types",
"has_null_encoder",
"=",
"bool",
"(",
"encode_decode_null",
"in",
"self",
".",
"_decoders",
")",
"if",
"value",
"is",
"None",
"and",
"self",
".",
"_default",
"is",
"not",
"None",
"and",
"not",
"has_null_encoder",
":",
"value",
"=",
"self",
".",
"_default",
"for",
"decoder",
"in",
"self",
".",
"_decoders",
":",
"try",
":",
"return",
"decoder",
"(",
"value",
")",
"except",
"ValueError",
"as",
"ex",
":",
"pass",
"raise",
"ValueError",
"(",
"'Value \\'{}\\' is invalid. {}'",
".",
"format",
"(",
"value",
",",
"ex",
".",
"message",
")",
")"
] | The decoder for this schema.
Tries each decoder in order of the types specified for this schema. | [
"The",
"decoder",
"for",
"this",
"schema",
".",
"Tries",
"each",
"decoder",
"in",
"order",
"of",
"the",
"types",
"specified",
"for",
"this",
"schema",
"."
] | 5bbef35e463eda6dc67b0c34d3633a5a1c75a932 | https://github.com/jpgxs/pyopsview/blob/5bbef35e463eda6dc67b0c34d3633a5a1c75a932/pyopsview/schema.py#L376-L393 | train |
jpgxs/pyopsview | pyopsview/ansible/module_utils/opsview.py | _fail_early | def _fail_early(message, **kwds):
"""The module arguments are dynamically generated based on the Opsview
version. This means that fail_json isn't available until after the module
has been properly initialized and the schemas have been loaded.
"""
import json
output = dict(kwds)
output.update({
'msg': message,
'failed': True,
})
print(json.dumps(output))
sys.exit(1) | python | def _fail_early(message, **kwds):
"""The module arguments are dynamically generated based on the Opsview
version. This means that fail_json isn't available until after the module
has been properly initialized and the schemas have been loaded.
"""
import json
output = dict(kwds)
output.update({
'msg': message,
'failed': True,
})
print(json.dumps(output))
sys.exit(1) | [
"def",
"_fail_early",
"(",
"message",
",",
"*",
"*",
"kwds",
")",
":",
"import",
"json",
"output",
"=",
"dict",
"(",
"kwds",
")",
"output",
".",
"update",
"(",
"{",
"'msg'",
":",
"message",
",",
"'failed'",
":",
"True",
",",
"}",
")",
"print",
"(",
"json",
".",
"dumps",
"(",
"output",
")",
")",
"sys",
".",
"exit",
"(",
"1",
")"
] | The module arguments are dynamically generated based on the Opsview
version. This means that fail_json isn't available until after the module
has been properly initialized and the schemas have been loaded. | [
"The",
"module",
"arguments",
"are",
"dynamically",
"generated",
"based",
"on",
"the",
"Opsview",
"version",
".",
"This",
"means",
"that",
"fail_json",
"isn",
"t",
"available",
"until",
"after",
"the",
"module",
"has",
"been",
"properly",
"initialized",
"and",
"the",
"schemas",
"have",
"been",
"loaded",
"."
] | 5bbef35e463eda6dc67b0c34d3633a5a1c75a932 | https://github.com/jpgxs/pyopsview/blob/5bbef35e463eda6dc67b0c34d3633a5a1c75a932/pyopsview/ansible/module_utils/opsview.py#L14-L27 | train |
jpgxs/pyopsview | pyopsview/ansible/module_utils/opsview.py | _compare_recursive | def _compare_recursive(old, new):
"""Deep comparison between objects; assumes that `new` contains
user defined parameters so only keys which exist in `new` will be
compared. Returns `True` if they differ. Else, `False`.
"""
if isinstance(new, dict):
for key in six.iterkeys(new):
try:
if _compare_recursive(old[key], new[key]):
return True
except (KeyError, TypeError):
return True
elif isinstance(new, list) or isinstance(new, tuple):
for i, item in enumerate(new):
try:
if _compare_recursive(old[i], item):
return True
except (IndexError, TypeError):
return True
else:
return old != new
return False | python | def _compare_recursive(old, new):
"""Deep comparison between objects; assumes that `new` contains
user defined parameters so only keys which exist in `new` will be
compared. Returns `True` if they differ. Else, `False`.
"""
if isinstance(new, dict):
for key in six.iterkeys(new):
try:
if _compare_recursive(old[key], new[key]):
return True
except (KeyError, TypeError):
return True
elif isinstance(new, list) or isinstance(new, tuple):
for i, item in enumerate(new):
try:
if _compare_recursive(old[i], item):
return True
except (IndexError, TypeError):
return True
else:
return old != new
return False | [
"def",
"_compare_recursive",
"(",
"old",
",",
"new",
")",
":",
"if",
"isinstance",
"(",
"new",
",",
"dict",
")",
":",
"for",
"key",
"in",
"six",
".",
"iterkeys",
"(",
"new",
")",
":",
"try",
":",
"if",
"_compare_recursive",
"(",
"old",
"[",
"key",
"]",
",",
"new",
"[",
"key",
"]",
")",
":",
"return",
"True",
"except",
"(",
"KeyError",
",",
"TypeError",
")",
":",
"return",
"True",
"elif",
"isinstance",
"(",
"new",
",",
"list",
")",
"or",
"isinstance",
"(",
"new",
",",
"tuple",
")",
":",
"for",
"i",
",",
"item",
"in",
"enumerate",
"(",
"new",
")",
":",
"try",
":",
"if",
"_compare_recursive",
"(",
"old",
"[",
"i",
"]",
",",
"item",
")",
":",
"return",
"True",
"except",
"(",
"IndexError",
",",
"TypeError",
")",
":",
"return",
"True",
"else",
":",
"return",
"old",
"!=",
"new",
"return",
"False"
] | Deep comparison between objects; assumes that `new` contains
user defined parameters so only keys which exist in `new` will be
compared. Returns `True` if they differ. Else, `False`. | [
"Deep",
"comparison",
"between",
"objects",
";",
"assumes",
"that",
"new",
"contains",
"user",
"defined",
"parameters",
"so",
"only",
"keys",
"which",
"exist",
"in",
"new",
"will",
"be",
"compared",
".",
"Returns",
"True",
"if",
"they",
"differ",
".",
"Else",
"False",
"."
] | 5bbef35e463eda6dc67b0c34d3633a5a1c75a932 | https://github.com/jpgxs/pyopsview/blob/5bbef35e463eda6dc67b0c34d3633a5a1c75a932/pyopsview/ansible/module_utils/opsview.py#L30-L53 | train |
jpgxs/pyopsview | pyopsview/ansible/module_utils/opsview.py | OpsviewAnsibleModuleAdvanced._requires_update | def _requires_update(self, old_object, new_object):
"""Checks whether the old object and new object differ; only checks
keys which exist in the new object
"""
old_encoded = self.manager._encode(old_object)
new_encoded = self.manager._encode(new_object)
return _compare_recursive(old_encoded, new_encoded) | python | def _requires_update(self, old_object, new_object):
"""Checks whether the old object and new object differ; only checks
keys which exist in the new object
"""
old_encoded = self.manager._encode(old_object)
new_encoded = self.manager._encode(new_object)
return _compare_recursive(old_encoded, new_encoded) | [
"def",
"_requires_update",
"(",
"self",
",",
"old_object",
",",
"new_object",
")",
":",
"old_encoded",
"=",
"self",
".",
"manager",
".",
"_encode",
"(",
"old_object",
")",
"new_encoded",
"=",
"self",
".",
"manager",
".",
"_encode",
"(",
"new_object",
")",
"return",
"_compare_recursive",
"(",
"old_encoded",
",",
"new_encoded",
")"
] | Checks whether the old object and new object differ; only checks
keys which exist in the new object | [
"Checks",
"whether",
"the",
"old",
"object",
"and",
"new",
"object",
"differ",
";",
"only",
"checks",
"keys",
"which",
"exist",
"in",
"the",
"new",
"object"
] | 5bbef35e463eda6dc67b0c34d3633a5a1c75a932 | https://github.com/jpgxs/pyopsview/blob/5bbef35e463eda6dc67b0c34d3633a5a1c75a932/pyopsview/ansible/module_utils/opsview.py#L215-L221 | train |
cnschema/cdata | cdata/web.py | url2domain | def url2domain(url):
""" extract domain from url
"""
parsed_uri = urlparse.urlparse(url)
domain = '{uri.netloc}'.format(uri=parsed_uri)
domain = re.sub("^.+@", "", domain)
domain = re.sub(":.+$", "", domain)
return domain | python | def url2domain(url):
""" extract domain from url
"""
parsed_uri = urlparse.urlparse(url)
domain = '{uri.netloc}'.format(uri=parsed_uri)
domain = re.sub("^.+@", "", domain)
domain = re.sub(":.+$", "", domain)
return domain | [
"def",
"url2domain",
"(",
"url",
")",
":",
"parsed_uri",
"=",
"urlparse",
".",
"urlparse",
"(",
"url",
")",
"domain",
"=",
"'{uri.netloc}'",
".",
"format",
"(",
"uri",
"=",
"parsed_uri",
")",
"domain",
"=",
"re",
".",
"sub",
"(",
"\"^.+@\"",
",",
"\"\"",
",",
"domain",
")",
"domain",
"=",
"re",
".",
"sub",
"(",
"\":.+$\"",
",",
"\"\"",
",",
"domain",
")",
"return",
"domain"
] | extract domain from url | [
"extract",
"domain",
"from",
"url"
] | 893e2e1e27b61c8551c8b5f5f9bf05ec61490e23 | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/web.py#L20-L27 | train |
camptocamp/Studio | studio/model/__init__.py | init_model | def init_model(engine):
"""Call me before using any of the tables or classes in the model"""
if meta.Session is None:
sm = orm.sessionmaker(autoflush=True, autocommit=False, bind=engine)
meta.engine = engine
meta.Session = orm.scoped_session(sm) | python | def init_model(engine):
"""Call me before using any of the tables or classes in the model"""
if meta.Session is None:
sm = orm.sessionmaker(autoflush=True, autocommit=False, bind=engine)
meta.engine = engine
meta.Session = orm.scoped_session(sm) | [
"def",
"init_model",
"(",
"engine",
")",
":",
"if",
"meta",
".",
"Session",
"is",
"None",
":",
"sm",
"=",
"orm",
".",
"sessionmaker",
"(",
"autoflush",
"=",
"True",
",",
"autocommit",
"=",
"False",
",",
"bind",
"=",
"engine",
")",
"meta",
".",
"engine",
"=",
"engine",
"meta",
".",
"Session",
"=",
"orm",
".",
"scoped_session",
"(",
"sm",
")"
] | Call me before using any of the tables or classes in the model | [
"Call",
"me",
"before",
"using",
"any",
"of",
"the",
"tables",
"or",
"classes",
"in",
"the",
"model"
] | 43cb7298434fb606b15136801b79b03571a2f27e | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/model/__init__.py#L32-L38 | train |
unbit/davvy | davvy/__init__.py | register_prop | def register_prop(name, handler_get, handler_set):
"""
register a property handler
"""
global props_get, props_set
if handler_get:
props_get[name] = handler_get
if handler_set:
props_set[name] = handler_set | python | def register_prop(name, handler_get, handler_set):
"""
register a property handler
"""
global props_get, props_set
if handler_get:
props_get[name] = handler_get
if handler_set:
props_set[name] = handler_set | [
"def",
"register_prop",
"(",
"name",
",",
"handler_get",
",",
"handler_set",
")",
":",
"global",
"props_get",
",",
"props_set",
"if",
"handler_get",
":",
"props_get",
"[",
"name",
"]",
"=",
"handler_get",
"if",
"handler_set",
":",
"props_set",
"[",
"name",
"]",
"=",
"handler_set"
] | register a property handler | [
"register",
"a",
"property",
"handler"
] | d9cd95fba25dbc76d80955bbbe5ff9d7cf52268a | https://github.com/unbit/davvy/blob/d9cd95fba25dbc76d80955bbbe5ff9d7cf52268a/davvy/__init__.py#L9-L17 | train |
unbit/davvy | davvy/__init__.py | retrieve_prop | def retrieve_prop(name):
"""
retrieve a property handler
"""
handler_get, handler_set = None, None
if name in props_get:
handler_get = props_get[name]
if name in props_set:
handler_set = props_set[name]
return (name, handler_get, handler_set) | python | def retrieve_prop(name):
"""
retrieve a property handler
"""
handler_get, handler_set = None, None
if name in props_get:
handler_get = props_get[name]
if name in props_set:
handler_set = props_set[name]
return (name, handler_get, handler_set) | [
"def",
"retrieve_prop",
"(",
"name",
")",
":",
"handler_get",
",",
"handler_set",
"=",
"None",
",",
"None",
"if",
"name",
"in",
"props_get",
":",
"handler_get",
"=",
"props_get",
"[",
"name",
"]",
"if",
"name",
"in",
"props_set",
":",
"handler_set",
"=",
"props_set",
"[",
"name",
"]",
"return",
"(",
"name",
",",
"handler_get",
",",
"handler_set",
")"
] | retrieve a property handler | [
"retrieve",
"a",
"property",
"handler"
] | d9cd95fba25dbc76d80955bbbe5ff9d7cf52268a | https://github.com/unbit/davvy/blob/d9cd95fba25dbc76d80955bbbe5ff9d7cf52268a/davvy/__init__.py#L20-L31 | train |
Radi85/Comment | comment/api/views.py | CommentList.get_queryset | def get_queryset(self):
'''
Parameters are already validated in the QuerySetPermission
'''
model_type = self.request.GET.get("type")
pk = self.request.GET.get("id")
content_type_model = ContentType.objects.get(model=model_type.lower())
Model = content_type_model.model_class()
model_obj = Model.objects.filter(id=pk).first()
return Comment.objects.filter_by_object(model_obj) | python | def get_queryset(self):
'''
Parameters are already validated in the QuerySetPermission
'''
model_type = self.request.GET.get("type")
pk = self.request.GET.get("id")
content_type_model = ContentType.objects.get(model=model_type.lower())
Model = content_type_model.model_class()
model_obj = Model.objects.filter(id=pk).first()
return Comment.objects.filter_by_object(model_obj) | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"model_type",
"=",
"self",
".",
"request",
".",
"GET",
".",
"get",
"(",
"\"type\"",
")",
"pk",
"=",
"self",
".",
"request",
".",
"GET",
".",
"get",
"(",
"\"id\"",
")",
"content_type_model",
"=",
"ContentType",
".",
"objects",
".",
"get",
"(",
"model",
"=",
"model_type",
".",
"lower",
"(",
")",
")",
"Model",
"=",
"content_type_model",
".",
"model_class",
"(",
")",
"model_obj",
"=",
"Model",
".",
"objects",
".",
"filter",
"(",
"id",
"=",
"pk",
")",
".",
"first",
"(",
")",
"return",
"Comment",
".",
"objects",
".",
"filter_by_object",
"(",
"model_obj",
")"
] | Parameters are already validated in the QuerySetPermission | [
"Parameters",
"are",
"already",
"validated",
"in",
"the",
"QuerySetPermission"
] | c3c46afe51228cd7ee4e04f5e6164fff1be3a5bc | https://github.com/Radi85/Comment/blob/c3c46afe51228cd7ee4e04f5e6164fff1be3a5bc/comment/api/views.py#L34-L43 | train |
camptocamp/Studio | studio/lib/archivefile.py | extractall | def extractall(archive, filename, dstdir):
""" extract zip or tar content to dstdir"""
if zipfile.is_zipfile(archive):
z = zipfile.ZipFile(archive)
for name in z.namelist():
targetname = name
# directories ends with '/' (on Windows as well)
if targetname.endswith('/'):
targetname = targetname[:-1]
# don't include leading "/" from file name if present
if targetname.startswith(os.path.sep):
targetname = os.path.join(dstdir, targetname[1:])
else:
targetname = os.path.join(dstdir, targetname)
targetname = os.path.normpath(targetname)
# Create all upper directories if necessary.
upperdirs = os.path.dirname(targetname)
if upperdirs and not os.path.exists(upperdirs):
os.makedirs(upperdirs)
# directories ends with '/' (on Windows as well)
if not name.endswith('/'):
# copy file
file(targetname, 'wb').write(z.read(name))
elif tarfile.is_tarfile(archive):
tar = tarfile.open(archive)
tar.extractall(path=dstdir)
else:
# seems to be a single file, save it
shutil.copyfile(archive, os.path.join(dstdir, filename)) | python | def extractall(archive, filename, dstdir):
""" extract zip or tar content to dstdir"""
if zipfile.is_zipfile(archive):
z = zipfile.ZipFile(archive)
for name in z.namelist():
targetname = name
# directories ends with '/' (on Windows as well)
if targetname.endswith('/'):
targetname = targetname[:-1]
# don't include leading "/" from file name if present
if targetname.startswith(os.path.sep):
targetname = os.path.join(dstdir, targetname[1:])
else:
targetname = os.path.join(dstdir, targetname)
targetname = os.path.normpath(targetname)
# Create all upper directories if necessary.
upperdirs = os.path.dirname(targetname)
if upperdirs and not os.path.exists(upperdirs):
os.makedirs(upperdirs)
# directories ends with '/' (on Windows as well)
if not name.endswith('/'):
# copy file
file(targetname, 'wb').write(z.read(name))
elif tarfile.is_tarfile(archive):
tar = tarfile.open(archive)
tar.extractall(path=dstdir)
else:
# seems to be a single file, save it
shutil.copyfile(archive, os.path.join(dstdir, filename)) | [
"def",
"extractall",
"(",
"archive",
",",
"filename",
",",
"dstdir",
")",
":",
"if",
"zipfile",
".",
"is_zipfile",
"(",
"archive",
")",
":",
"z",
"=",
"zipfile",
".",
"ZipFile",
"(",
"archive",
")",
"for",
"name",
"in",
"z",
".",
"namelist",
"(",
")",
":",
"targetname",
"=",
"name",
"# directories ends with '/' (on Windows as well)",
"if",
"targetname",
".",
"endswith",
"(",
"'/'",
")",
":",
"targetname",
"=",
"targetname",
"[",
":",
"-",
"1",
"]",
"# don't include leading \"/\" from file name if present",
"if",
"targetname",
".",
"startswith",
"(",
"os",
".",
"path",
".",
"sep",
")",
":",
"targetname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dstdir",
",",
"targetname",
"[",
"1",
":",
"]",
")",
"else",
":",
"targetname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dstdir",
",",
"targetname",
")",
"targetname",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"targetname",
")",
"# Create all upper directories if necessary. ",
"upperdirs",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"targetname",
")",
"if",
"upperdirs",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"upperdirs",
")",
":",
"os",
".",
"makedirs",
"(",
"upperdirs",
")",
"# directories ends with '/' (on Windows as well)",
"if",
"not",
"name",
".",
"endswith",
"(",
"'/'",
")",
":",
"# copy file",
"file",
"(",
"targetname",
",",
"'wb'",
")",
".",
"write",
"(",
"z",
".",
"read",
"(",
"name",
")",
")",
"elif",
"tarfile",
".",
"is_tarfile",
"(",
"archive",
")",
":",
"tar",
"=",
"tarfile",
".",
"open",
"(",
"archive",
")",
"tar",
".",
"extractall",
"(",
"path",
"=",
"dstdir",
")",
"else",
":",
"# seems to be a single file, save it",
"shutil",
".",
"copyfile",
"(",
"archive",
",",
"os",
".",
"path",
".",
"join",
"(",
"dstdir",
",",
"filename",
")",
")"
] | extract zip or tar content to dstdir | [
"extract",
"zip",
"or",
"tar",
"content",
"to",
"dstdir"
] | 43cb7298434fb606b15136801b79b03571a2f27e | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/lib/archivefile.py#L22-L55 | train |
camptocamp/Studio | studio/websetup.py | _merge_js | def _merge_js(input_file, input_dir, output_file):
""" Call into the merge_js module to merge the js files
and minify the code. """
from studio.lib.buildjs import merge_js
merge_js.main(input_file, input_dir, output_file) | python | def _merge_js(input_file, input_dir, output_file):
""" Call into the merge_js module to merge the js files
and minify the code. """
from studio.lib.buildjs import merge_js
merge_js.main(input_file, input_dir, output_file) | [
"def",
"_merge_js",
"(",
"input_file",
",",
"input_dir",
",",
"output_file",
")",
":",
"from",
"studio",
".",
"lib",
".",
"buildjs",
"import",
"merge_js",
"merge_js",
".",
"main",
"(",
"input_file",
",",
"input_dir",
",",
"output_file",
")"
] | Call into the merge_js module to merge the js files
and minify the code. | [
"Call",
"into",
"the",
"merge_js",
"module",
"to",
"merge",
"the",
"js",
"files",
"and",
"minify",
"the",
"code",
"."
] | 43cb7298434fb606b15136801b79b03571a2f27e | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/websetup.py#L208-L212 | train |
pjamesjoyce/lcopt | lcopt/utils.py | lcopt_bw2_setup | def lcopt_bw2_setup(ecospold_path, overwrite=False, db_name=None): # pragma: no cover
"""
Utility function to set up brightway2 to work correctly with lcopt.
It requires the path to the ecospold files containing the Ecoinvent 3.3 cutoff database.
If you don't have these files, log into `ecoinvent.org <http://www.ecoinvent.org/login-databases.html>`_ and go to the Files tab
Download the file called ``ecoinvent 3.3_cutoff_ecoSpold02.7z``
Extract the file somewhere sensible on your machine, you might need to download `7-zip <http://www.7-zip.org/download.html>`_ to extract the files.
Make a note of the path of the folder that contains the .ecospold files, its probably ``<path/extracted/to>/datasets/``
Use this path (as a string) as the first parameter in this function
To overwrite an existing version, set overwrite=True
"""
default_ei_name = "Ecoinvent3_3_cutoff"
if db_name is None:
db_name = DEFAULT_PROJECT_STEM + default_ei_name
if db_name in bw2.projects:
if overwrite:
bw2.projects.delete_project(name=db_name, delete_dir=True)
else:
print('Looks like bw2 is already set up - if you want to overwrite the existing version run lcopt.utils.lcopt_bw2_setup in a python shell using overwrite = True')
return False
bw2.projects.set_current(db_name)
bw2.bw2setup()
ei = bw2.SingleOutputEcospold2Importer(fix_mac_path_escapes(ecospold_path), default_ei_name)
ei.apply_strategies()
ei.statistics()
ei.write_database()
return True | python | def lcopt_bw2_setup(ecospold_path, overwrite=False, db_name=None): # pragma: no cover
"""
Utility function to set up brightway2 to work correctly with lcopt.
It requires the path to the ecospold files containing the Ecoinvent 3.3 cutoff database.
If you don't have these files, log into `ecoinvent.org <http://www.ecoinvent.org/login-databases.html>`_ and go to the Files tab
Download the file called ``ecoinvent 3.3_cutoff_ecoSpold02.7z``
Extract the file somewhere sensible on your machine, you might need to download `7-zip <http://www.7-zip.org/download.html>`_ to extract the files.
Make a note of the path of the folder that contains the .ecospold files, its probably ``<path/extracted/to>/datasets/``
Use this path (as a string) as the first parameter in this function
To overwrite an existing version, set overwrite=True
"""
default_ei_name = "Ecoinvent3_3_cutoff"
if db_name is None:
db_name = DEFAULT_PROJECT_STEM + default_ei_name
if db_name in bw2.projects:
if overwrite:
bw2.projects.delete_project(name=db_name, delete_dir=True)
else:
print('Looks like bw2 is already set up - if you want to overwrite the existing version run lcopt.utils.lcopt_bw2_setup in a python shell using overwrite = True')
return False
bw2.projects.set_current(db_name)
bw2.bw2setup()
ei = bw2.SingleOutputEcospold2Importer(fix_mac_path_escapes(ecospold_path), default_ei_name)
ei.apply_strategies()
ei.statistics()
ei.write_database()
return True | [
"def",
"lcopt_bw2_setup",
"(",
"ecospold_path",
",",
"overwrite",
"=",
"False",
",",
"db_name",
"=",
"None",
")",
":",
"# pragma: no cover",
"default_ei_name",
"=",
"\"Ecoinvent3_3_cutoff\"",
"if",
"db_name",
"is",
"None",
":",
"db_name",
"=",
"DEFAULT_PROJECT_STEM",
"+",
"default_ei_name",
"if",
"db_name",
"in",
"bw2",
".",
"projects",
":",
"if",
"overwrite",
":",
"bw2",
".",
"projects",
".",
"delete_project",
"(",
"name",
"=",
"db_name",
",",
"delete_dir",
"=",
"True",
")",
"else",
":",
"print",
"(",
"'Looks like bw2 is already set up - if you want to overwrite the existing version run lcopt.utils.lcopt_bw2_setup in a python shell using overwrite = True'",
")",
"return",
"False",
"bw2",
".",
"projects",
".",
"set_current",
"(",
"db_name",
")",
"bw2",
".",
"bw2setup",
"(",
")",
"ei",
"=",
"bw2",
".",
"SingleOutputEcospold2Importer",
"(",
"fix_mac_path_escapes",
"(",
"ecospold_path",
")",
",",
"default_ei_name",
")",
"ei",
".",
"apply_strategies",
"(",
")",
"ei",
".",
"statistics",
"(",
")",
"ei",
".",
"write_database",
"(",
")",
"return",
"True"
] | Utility function to set up brightway2 to work correctly with lcopt.
It requires the path to the ecospold files containing the Ecoinvent 3.3 cutoff database.
If you don't have these files, log into `ecoinvent.org <http://www.ecoinvent.org/login-databases.html>`_ and go to the Files tab
Download the file called ``ecoinvent 3.3_cutoff_ecoSpold02.7z``
Extract the file somewhere sensible on your machine, you might need to download `7-zip <http://www.7-zip.org/download.html>`_ to extract the files.
Make a note of the path of the folder that contains the .ecospold files, its probably ``<path/extracted/to>/datasets/``
Use this path (as a string) as the first parameter in this function
To overwrite an existing version, set overwrite=True | [
"Utility",
"function",
"to",
"set",
"up",
"brightway2",
"to",
"work",
"correctly",
"with",
"lcopt",
"."
] | 3f1caca31fece4a3068a384900707e6d21d04597 | https://github.com/pjamesjoyce/lcopt/blob/3f1caca31fece4a3068a384900707e6d21d04597/lcopt/utils.py#L38-L77 | train |
pjamesjoyce/lcopt | lcopt/utils.py | lcopt_bw2_autosetup | def lcopt_bw2_autosetup(ei_username=None, ei_password=None, write_config=None, ecoinvent_version='3.3', ecoinvent_system_model = "cutoff", overwrite=False):
"""
Utility function to automatically set up brightway2 to work correctly with lcopt.
It requires a valid username and password to login to the ecoinvent website.
These can be entered directly into the function using the keyword arguments `ei_username` and `ei_password` or entered interactively by using no arguments.
`ecoinvent_version` needs to be a string representation of a valid ecoinvent database, at time of writing these are "3.01", "3.1", "3.2", "3.3", "3.4"
`ecoinvent_system_model` needs to be one of "cutoff", "apos", "consequential"
To overwrite an existing version, set overwrite=True
"""
ei_name = "Ecoinvent{}_{}_{}".format(*ecoinvent_version.split('.'), ecoinvent_system_model)
config = check_for_config()
# If, for some reason, there's no config file, write the defaults
if config is None:
config = DEFAULT_CONFIG
with open(storage.config_file, "w") as cfg:
yaml.dump(config, cfg, default_flow_style=False)
store_option = storage.project_type
# Check if there's already a project set up that matches the current configuration
if store_option == 'single':
project_name = storage.single_project_name
if bw2_project_exists(project_name):
bw2.projects.set_current(project_name)
if ei_name in bw2.databases and overwrite == False:
#print ('{} is already set up'.format(ei_name))
return True
else: # default to 'unique'
project_name = DEFAULT_PROJECT_STEM + ei_name
if bw2_project_exists(project_name):
if overwrite:
bw2.projects.delete_project(name=project_name, delete_dir=True)
auto_ecoinvent = partial(eidl.get_ecoinvent,db_name=ei_name, auto_write=True, version=ecoinvent_version, system_model=ecoinvent_system_model)
# check for a config file (lcopt_config.yml)
if config is not None:
if "ecoinvent" in config:
if ei_username is None:
ei_username = config['ecoinvent'].get('username')
if ei_password is None:
ei_password = config['ecoinvent'].get('password')
write_config = False
if ei_username is None:
ei_username = input('ecoinvent username: ')
if ei_password is None:
ei_password = getpass.getpass('ecoinvent password: ')
if write_config is None:
write_config = input('store username and password on this computer? y/[n]') in ['y', 'Y', 'yes', 'YES', 'Yes']
if write_config:
config['ecoinvent'] = {
'username': ei_username,
'password': ei_password
}
with open(storage.config_file, "w") as cfg:
yaml.dump(config, cfg, default_flow_style=False)
# no need to keep running bw2setup - we can just copy a blank project which has been set up before
if store_option == 'single':
if bw2_project_exists(project_name):
bw2.projects.set_current(project_name)
else:
if not bw2_project_exists(DEFAULT_BIOSPHERE_PROJECT):
bw2.projects.set_current(project_name)
bw2.bw2setup()
else:
bw2.projects.set_current(DEFAULT_BIOSPHERE_PROJECT)
bw2.create_core_migrations()
bw2.projects.copy_project(project_name, switch=True)
else: #if store_option == 'unique':
if not bw2_project_exists(DEFAULT_BIOSPHERE_PROJECT):
lcopt_biosphere_setup()
bw2.projects.set_current(DEFAULT_BIOSPHERE_PROJECT)
bw2.create_core_migrations()
bw2.projects.copy_project(project_name, switch=True)
if ei_username is not None and ei_password is not None:
auto_ecoinvent(username=ei_username, password=ei_password)
else:
auto_ecoinvent()
write_search_index(project_name, ei_name, overwrite=overwrite)
return True | python | def lcopt_bw2_autosetup(ei_username=None, ei_password=None, write_config=None, ecoinvent_version='3.3', ecoinvent_system_model = "cutoff", overwrite=False):
"""
Utility function to automatically set up brightway2 to work correctly with lcopt.
It requires a valid username and password to login to the ecoinvent website.
These can be entered directly into the function using the keyword arguments `ei_username` and `ei_password` or entered interactively by using no arguments.
`ecoinvent_version` needs to be a string representation of a valid ecoinvent database, at time of writing these are "3.01", "3.1", "3.2", "3.3", "3.4"
`ecoinvent_system_model` needs to be one of "cutoff", "apos", "consequential"
To overwrite an existing version, set overwrite=True
"""
ei_name = "Ecoinvent{}_{}_{}".format(*ecoinvent_version.split('.'), ecoinvent_system_model)
config = check_for_config()
# If, for some reason, there's no config file, write the defaults
if config is None:
config = DEFAULT_CONFIG
with open(storage.config_file, "w") as cfg:
yaml.dump(config, cfg, default_flow_style=False)
store_option = storage.project_type
# Check if there's already a project set up that matches the current configuration
if store_option == 'single':
project_name = storage.single_project_name
if bw2_project_exists(project_name):
bw2.projects.set_current(project_name)
if ei_name in bw2.databases and overwrite == False:
#print ('{} is already set up'.format(ei_name))
return True
else: # default to 'unique'
project_name = DEFAULT_PROJECT_STEM + ei_name
if bw2_project_exists(project_name):
if overwrite:
bw2.projects.delete_project(name=project_name, delete_dir=True)
auto_ecoinvent = partial(eidl.get_ecoinvent,db_name=ei_name, auto_write=True, version=ecoinvent_version, system_model=ecoinvent_system_model)
# check for a config file (lcopt_config.yml)
if config is not None:
if "ecoinvent" in config:
if ei_username is None:
ei_username = config['ecoinvent'].get('username')
if ei_password is None:
ei_password = config['ecoinvent'].get('password')
write_config = False
if ei_username is None:
ei_username = input('ecoinvent username: ')
if ei_password is None:
ei_password = getpass.getpass('ecoinvent password: ')
if write_config is None:
write_config = input('store username and password on this computer? y/[n]') in ['y', 'Y', 'yes', 'YES', 'Yes']
if write_config:
config['ecoinvent'] = {
'username': ei_username,
'password': ei_password
}
with open(storage.config_file, "w") as cfg:
yaml.dump(config, cfg, default_flow_style=False)
# no need to keep running bw2setup - we can just copy a blank project which has been set up before
if store_option == 'single':
if bw2_project_exists(project_name):
bw2.projects.set_current(project_name)
else:
if not bw2_project_exists(DEFAULT_BIOSPHERE_PROJECT):
bw2.projects.set_current(project_name)
bw2.bw2setup()
else:
bw2.projects.set_current(DEFAULT_BIOSPHERE_PROJECT)
bw2.create_core_migrations()
bw2.projects.copy_project(project_name, switch=True)
else: #if store_option == 'unique':
if not bw2_project_exists(DEFAULT_BIOSPHERE_PROJECT):
lcopt_biosphere_setup()
bw2.projects.set_current(DEFAULT_BIOSPHERE_PROJECT)
bw2.create_core_migrations()
bw2.projects.copy_project(project_name, switch=True)
if ei_username is not None and ei_password is not None:
auto_ecoinvent(username=ei_username, password=ei_password)
else:
auto_ecoinvent()
write_search_index(project_name, ei_name, overwrite=overwrite)
return True | [
"def",
"lcopt_bw2_autosetup",
"(",
"ei_username",
"=",
"None",
",",
"ei_password",
"=",
"None",
",",
"write_config",
"=",
"None",
",",
"ecoinvent_version",
"=",
"'3.3'",
",",
"ecoinvent_system_model",
"=",
"\"cutoff\"",
",",
"overwrite",
"=",
"False",
")",
":",
"ei_name",
"=",
"\"Ecoinvent{}_{}_{}\"",
".",
"format",
"(",
"*",
"ecoinvent_version",
".",
"split",
"(",
"'.'",
")",
",",
"ecoinvent_system_model",
")",
"config",
"=",
"check_for_config",
"(",
")",
"# If, for some reason, there's no config file, write the defaults",
"if",
"config",
"is",
"None",
":",
"config",
"=",
"DEFAULT_CONFIG",
"with",
"open",
"(",
"storage",
".",
"config_file",
",",
"\"w\"",
")",
"as",
"cfg",
":",
"yaml",
".",
"dump",
"(",
"config",
",",
"cfg",
",",
"default_flow_style",
"=",
"False",
")",
"store_option",
"=",
"storage",
".",
"project_type",
"# Check if there's already a project set up that matches the current configuration",
"if",
"store_option",
"==",
"'single'",
":",
"project_name",
"=",
"storage",
".",
"single_project_name",
"if",
"bw2_project_exists",
"(",
"project_name",
")",
":",
"bw2",
".",
"projects",
".",
"set_current",
"(",
"project_name",
")",
"if",
"ei_name",
"in",
"bw2",
".",
"databases",
"and",
"overwrite",
"==",
"False",
":",
"#print ('{} is already set up'.format(ei_name))",
"return",
"True",
"else",
":",
"# default to 'unique'",
"project_name",
"=",
"DEFAULT_PROJECT_STEM",
"+",
"ei_name",
"if",
"bw2_project_exists",
"(",
"project_name",
")",
":",
"if",
"overwrite",
":",
"bw2",
".",
"projects",
".",
"delete_project",
"(",
"name",
"=",
"project_name",
",",
"delete_dir",
"=",
"True",
")",
"auto_ecoinvent",
"=",
"partial",
"(",
"eidl",
".",
"get_ecoinvent",
",",
"db_name",
"=",
"ei_name",
",",
"auto_write",
"=",
"True",
",",
"version",
"=",
"ecoinvent_version",
",",
"system_model",
"=",
"ecoinvent_system_model",
")",
"# check for a config file (lcopt_config.yml)",
"if",
"config",
"is",
"not",
"None",
":",
"if",
"\"ecoinvent\"",
"in",
"config",
":",
"if",
"ei_username",
"is",
"None",
":",
"ei_username",
"=",
"config",
"[",
"'ecoinvent'",
"]",
".",
"get",
"(",
"'username'",
")",
"if",
"ei_password",
"is",
"None",
":",
"ei_password",
"=",
"config",
"[",
"'ecoinvent'",
"]",
".",
"get",
"(",
"'password'",
")",
"write_config",
"=",
"False",
"if",
"ei_username",
"is",
"None",
":",
"ei_username",
"=",
"input",
"(",
"'ecoinvent username: '",
")",
"if",
"ei_password",
"is",
"None",
":",
"ei_password",
"=",
"getpass",
".",
"getpass",
"(",
"'ecoinvent password: '",
")",
"if",
"write_config",
"is",
"None",
":",
"write_config",
"=",
"input",
"(",
"'store username and password on this computer? y/[n]'",
")",
"in",
"[",
"'y'",
",",
"'Y'",
",",
"'yes'",
",",
"'YES'",
",",
"'Yes'",
"]",
"if",
"write_config",
":",
"config",
"[",
"'ecoinvent'",
"]",
"=",
"{",
"'username'",
":",
"ei_username",
",",
"'password'",
":",
"ei_password",
"}",
"with",
"open",
"(",
"storage",
".",
"config_file",
",",
"\"w\"",
")",
"as",
"cfg",
":",
"yaml",
".",
"dump",
"(",
"config",
",",
"cfg",
",",
"default_flow_style",
"=",
"False",
")",
"# no need to keep running bw2setup - we can just copy a blank project which has been set up before",
"if",
"store_option",
"==",
"'single'",
":",
"if",
"bw2_project_exists",
"(",
"project_name",
")",
":",
"bw2",
".",
"projects",
".",
"set_current",
"(",
"project_name",
")",
"else",
":",
"if",
"not",
"bw2_project_exists",
"(",
"DEFAULT_BIOSPHERE_PROJECT",
")",
":",
"bw2",
".",
"projects",
".",
"set_current",
"(",
"project_name",
")",
"bw2",
".",
"bw2setup",
"(",
")",
"else",
":",
"bw2",
".",
"projects",
".",
"set_current",
"(",
"DEFAULT_BIOSPHERE_PROJECT",
")",
"bw2",
".",
"create_core_migrations",
"(",
")",
"bw2",
".",
"projects",
".",
"copy_project",
"(",
"project_name",
",",
"switch",
"=",
"True",
")",
"else",
":",
"#if store_option == 'unique':",
"if",
"not",
"bw2_project_exists",
"(",
"DEFAULT_BIOSPHERE_PROJECT",
")",
":",
"lcopt_biosphere_setup",
"(",
")",
"bw2",
".",
"projects",
".",
"set_current",
"(",
"DEFAULT_BIOSPHERE_PROJECT",
")",
"bw2",
".",
"create_core_migrations",
"(",
")",
"bw2",
".",
"projects",
".",
"copy_project",
"(",
"project_name",
",",
"switch",
"=",
"True",
")",
"if",
"ei_username",
"is",
"not",
"None",
"and",
"ei_password",
"is",
"not",
"None",
":",
"auto_ecoinvent",
"(",
"username",
"=",
"ei_username",
",",
"password",
"=",
"ei_password",
")",
"else",
":",
"auto_ecoinvent",
"(",
")",
"write_search_index",
"(",
"project_name",
",",
"ei_name",
",",
"overwrite",
"=",
"overwrite",
")",
"return",
"True"
] | Utility function to automatically set up brightway2 to work correctly with lcopt.
It requires a valid username and password to login to the ecoinvent website.
These can be entered directly into the function using the keyword arguments `ei_username` and `ei_password` or entered interactively by using no arguments.
`ecoinvent_version` needs to be a string representation of a valid ecoinvent database, at time of writing these are "3.01", "3.1", "3.2", "3.3", "3.4"
`ecoinvent_system_model` needs to be one of "cutoff", "apos", "consequential"
To overwrite an existing version, set overwrite=True | [
"Utility",
"function",
"to",
"automatically",
"set",
"up",
"brightway2",
"to",
"work",
"correctly",
"with",
"lcopt",
"."
] | 3f1caca31fece4a3068a384900707e6d21d04597 | https://github.com/pjamesjoyce/lcopt/blob/3f1caca31fece4a3068a384900707e6d21d04597/lcopt/utils.py#L123-L228 | train |
pjamesjoyce/lcopt | lcopt/utils.py | forwast_autodownload | def forwast_autodownload(FORWAST_URL):
"""
Autodownloader for forwast database package for brightway. Used by `lcopt_bw2_forwast_setup` to get the database data. Not designed to be used on its own
"""
dirpath = tempfile.mkdtemp()
r = requests.get(FORWAST_URL)
z = zipfile.ZipFile(io.BytesIO(r.content))
z.extractall(dirpath)
return os.path.join(dirpath, 'forwast.bw2package') | python | def forwast_autodownload(FORWAST_URL):
"""
Autodownloader for forwast database package for brightway. Used by `lcopt_bw2_forwast_setup` to get the database data. Not designed to be used on its own
"""
dirpath = tempfile.mkdtemp()
r = requests.get(FORWAST_URL)
z = zipfile.ZipFile(io.BytesIO(r.content))
z.extractall(dirpath)
return os.path.join(dirpath, 'forwast.bw2package') | [
"def",
"forwast_autodownload",
"(",
"FORWAST_URL",
")",
":",
"dirpath",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"r",
"=",
"requests",
".",
"get",
"(",
"FORWAST_URL",
")",
"z",
"=",
"zipfile",
".",
"ZipFile",
"(",
"io",
".",
"BytesIO",
"(",
"r",
".",
"content",
")",
")",
"z",
".",
"extractall",
"(",
"dirpath",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"dirpath",
",",
"'forwast.bw2package'",
")"
] | Autodownloader for forwast database package for brightway. Used by `lcopt_bw2_forwast_setup` to get the database data. Not designed to be used on its own | [
"Autodownloader",
"for",
"forwast",
"database",
"package",
"for",
"brightway",
".",
"Used",
"by",
"lcopt_bw2_forwast_setup",
"to",
"get",
"the",
"database",
"data",
".",
"Not",
"designed",
"to",
"be",
"used",
"on",
"its",
"own"
] | 3f1caca31fece4a3068a384900707e6d21d04597 | https://github.com/pjamesjoyce/lcopt/blob/3f1caca31fece4a3068a384900707e6d21d04597/lcopt/utils.py#L288-L297 | train |
pjamesjoyce/lcopt | lcopt/utils.py | lcopt_bw2_forwast_setup | def lcopt_bw2_forwast_setup(use_autodownload=True, forwast_path=None, db_name=FORWAST_PROJECT_NAME, overwrite=False):
"""
Utility function to set up brightway2 to work correctly with lcopt using the FORWAST database instead of ecoinvent
By default it'll try and download the forwast database as a .bw2package file from lca-net
If you've downloaded the forwast .bw2package file already you can set use_autodownload=False and forwast_path to point to the downloaded file
To overwrite an existing version, set overwrite=True
"""
if use_autodownload:
forwast_filepath = forwast_autodownload(FORWAST_URL)
elif forwast_path is not None:
forwast_filepath = forwast_path
else:
raise ValueError('Need a path if not using autodownload')
if storage.project_type == 'single':
db_name = storage.single_project_name
if bw2_project_exists(db_name):
bw2.projects.set_current(db_name)
else:
bw2.projects.set_current(db_name)
bw2.bw2setup()
else:
if db_name in bw2.projects:
if overwrite:
bw2.projects.delete_project(name=db_name, delete_dir=True)
else:
print('Looks like bw2 is already set up for the FORWAST database - if you want to overwrite the existing version run lcopt.utils.lcopt_bw2_forwast_setup in a python shell using overwrite = True')
return False
# no need to keep running bw2setup - we can just copy a blank project which has been set up before
if not bw2_project_exists(DEFAULT_BIOSPHERE_PROJECT):
lcopt_biosphere_setup()
bw2.projects.set_current(DEFAULT_BIOSPHERE_PROJECT)
bw2.create_core_migrations()
bw2.projects.copy_project(db_name, switch=True)
bw2.BW2Package.import_file(forwast_filepath)
return True | python | def lcopt_bw2_forwast_setup(use_autodownload=True, forwast_path=None, db_name=FORWAST_PROJECT_NAME, overwrite=False):
"""
Utility function to set up brightway2 to work correctly with lcopt using the FORWAST database instead of ecoinvent
By default it'll try and download the forwast database as a .bw2package file from lca-net
If you've downloaded the forwast .bw2package file already you can set use_autodownload=False and forwast_path to point to the downloaded file
To overwrite an existing version, set overwrite=True
"""
if use_autodownload:
forwast_filepath = forwast_autodownload(FORWAST_URL)
elif forwast_path is not None:
forwast_filepath = forwast_path
else:
raise ValueError('Need a path if not using autodownload')
if storage.project_type == 'single':
db_name = storage.single_project_name
if bw2_project_exists(db_name):
bw2.projects.set_current(db_name)
else:
bw2.projects.set_current(db_name)
bw2.bw2setup()
else:
if db_name in bw2.projects:
if overwrite:
bw2.projects.delete_project(name=db_name, delete_dir=True)
else:
print('Looks like bw2 is already set up for the FORWAST database - if you want to overwrite the existing version run lcopt.utils.lcopt_bw2_forwast_setup in a python shell using overwrite = True')
return False
# no need to keep running bw2setup - we can just copy a blank project which has been set up before
if not bw2_project_exists(DEFAULT_BIOSPHERE_PROJECT):
lcopt_biosphere_setup()
bw2.projects.set_current(DEFAULT_BIOSPHERE_PROJECT)
bw2.create_core_migrations()
bw2.projects.copy_project(db_name, switch=True)
bw2.BW2Package.import_file(forwast_filepath)
return True | [
"def",
"lcopt_bw2_forwast_setup",
"(",
"use_autodownload",
"=",
"True",
",",
"forwast_path",
"=",
"None",
",",
"db_name",
"=",
"FORWAST_PROJECT_NAME",
",",
"overwrite",
"=",
"False",
")",
":",
"if",
"use_autodownload",
":",
"forwast_filepath",
"=",
"forwast_autodownload",
"(",
"FORWAST_URL",
")",
"elif",
"forwast_path",
"is",
"not",
"None",
":",
"forwast_filepath",
"=",
"forwast_path",
"else",
":",
"raise",
"ValueError",
"(",
"'Need a path if not using autodownload'",
")",
"if",
"storage",
".",
"project_type",
"==",
"'single'",
":",
"db_name",
"=",
"storage",
".",
"single_project_name",
"if",
"bw2_project_exists",
"(",
"db_name",
")",
":",
"bw2",
".",
"projects",
".",
"set_current",
"(",
"db_name",
")",
"else",
":",
"bw2",
".",
"projects",
".",
"set_current",
"(",
"db_name",
")",
"bw2",
".",
"bw2setup",
"(",
")",
"else",
":",
"if",
"db_name",
"in",
"bw2",
".",
"projects",
":",
"if",
"overwrite",
":",
"bw2",
".",
"projects",
".",
"delete_project",
"(",
"name",
"=",
"db_name",
",",
"delete_dir",
"=",
"True",
")",
"else",
":",
"print",
"(",
"'Looks like bw2 is already set up for the FORWAST database - if you want to overwrite the existing version run lcopt.utils.lcopt_bw2_forwast_setup in a python shell using overwrite = True'",
")",
"return",
"False",
"# no need to keep running bw2setup - we can just copy a blank project which has been set up before",
"if",
"not",
"bw2_project_exists",
"(",
"DEFAULT_BIOSPHERE_PROJECT",
")",
":",
"lcopt_biosphere_setup",
"(",
")",
"bw2",
".",
"projects",
".",
"set_current",
"(",
"DEFAULT_BIOSPHERE_PROJECT",
")",
"bw2",
".",
"create_core_migrations",
"(",
")",
"bw2",
".",
"projects",
".",
"copy_project",
"(",
"db_name",
",",
"switch",
"=",
"True",
")",
"bw2",
".",
"BW2Package",
".",
"import_file",
"(",
"forwast_filepath",
")",
"return",
"True"
] | Utility function to set up brightway2 to work correctly with lcopt using the FORWAST database instead of ecoinvent
By default it'll try and download the forwast database as a .bw2package file from lca-net
If you've downloaded the forwast .bw2package file already you can set use_autodownload=False and forwast_path to point to the downloaded file
To overwrite an existing version, set overwrite=True | [
"Utility",
"function",
"to",
"set",
"up",
"brightway2",
"to",
"work",
"correctly",
"with",
"lcopt",
"using",
"the",
"FORWAST",
"database",
"instead",
"of",
"ecoinvent"
] | 3f1caca31fece4a3068a384900707e6d21d04597 | https://github.com/pjamesjoyce/lcopt/blob/3f1caca31fece4a3068a384900707e6d21d04597/lcopt/utils.py#L300-L350 | train |
MoseleyBioinformaticsLab/mwtab | mwtab/validator.py | _validate_samples_factors | def _validate_samples_factors(mwtabfile, validate_samples=True, validate_factors=True):
"""Validate ``Samples`` and ``Factors`` identifiers across the file.
:param mwtabfile: Instance of :class:`~mwtab.mwtab.MWTabFile`.
:type mwtabfile: :class:`~mwtab.mwtab.MWTabFile`
:return: None
:rtype: :py:obj:`None`
"""
from_subject_samples = {i["local_sample_id"] for i in mwtabfile["SUBJECT_SAMPLE_FACTORS"]["SUBJECT_SAMPLE_FACTORS"]}
from_subject_factors = {i["factors"] for i in mwtabfile["SUBJECT_SAMPLE_FACTORS"]["SUBJECT_SAMPLE_FACTORS"]}
if validate_samples:
if "MS_METABOLITE_DATA" in mwtabfile:
from_metabolite_data_samples = set(mwtabfile["MS_METABOLITE_DATA"]["MS_METABOLITE_DATA_START"]["Samples"])
assert from_subject_samples == from_metabolite_data_samples
if "NMR_BINNED_DATA" in mwtabfile:
from_nmr_binned_data_samples = set(mwtabfile["NMR_BINNED_DATA"]["NMR_BINNED_DATA_START"]["Fields"][1:])
assert from_subject_samples == from_nmr_binned_data_samples
if validate_factors:
if "MS_METABOLITE_DATA" in mwtabfile:
from_metabolite_data_factors = set(mwtabfile["MS_METABOLITE_DATA"]["MS_METABOLITE_DATA_START"]["Factors"])
assert from_subject_factors == from_metabolite_data_factors | python | def _validate_samples_factors(mwtabfile, validate_samples=True, validate_factors=True):
"""Validate ``Samples`` and ``Factors`` identifiers across the file.
:param mwtabfile: Instance of :class:`~mwtab.mwtab.MWTabFile`.
:type mwtabfile: :class:`~mwtab.mwtab.MWTabFile`
:return: None
:rtype: :py:obj:`None`
"""
from_subject_samples = {i["local_sample_id"] for i in mwtabfile["SUBJECT_SAMPLE_FACTORS"]["SUBJECT_SAMPLE_FACTORS"]}
from_subject_factors = {i["factors"] for i in mwtabfile["SUBJECT_SAMPLE_FACTORS"]["SUBJECT_SAMPLE_FACTORS"]}
if validate_samples:
if "MS_METABOLITE_DATA" in mwtabfile:
from_metabolite_data_samples = set(mwtabfile["MS_METABOLITE_DATA"]["MS_METABOLITE_DATA_START"]["Samples"])
assert from_subject_samples == from_metabolite_data_samples
if "NMR_BINNED_DATA" in mwtabfile:
from_nmr_binned_data_samples = set(mwtabfile["NMR_BINNED_DATA"]["NMR_BINNED_DATA_START"]["Fields"][1:])
assert from_subject_samples == from_nmr_binned_data_samples
if validate_factors:
if "MS_METABOLITE_DATA" in mwtabfile:
from_metabolite_data_factors = set(mwtabfile["MS_METABOLITE_DATA"]["MS_METABOLITE_DATA_START"]["Factors"])
assert from_subject_factors == from_metabolite_data_factors | [
"def",
"_validate_samples_factors",
"(",
"mwtabfile",
",",
"validate_samples",
"=",
"True",
",",
"validate_factors",
"=",
"True",
")",
":",
"from_subject_samples",
"=",
"{",
"i",
"[",
"\"local_sample_id\"",
"]",
"for",
"i",
"in",
"mwtabfile",
"[",
"\"SUBJECT_SAMPLE_FACTORS\"",
"]",
"[",
"\"SUBJECT_SAMPLE_FACTORS\"",
"]",
"}",
"from_subject_factors",
"=",
"{",
"i",
"[",
"\"factors\"",
"]",
"for",
"i",
"in",
"mwtabfile",
"[",
"\"SUBJECT_SAMPLE_FACTORS\"",
"]",
"[",
"\"SUBJECT_SAMPLE_FACTORS\"",
"]",
"}",
"if",
"validate_samples",
":",
"if",
"\"MS_METABOLITE_DATA\"",
"in",
"mwtabfile",
":",
"from_metabolite_data_samples",
"=",
"set",
"(",
"mwtabfile",
"[",
"\"MS_METABOLITE_DATA\"",
"]",
"[",
"\"MS_METABOLITE_DATA_START\"",
"]",
"[",
"\"Samples\"",
"]",
")",
"assert",
"from_subject_samples",
"==",
"from_metabolite_data_samples",
"if",
"\"NMR_BINNED_DATA\"",
"in",
"mwtabfile",
":",
"from_nmr_binned_data_samples",
"=",
"set",
"(",
"mwtabfile",
"[",
"\"NMR_BINNED_DATA\"",
"]",
"[",
"\"NMR_BINNED_DATA_START\"",
"]",
"[",
"\"Fields\"",
"]",
"[",
"1",
":",
"]",
")",
"assert",
"from_subject_samples",
"==",
"from_nmr_binned_data_samples",
"if",
"validate_factors",
":",
"if",
"\"MS_METABOLITE_DATA\"",
"in",
"mwtabfile",
":",
"from_metabolite_data_factors",
"=",
"set",
"(",
"mwtabfile",
"[",
"\"MS_METABOLITE_DATA\"",
"]",
"[",
"\"MS_METABOLITE_DATA_START\"",
"]",
"[",
"\"Factors\"",
"]",
")",
"assert",
"from_subject_factors",
"==",
"from_metabolite_data_factors"
] | Validate ``Samples`` and ``Factors`` identifiers across the file.
:param mwtabfile: Instance of :class:`~mwtab.mwtab.MWTabFile`.
:type mwtabfile: :class:`~mwtab.mwtab.MWTabFile`
:return: None
:rtype: :py:obj:`None` | [
"Validate",
"Samples",
"and",
"Factors",
"identifiers",
"across",
"the",
"file",
"."
] | 8c0ae8ab2aa621662f99589ed41e481cf8b7152b | https://github.com/MoseleyBioinformaticsLab/mwtab/blob/8c0ae8ab2aa621662f99589ed41e481cf8b7152b/mwtab/validator.py#L19-L44 | train |
cocaine/cocaine-tools | cocaine/proxy/__init__.py | Daemon.daemonize | def daemonize(self):
"""Double-fork magic"""
if self.userid:
uid = pwd.getpwnam(self.userid).pw_uid
os.seteuid(uid)
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError as err:
sys.stderr.write("First fork failed: {0} ({1})\n".format(err.errno, err.strerror))
sys.exit(1)
# decouple from parent environment
os.chdir("/")
os.setsid()
os.umask(0)
# Second fork
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError as err:
sys.stderr.write("Second fork failed: {0} ({1})\n".format(err.errno, err.strerror))
sys.exit(1)
sys.stdout.flush()
sys.stderr.flush()
si = open(self.stdin, 'r')
so = open(self.stdout, 'w')
se = open(self.stderr, 'w')
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
# write PID file
atexit.register(self.delpid)
pid = str(os.getpid())
open(self.pidfile, 'w').write("%s\n" % pid) | python | def daemonize(self):
"""Double-fork magic"""
if self.userid:
uid = pwd.getpwnam(self.userid).pw_uid
os.seteuid(uid)
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError as err:
sys.stderr.write("First fork failed: {0} ({1})\n".format(err.errno, err.strerror))
sys.exit(1)
# decouple from parent environment
os.chdir("/")
os.setsid()
os.umask(0)
# Second fork
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError as err:
sys.stderr.write("Second fork failed: {0} ({1})\n".format(err.errno, err.strerror))
sys.exit(1)
sys.stdout.flush()
sys.stderr.flush()
si = open(self.stdin, 'r')
so = open(self.stdout, 'w')
se = open(self.stderr, 'w')
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
# write PID file
atexit.register(self.delpid)
pid = str(os.getpid())
open(self.pidfile, 'w').write("%s\n" % pid) | [
"def",
"daemonize",
"(",
"self",
")",
":",
"if",
"self",
".",
"userid",
":",
"uid",
"=",
"pwd",
".",
"getpwnam",
"(",
"self",
".",
"userid",
")",
".",
"pw_uid",
"os",
".",
"seteuid",
"(",
"uid",
")",
"try",
":",
"pid",
"=",
"os",
".",
"fork",
"(",
")",
"if",
"pid",
">",
"0",
":",
"sys",
".",
"exit",
"(",
"0",
")",
"except",
"OSError",
"as",
"err",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"First fork failed: {0} ({1})\\n\"",
".",
"format",
"(",
"err",
".",
"errno",
",",
"err",
".",
"strerror",
")",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"# decouple from parent environment",
"os",
".",
"chdir",
"(",
"\"/\"",
")",
"os",
".",
"setsid",
"(",
")",
"os",
".",
"umask",
"(",
"0",
")",
"# Second fork",
"try",
":",
"pid",
"=",
"os",
".",
"fork",
"(",
")",
"if",
"pid",
">",
"0",
":",
"sys",
".",
"exit",
"(",
"0",
")",
"except",
"OSError",
"as",
"err",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"Second fork failed: {0} ({1})\\n\"",
".",
"format",
"(",
"err",
".",
"errno",
",",
"err",
".",
"strerror",
")",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"sys",
".",
"stderr",
".",
"flush",
"(",
")",
"si",
"=",
"open",
"(",
"self",
".",
"stdin",
",",
"'r'",
")",
"so",
"=",
"open",
"(",
"self",
".",
"stdout",
",",
"'w'",
")",
"se",
"=",
"open",
"(",
"self",
".",
"stderr",
",",
"'w'",
")",
"os",
".",
"dup2",
"(",
"si",
".",
"fileno",
"(",
")",
",",
"sys",
".",
"stdin",
".",
"fileno",
"(",
")",
")",
"os",
".",
"dup2",
"(",
"so",
".",
"fileno",
"(",
")",
",",
"sys",
".",
"stdout",
".",
"fileno",
"(",
")",
")",
"os",
".",
"dup2",
"(",
"se",
".",
"fileno",
"(",
")",
",",
"sys",
".",
"stderr",
".",
"fileno",
"(",
")",
")",
"# write PID file",
"atexit",
".",
"register",
"(",
"self",
".",
"delpid",
")",
"pid",
"=",
"str",
"(",
"os",
".",
"getpid",
"(",
")",
")",
"open",
"(",
"self",
".",
"pidfile",
",",
"'w'",
")",
".",
"write",
"(",
"\"%s\\n\"",
"%",
"pid",
")"
] | Double-fork magic | [
"Double",
"-",
"fork",
"magic"
] | d8834f8e04ca42817d5f4e368d471484d4b3419f | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/proxy/__init__.py#L38-L77 | train |
tropo/tropo-webapi-python | build/lib/tropo.py | Tropo.RenderJson | def RenderJson(self, pretty=False):
"""
Render a Tropo object into a Json string.
"""
steps = self._steps
topdict = {}
topdict['tropo'] = steps
if pretty:
try:
json = jsonlib.dumps(topdict, indent=4, sort_keys=False)
except TypeError:
json = jsonlib.dumps(topdict)
else:
json = jsonlib.dumps(topdict)
return json | python | def RenderJson(self, pretty=False):
"""
Render a Tropo object into a Json string.
"""
steps = self._steps
topdict = {}
topdict['tropo'] = steps
if pretty:
try:
json = jsonlib.dumps(topdict, indent=4, sort_keys=False)
except TypeError:
json = jsonlib.dumps(topdict)
else:
json = jsonlib.dumps(topdict)
return json | [
"def",
"RenderJson",
"(",
"self",
",",
"pretty",
"=",
"False",
")",
":",
"steps",
"=",
"self",
".",
"_steps",
"topdict",
"=",
"{",
"}",
"topdict",
"[",
"'tropo'",
"]",
"=",
"steps",
"if",
"pretty",
":",
"try",
":",
"json",
"=",
"jsonlib",
".",
"dumps",
"(",
"topdict",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"False",
")",
"except",
"TypeError",
":",
"json",
"=",
"jsonlib",
".",
"dumps",
"(",
"topdict",
")",
"else",
":",
"json",
"=",
"jsonlib",
".",
"dumps",
"(",
"topdict",
")",
"return",
"json"
] | Render a Tropo object into a Json string. | [
"Render",
"a",
"Tropo",
"object",
"into",
"a",
"Json",
"string",
"."
] | f87772644a6b45066a4c5218f0c1f6467b64ab3c | https://github.com/tropo/tropo-webapi-python/blob/f87772644a6b45066a4c5218f0c1f6467b64ab3c/build/lib/tropo.py#L864-L878 | train |
tropo/tropo-webapi-python | tropo.py | Result.getIndexedValue | def getIndexedValue(self, index):
"""
Get the value of the indexed Tropo action.
"""
actions = self._actions
if (type (actions) is list):
dict = actions[index]
else:
dict = actions
return dict.get('value', 'NoValue') | python | def getIndexedValue(self, index):
"""
Get the value of the indexed Tropo action.
"""
actions = self._actions
if (type (actions) is list):
dict = actions[index]
else:
dict = actions
return dict.get('value', 'NoValue') | [
"def",
"getIndexedValue",
"(",
"self",
",",
"index",
")",
":",
"actions",
"=",
"self",
".",
"_actions",
"if",
"(",
"type",
"(",
"actions",
")",
"is",
"list",
")",
":",
"dict",
"=",
"actions",
"[",
"index",
"]",
"else",
":",
"dict",
"=",
"actions",
"return",
"dict",
".",
"get",
"(",
"'value'",
",",
"'NoValue'",
")"
] | Get the value of the indexed Tropo action. | [
"Get",
"the",
"value",
"of",
"the",
"indexed",
"Tropo",
"action",
"."
] | f87772644a6b45066a4c5218f0c1f6467b64ab3c | https://github.com/tropo/tropo-webapi-python/blob/f87772644a6b45066a4c5218f0c1f6467b64ab3c/tropo.py#L724-L734 | train |
tropo/tropo-webapi-python | tropo.py | Result.getNamedActionValue | def getNamedActionValue(self, name):
"""
Get the value of the named Tropo action.
"""
actions = self._actions
if (type (actions) is list):
for a in actions:
if a.get('name', 'NoValue') == name:
dict =a
else:
dict = actions
return dict.get('value', 'NoValue') | python | def getNamedActionValue(self, name):
"""
Get the value of the named Tropo action.
"""
actions = self._actions
if (type (actions) is list):
for a in actions:
if a.get('name', 'NoValue') == name:
dict =a
else:
dict = actions
return dict.get('value', 'NoValue') | [
"def",
"getNamedActionValue",
"(",
"self",
",",
"name",
")",
":",
"actions",
"=",
"self",
".",
"_actions",
"if",
"(",
"type",
"(",
"actions",
")",
"is",
"list",
")",
":",
"for",
"a",
"in",
"actions",
":",
"if",
"a",
".",
"get",
"(",
"'name'",
",",
"'NoValue'",
")",
"==",
"name",
":",
"dict",
"=",
"a",
"else",
":",
"dict",
"=",
"actions",
"return",
"dict",
".",
"get",
"(",
"'value'",
",",
"'NoValue'",
")"
] | Get the value of the named Tropo action. | [
"Get",
"the",
"value",
"of",
"the",
"named",
"Tropo",
"action",
"."
] | f87772644a6b45066a4c5218f0c1f6467b64ab3c | https://github.com/tropo/tropo-webapi-python/blob/f87772644a6b45066a4c5218f0c1f6467b64ab3c/tropo.py#L736-L748 | train |
camptocamp/Studio | studio/lib/os_utils.py | stop_subprocess | def stop_subprocess(pid):
"""Stop subprocess whose process id is pid."""
if hasattr(os, "kill"):
import signal
os.kill(pid, signal.SIGTERM)
else:
import win32api
pid = win32api.OpenProcess(1, 0, pid)
win32api.TerminateProcess(pid, 0)
os.waitpid(pid, 0) | python | def stop_subprocess(pid):
"""Stop subprocess whose process id is pid."""
if hasattr(os, "kill"):
import signal
os.kill(pid, signal.SIGTERM)
else:
import win32api
pid = win32api.OpenProcess(1, 0, pid)
win32api.TerminateProcess(pid, 0)
os.waitpid(pid, 0) | [
"def",
"stop_subprocess",
"(",
"pid",
")",
":",
"if",
"hasattr",
"(",
"os",
",",
"\"kill\"",
")",
":",
"import",
"signal",
"os",
".",
"kill",
"(",
"pid",
",",
"signal",
".",
"SIGTERM",
")",
"else",
":",
"import",
"win32api",
"pid",
"=",
"win32api",
".",
"OpenProcess",
"(",
"1",
",",
"0",
",",
"pid",
")",
"win32api",
".",
"TerminateProcess",
"(",
"pid",
",",
"0",
")",
"os",
".",
"waitpid",
"(",
"pid",
",",
"0",
")"
] | Stop subprocess whose process id is pid. | [
"Stop",
"subprocess",
"whose",
"process",
"id",
"is",
"pid",
"."
] | 43cb7298434fb606b15136801b79b03571a2f27e | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/lib/os_utils.py#L23-L32 | train |
cnschema/cdata | cdata/core.py | file2abspath | def file2abspath(filename, this_file=__file__):
"""
generate absolute path for the given file and base dir
"""
return os.path.abspath(
os.path.join(os.path.dirname(os.path.abspath(this_file)), filename)) | python | def file2abspath(filename, this_file=__file__):
"""
generate absolute path for the given file and base dir
"""
return os.path.abspath(
os.path.join(os.path.dirname(os.path.abspath(this_file)), filename)) | [
"def",
"file2abspath",
"(",
"filename",
",",
"this_file",
"=",
"__file__",
")",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"this_file",
")",
")",
",",
"filename",
")",
")"
] | generate absolute path for the given file and base dir | [
"generate",
"absolute",
"path",
"for",
"the",
"given",
"file",
"and",
"base",
"dir"
] | 893e2e1e27b61c8551c8b5f5f9bf05ec61490e23 | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L28-L33 | train |
cnschema/cdata | cdata/core.py | file2json | def file2json(filename, encoding='utf-8'):
"""
save a line
"""
with codecs.open(filename, "r", encoding=encoding) as f:
return json.load(f) | python | def file2json(filename, encoding='utf-8'):
"""
save a line
"""
with codecs.open(filename, "r", encoding=encoding) as f:
return json.load(f) | [
"def",
"file2json",
"(",
"filename",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"with",
"codecs",
".",
"open",
"(",
"filename",
",",
"\"r\"",
",",
"encoding",
"=",
"encoding",
")",
"as",
"f",
":",
"return",
"json",
".",
"load",
"(",
"f",
")"
] | save a line | [
"save",
"a",
"line"
] | 893e2e1e27b61c8551c8b5f5f9bf05ec61490e23 | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L39-L44 | train |
cnschema/cdata | cdata/core.py | file2iter | def file2iter(filename, encoding='utf-8', comment_prefix="#",
skip_empty_line=True):
"""
json stream parsing or line parsing
"""
ret = list()
visited = set()
with codecs.open(filename, encoding=encoding) as f:
for line in f:
line = line.strip()
# skip empty line
if skip_empty_line and len(line) == 0:
continue
# skip comment line
if comment_prefix and line.startswith(comment_prefix):
continue
yield line | python | def file2iter(filename, encoding='utf-8', comment_prefix="#",
skip_empty_line=True):
"""
json stream parsing or line parsing
"""
ret = list()
visited = set()
with codecs.open(filename, encoding=encoding) as f:
for line in f:
line = line.strip()
# skip empty line
if skip_empty_line and len(line) == 0:
continue
# skip comment line
if comment_prefix and line.startswith(comment_prefix):
continue
yield line | [
"def",
"file2iter",
"(",
"filename",
",",
"encoding",
"=",
"'utf-8'",
",",
"comment_prefix",
"=",
"\"#\"",
",",
"skip_empty_line",
"=",
"True",
")",
":",
"ret",
"=",
"list",
"(",
")",
"visited",
"=",
"set",
"(",
")",
"with",
"codecs",
".",
"open",
"(",
"filename",
",",
"encoding",
"=",
"encoding",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"# skip empty line",
"if",
"skip_empty_line",
"and",
"len",
"(",
"line",
")",
"==",
"0",
":",
"continue",
"# skip comment line",
"if",
"comment_prefix",
"and",
"line",
".",
"startswith",
"(",
"comment_prefix",
")",
":",
"continue",
"yield",
"line"
] | json stream parsing or line parsing | [
"json",
"stream",
"parsing",
"or",
"line",
"parsing"
] | 893e2e1e27b61c8551c8b5f5f9bf05ec61490e23 | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L47-L65 | train |
cnschema/cdata | cdata/core.py | json2file | def json2file(data, filename, encoding='utf-8'):
"""
write json in canonical json format
"""
with codecs.open(filename, "w", encoding=encoding) as f:
json.dump(data, f, ensure_ascii=False, indent=4, sort_keys=True) | python | def json2file(data, filename, encoding='utf-8'):
"""
write json in canonical json format
"""
with codecs.open(filename, "w", encoding=encoding) as f:
json.dump(data, f, ensure_ascii=False, indent=4, sort_keys=True) | [
"def",
"json2file",
"(",
"data",
",",
"filename",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"with",
"codecs",
".",
"open",
"(",
"filename",
",",
"\"w\"",
",",
"encoding",
"=",
"encoding",
")",
"as",
"f",
":",
"json",
".",
"dump",
"(",
"data",
",",
"f",
",",
"ensure_ascii",
"=",
"False",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"True",
")"
] | write json in canonical json format | [
"write",
"json",
"in",
"canonical",
"json",
"format"
] | 893e2e1e27b61c8551c8b5f5f9bf05ec61490e23 | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L71-L76 | train |
cnschema/cdata | cdata/core.py | lines2file | def lines2file(lines, filename, encoding='utf-8'):
"""
write json stream, write lines too
"""
with codecs.open(filename, "w", encoding=encoding) as f:
for line in lines:
f.write(line)
f.write("\n") | python | def lines2file(lines, filename, encoding='utf-8'):
"""
write json stream, write lines too
"""
with codecs.open(filename, "w", encoding=encoding) as f:
for line in lines:
f.write(line)
f.write("\n") | [
"def",
"lines2file",
"(",
"lines",
",",
"filename",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"with",
"codecs",
".",
"open",
"(",
"filename",
",",
"\"w\"",
",",
"encoding",
"=",
"encoding",
")",
"as",
"f",
":",
"for",
"line",
"in",
"lines",
":",
"f",
".",
"write",
"(",
"line",
")",
"f",
".",
"write",
"(",
"\"\\n\"",
")"
] | write json stream, write lines too | [
"write",
"json",
"stream",
"write",
"lines",
"too"
] | 893e2e1e27b61c8551c8b5f5f9bf05ec61490e23 | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L79-L86 | train |
cnschema/cdata | cdata/core.py | items2file | def items2file(items, filename, encoding='utf-8', modifier='w'):
"""
json array to file, canonical json format
"""
with codecs.open(filename, modifier, encoding=encoding) as f:
for item in items:
f.write(u"{}\n".format(json.dumps(
item, ensure_ascii=False, sort_keys=True))) | python | def items2file(items, filename, encoding='utf-8', modifier='w'):
"""
json array to file, canonical json format
"""
with codecs.open(filename, modifier, encoding=encoding) as f:
for item in items:
f.write(u"{}\n".format(json.dumps(
item, ensure_ascii=False, sort_keys=True))) | [
"def",
"items2file",
"(",
"items",
",",
"filename",
",",
"encoding",
"=",
"'utf-8'",
",",
"modifier",
"=",
"'w'",
")",
":",
"with",
"codecs",
".",
"open",
"(",
"filename",
",",
"modifier",
",",
"encoding",
"=",
"encoding",
")",
"as",
"f",
":",
"for",
"item",
"in",
"items",
":",
"f",
".",
"write",
"(",
"u\"{}\\n\"",
".",
"format",
"(",
"json",
".",
"dumps",
"(",
"item",
",",
"ensure_ascii",
"=",
"False",
",",
"sort_keys",
"=",
"True",
")",
")",
")"
] | json array to file, canonical json format | [
"json",
"array",
"to",
"file",
"canonical",
"json",
"format"
] | 893e2e1e27b61c8551c8b5f5f9bf05ec61490e23 | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L89-L96 | train |
balloob/voluptuous-serialize | voluptuous_serialize/__init__.py | convert | def convert(schema):
"""Convert a voluptuous schema to a dictionary."""
# pylint: disable=too-many-return-statements,too-many-branches
if isinstance(schema, vol.Schema):
schema = schema.schema
if isinstance(schema, Mapping):
val = []
for key, value in schema.items():
description = None
if isinstance(key, vol.Marker):
pkey = key.schema
description = key.description
else:
pkey = key
pval = convert(value)
pval['name'] = pkey
if description is not None:
pval['description'] = description
if isinstance(key, (vol.Required, vol.Optional)):
pval[key.__class__.__name__.lower()] = True
if key.default is not vol.UNDEFINED:
pval['default'] = key.default()
val.append(pval)
return val
if isinstance(schema, vol.All):
val = {}
for validator in schema.validators:
val.update(convert(validator))
return val
if isinstance(schema, (vol.Clamp, vol.Range)):
val = {}
if schema.min is not None:
val['valueMin'] = schema.min
if schema.max is not None:
val['valueMax'] = schema.max
return val
if isinstance(schema, vol.Length):
val = {}
if schema.min is not None:
val['lengthMin'] = schema.min
if schema.max is not None:
val['lengthMax'] = schema.max
return val
if isinstance(schema, vol.Datetime):
return {
'type': 'datetime',
'format': schema.format,
}
if isinstance(schema, vol.In):
if isinstance(schema.container, Mapping):
return {
'type': 'select',
'options': list(schema.container.items()),
}
return {
'type': 'select',
'options': [(item, item) for item in schema.container]
}
if schema in (vol.Lower, vol.Upper, vol.Capitalize, vol.Title, vol.Strip):
return {
schema.__name__.lower(): True,
}
if isinstance(schema, vol.Coerce):
schema = schema.type
if schema in TYPES_MAP:
return {'type': TYPES_MAP[schema]}
raise ValueError('Unable to convert schema: {}'.format(schema)) | python | def convert(schema):
"""Convert a voluptuous schema to a dictionary."""
# pylint: disable=too-many-return-statements,too-many-branches
if isinstance(schema, vol.Schema):
schema = schema.schema
if isinstance(schema, Mapping):
val = []
for key, value in schema.items():
description = None
if isinstance(key, vol.Marker):
pkey = key.schema
description = key.description
else:
pkey = key
pval = convert(value)
pval['name'] = pkey
if description is not None:
pval['description'] = description
if isinstance(key, (vol.Required, vol.Optional)):
pval[key.__class__.__name__.lower()] = True
if key.default is not vol.UNDEFINED:
pval['default'] = key.default()
val.append(pval)
return val
if isinstance(schema, vol.All):
val = {}
for validator in schema.validators:
val.update(convert(validator))
return val
if isinstance(schema, (vol.Clamp, vol.Range)):
val = {}
if schema.min is not None:
val['valueMin'] = schema.min
if schema.max is not None:
val['valueMax'] = schema.max
return val
if isinstance(schema, vol.Length):
val = {}
if schema.min is not None:
val['lengthMin'] = schema.min
if schema.max is not None:
val['lengthMax'] = schema.max
return val
if isinstance(schema, vol.Datetime):
return {
'type': 'datetime',
'format': schema.format,
}
if isinstance(schema, vol.In):
if isinstance(schema.container, Mapping):
return {
'type': 'select',
'options': list(schema.container.items()),
}
return {
'type': 'select',
'options': [(item, item) for item in schema.container]
}
if schema in (vol.Lower, vol.Upper, vol.Capitalize, vol.Title, vol.Strip):
return {
schema.__name__.lower(): True,
}
if isinstance(schema, vol.Coerce):
schema = schema.type
if schema in TYPES_MAP:
return {'type': TYPES_MAP[schema]}
raise ValueError('Unable to convert schema: {}'.format(schema)) | [
"def",
"convert",
"(",
"schema",
")",
":",
"# pylint: disable=too-many-return-statements,too-many-branches",
"if",
"isinstance",
"(",
"schema",
",",
"vol",
".",
"Schema",
")",
":",
"schema",
"=",
"schema",
".",
"schema",
"if",
"isinstance",
"(",
"schema",
",",
"Mapping",
")",
":",
"val",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"schema",
".",
"items",
"(",
")",
":",
"description",
"=",
"None",
"if",
"isinstance",
"(",
"key",
",",
"vol",
".",
"Marker",
")",
":",
"pkey",
"=",
"key",
".",
"schema",
"description",
"=",
"key",
".",
"description",
"else",
":",
"pkey",
"=",
"key",
"pval",
"=",
"convert",
"(",
"value",
")",
"pval",
"[",
"'name'",
"]",
"=",
"pkey",
"if",
"description",
"is",
"not",
"None",
":",
"pval",
"[",
"'description'",
"]",
"=",
"description",
"if",
"isinstance",
"(",
"key",
",",
"(",
"vol",
".",
"Required",
",",
"vol",
".",
"Optional",
")",
")",
":",
"pval",
"[",
"key",
".",
"__class__",
".",
"__name__",
".",
"lower",
"(",
")",
"]",
"=",
"True",
"if",
"key",
".",
"default",
"is",
"not",
"vol",
".",
"UNDEFINED",
":",
"pval",
"[",
"'default'",
"]",
"=",
"key",
".",
"default",
"(",
")",
"val",
".",
"append",
"(",
"pval",
")",
"return",
"val",
"if",
"isinstance",
"(",
"schema",
",",
"vol",
".",
"All",
")",
":",
"val",
"=",
"{",
"}",
"for",
"validator",
"in",
"schema",
".",
"validators",
":",
"val",
".",
"update",
"(",
"convert",
"(",
"validator",
")",
")",
"return",
"val",
"if",
"isinstance",
"(",
"schema",
",",
"(",
"vol",
".",
"Clamp",
",",
"vol",
".",
"Range",
")",
")",
":",
"val",
"=",
"{",
"}",
"if",
"schema",
".",
"min",
"is",
"not",
"None",
":",
"val",
"[",
"'valueMin'",
"]",
"=",
"schema",
".",
"min",
"if",
"schema",
".",
"max",
"is",
"not",
"None",
":",
"val",
"[",
"'valueMax'",
"]",
"=",
"schema",
".",
"max",
"return",
"val",
"if",
"isinstance",
"(",
"schema",
",",
"vol",
".",
"Length",
")",
":",
"val",
"=",
"{",
"}",
"if",
"schema",
".",
"min",
"is",
"not",
"None",
":",
"val",
"[",
"'lengthMin'",
"]",
"=",
"schema",
".",
"min",
"if",
"schema",
".",
"max",
"is",
"not",
"None",
":",
"val",
"[",
"'lengthMax'",
"]",
"=",
"schema",
".",
"max",
"return",
"val",
"if",
"isinstance",
"(",
"schema",
",",
"vol",
".",
"Datetime",
")",
":",
"return",
"{",
"'type'",
":",
"'datetime'",
",",
"'format'",
":",
"schema",
".",
"format",
",",
"}",
"if",
"isinstance",
"(",
"schema",
",",
"vol",
".",
"In",
")",
":",
"if",
"isinstance",
"(",
"schema",
".",
"container",
",",
"Mapping",
")",
":",
"return",
"{",
"'type'",
":",
"'select'",
",",
"'options'",
":",
"list",
"(",
"schema",
".",
"container",
".",
"items",
"(",
")",
")",
",",
"}",
"return",
"{",
"'type'",
":",
"'select'",
",",
"'options'",
":",
"[",
"(",
"item",
",",
"item",
")",
"for",
"item",
"in",
"schema",
".",
"container",
"]",
"}",
"if",
"schema",
"in",
"(",
"vol",
".",
"Lower",
",",
"vol",
".",
"Upper",
",",
"vol",
".",
"Capitalize",
",",
"vol",
".",
"Title",
",",
"vol",
".",
"Strip",
")",
":",
"return",
"{",
"schema",
".",
"__name__",
".",
"lower",
"(",
")",
":",
"True",
",",
"}",
"if",
"isinstance",
"(",
"schema",
",",
"vol",
".",
"Coerce",
")",
":",
"schema",
"=",
"schema",
".",
"type",
"if",
"schema",
"in",
"TYPES_MAP",
":",
"return",
"{",
"'type'",
":",
"TYPES_MAP",
"[",
"schema",
"]",
"}",
"raise",
"ValueError",
"(",
"'Unable to convert schema: {}'",
".",
"format",
"(",
"schema",
")",
")"
] | Convert a voluptuous schema to a dictionary. | [
"Convert",
"a",
"voluptuous",
"schema",
"to",
"a",
"dictionary",
"."
] | 02992eb3128063d065048cdcbfb907efe0a53b99 | https://github.com/balloob/voluptuous-serialize/blob/02992eb3128063d065048cdcbfb907efe0a53b99/voluptuous_serialize/__init__.py#L15-L97 | train |
jpgxs/pyopsview | pyopsview/utils.py | version_cmp | def version_cmp(version_a, version_b):
"""Compares two versions"""
a = normalize_version(version_a)
b = normalize_version(version_b)
i_a = a[0] * 100 + a[1] * 10 + a[0] * 1
i_b = b[0] * 100 + b[1] * 10 + b[0] * 1
return i_a - i_b | python | def version_cmp(version_a, version_b):
"""Compares two versions"""
a = normalize_version(version_a)
b = normalize_version(version_b)
i_a = a[0] * 100 + a[1] * 10 + a[0] * 1
i_b = b[0] * 100 + b[1] * 10 + b[0] * 1
return i_a - i_b | [
"def",
"version_cmp",
"(",
"version_a",
",",
"version_b",
")",
":",
"a",
"=",
"normalize_version",
"(",
"version_a",
")",
"b",
"=",
"normalize_version",
"(",
"version_b",
")",
"i_a",
"=",
"a",
"[",
"0",
"]",
"*",
"100",
"+",
"a",
"[",
"1",
"]",
"*",
"10",
"+",
"a",
"[",
"0",
"]",
"*",
"1",
"i_b",
"=",
"b",
"[",
"0",
"]",
"*",
"100",
"+",
"b",
"[",
"1",
"]",
"*",
"10",
"+",
"b",
"[",
"0",
"]",
"*",
"1",
"return",
"i_a",
"-",
"i_b"
] | Compares two versions | [
"Compares",
"two",
"versions"
] | 5bbef35e463eda6dc67b0c34d3633a5a1c75a932 | https://github.com/jpgxs/pyopsview/blob/5bbef35e463eda6dc67b0c34d3633a5a1c75a932/pyopsview/utils.py#L52-L60 | train |
uw-it-aca/uw-restclients-core | restclients_core/models/__init__.py | MockHTTP.getheader | def getheader(self, field, default=''):
"""
Returns the HTTP response header field, case insensitively
"""
if self.headers:
for header in self.headers:
if field.lower() == header.lower():
return self.headers[header]
return default | python | def getheader(self, field, default=''):
"""
Returns the HTTP response header field, case insensitively
"""
if self.headers:
for header in self.headers:
if field.lower() == header.lower():
return self.headers[header]
return default | [
"def",
"getheader",
"(",
"self",
",",
"field",
",",
"default",
"=",
"''",
")",
":",
"if",
"self",
".",
"headers",
":",
"for",
"header",
"in",
"self",
".",
"headers",
":",
"if",
"field",
".",
"lower",
"(",
")",
"==",
"header",
".",
"lower",
"(",
")",
":",
"return",
"self",
".",
"headers",
"[",
"header",
"]",
"return",
"default"
] | Returns the HTTP response header field, case insensitively | [
"Returns",
"the",
"HTTP",
"response",
"header",
"field",
"case",
"insensitively"
] | fda9380dceb6355ec6a3123e88c9ec66ae992682 | https://github.com/uw-it-aca/uw-restclients-core/blob/fda9380dceb6355ec6a3123e88c9ec66ae992682/restclients_core/models/__init__.py#L30-L39 | train |
camptocamp/Studio | studio/lib/buildjs/jsmin.py | isAlphanum | def isAlphanum(c):
"""return true if the character is a letter, digit, underscore,
dollar sign, or non-ASCII character.
"""
return ((c >= 'a' and c <= 'z') or (c >= '0' and c <= '9') or
(c >= 'A' and c <= 'Z') or c == '_' or c == '$' or c == '\\' or (c is not None and ord(c) > 126)); | python | def isAlphanum(c):
"""return true if the character is a letter, digit, underscore,
dollar sign, or non-ASCII character.
"""
return ((c >= 'a' and c <= 'z') or (c >= '0' and c <= '9') or
(c >= 'A' and c <= 'Z') or c == '_' or c == '$' or c == '\\' or (c is not None and ord(c) > 126)); | [
"def",
"isAlphanum",
"(",
"c",
")",
":",
"return",
"(",
"(",
"c",
">=",
"'a'",
"and",
"c",
"<=",
"'z'",
")",
"or",
"(",
"c",
">=",
"'0'",
"and",
"c",
"<=",
"'9'",
")",
"or",
"(",
"c",
">=",
"'A'",
"and",
"c",
"<=",
"'Z'",
")",
"or",
"c",
"==",
"'_'",
"or",
"c",
"==",
"'$'",
"or",
"c",
"==",
"'\\\\'",
"or",
"(",
"c",
"is",
"not",
"None",
"and",
"ord",
"(",
"c",
")",
">",
"126",
")",
")"
] | return true if the character is a letter, digit, underscore,
dollar sign, or non-ASCII character. | [
"return",
"true",
"if",
"the",
"character",
"is",
"a",
"letter",
"digit",
"underscore",
"dollar",
"sign",
"or",
"non",
"-",
"ASCII",
"character",
"."
] | 43cb7298434fb606b15136801b79b03571a2f27e | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/lib/buildjs/jsmin.py#L63-L68 | train |
camptocamp/Studio | studio/lib/buildjs/jsmin.py | JavascriptMinify._get | def _get(self):
"""return the next character from stdin. Watch out for lookahead. If
the character is a control character, translate it to a space or
linefeed.
"""
c = self.theLookahead
self.theLookahead = None
if c == None:
c = self.instream.read(1)
if c >= ' ' or c == '\n':
return c
if c == '': # EOF
return '\000'
if c == '\r':
return '\n'
return ' ' | python | def _get(self):
"""return the next character from stdin. Watch out for lookahead. If
the character is a control character, translate it to a space or
linefeed.
"""
c = self.theLookahead
self.theLookahead = None
if c == None:
c = self.instream.read(1)
if c >= ' ' or c == '\n':
return c
if c == '': # EOF
return '\000'
if c == '\r':
return '\n'
return ' ' | [
"def",
"_get",
"(",
"self",
")",
":",
"c",
"=",
"self",
".",
"theLookahead",
"self",
".",
"theLookahead",
"=",
"None",
"if",
"c",
"==",
"None",
":",
"c",
"=",
"self",
".",
"instream",
".",
"read",
"(",
"1",
")",
"if",
"c",
">=",
"' '",
"or",
"c",
"==",
"'\\n'",
":",
"return",
"c",
"if",
"c",
"==",
"''",
":",
"# EOF",
"return",
"'\\000'",
"if",
"c",
"==",
"'\\r'",
":",
"return",
"'\\n'",
"return",
"' '"
] | return the next character from stdin. Watch out for lookahead. If
the character is a control character, translate it to a space or
linefeed. | [
"return",
"the",
"next",
"character",
"from",
"stdin",
".",
"Watch",
"out",
"for",
"lookahead",
".",
"If",
"the",
"character",
"is",
"a",
"control",
"character",
"translate",
"it",
"to",
"a",
"space",
"or",
"linefeed",
"."
] | 43cb7298434fb606b15136801b79b03571a2f27e | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/lib/buildjs/jsmin.py#L86-L101 | train |
camptocamp/Studio | studio/lib/buildjs/jsmin.py | JavascriptMinify._jsmin | def _jsmin(self):
"""Copy the input to the output, deleting the characters which are
insignificant to JavaScript. Comments will be removed. Tabs will be
replaced with spaces. Carriage returns will be replaced with linefeeds.
Most spaces and linefeeds will be removed.
"""
self.theA = '\n'
self._action(3)
while self.theA != '\000':
if self.theA == ' ':
if isAlphanum(self.theB):
self._action(1)
else:
self._action(2)
elif self.theA == '\n':
if self.theB in ['{', '[', '(', '+', '-']:
self._action(1)
elif self.theB == ' ':
self._action(3)
else:
if isAlphanum(self.theB):
self._action(1)
else:
self._action(2)
else:
if self.theB == ' ':
if isAlphanum(self.theA):
self._action(1)
else:
self._action(3)
elif self.theB == '\n':
if self.theA in ['}', ']', ')', '+', '-', '"', '\'']:
self._action(1)
else:
if isAlphanum(self.theA):
self._action(1)
else:
self._action(3)
else:
self._action(1) | python | def _jsmin(self):
"""Copy the input to the output, deleting the characters which are
insignificant to JavaScript. Comments will be removed. Tabs will be
replaced with spaces. Carriage returns will be replaced with linefeeds.
Most spaces and linefeeds will be removed.
"""
self.theA = '\n'
self._action(3)
while self.theA != '\000':
if self.theA == ' ':
if isAlphanum(self.theB):
self._action(1)
else:
self._action(2)
elif self.theA == '\n':
if self.theB in ['{', '[', '(', '+', '-']:
self._action(1)
elif self.theB == ' ':
self._action(3)
else:
if isAlphanum(self.theB):
self._action(1)
else:
self._action(2)
else:
if self.theB == ' ':
if isAlphanum(self.theA):
self._action(1)
else:
self._action(3)
elif self.theB == '\n':
if self.theA in ['}', ']', ')', '+', '-', '"', '\'']:
self._action(1)
else:
if isAlphanum(self.theA):
self._action(1)
else:
self._action(3)
else:
self._action(1) | [
"def",
"_jsmin",
"(",
"self",
")",
":",
"self",
".",
"theA",
"=",
"'\\n'",
"self",
".",
"_action",
"(",
"3",
")",
"while",
"self",
".",
"theA",
"!=",
"'\\000'",
":",
"if",
"self",
".",
"theA",
"==",
"' '",
":",
"if",
"isAlphanum",
"(",
"self",
".",
"theB",
")",
":",
"self",
".",
"_action",
"(",
"1",
")",
"else",
":",
"self",
".",
"_action",
"(",
"2",
")",
"elif",
"self",
".",
"theA",
"==",
"'\\n'",
":",
"if",
"self",
".",
"theB",
"in",
"[",
"'{'",
",",
"'['",
",",
"'('",
",",
"'+'",
",",
"'-'",
"]",
":",
"self",
".",
"_action",
"(",
"1",
")",
"elif",
"self",
".",
"theB",
"==",
"' '",
":",
"self",
".",
"_action",
"(",
"3",
")",
"else",
":",
"if",
"isAlphanum",
"(",
"self",
".",
"theB",
")",
":",
"self",
".",
"_action",
"(",
"1",
")",
"else",
":",
"self",
".",
"_action",
"(",
"2",
")",
"else",
":",
"if",
"self",
".",
"theB",
"==",
"' '",
":",
"if",
"isAlphanum",
"(",
"self",
".",
"theA",
")",
":",
"self",
".",
"_action",
"(",
"1",
")",
"else",
":",
"self",
".",
"_action",
"(",
"3",
")",
"elif",
"self",
".",
"theB",
"==",
"'\\n'",
":",
"if",
"self",
".",
"theA",
"in",
"[",
"'}'",
",",
"']'",
",",
"')'",
",",
"'+'",
",",
"'-'",
",",
"'\"'",
",",
"'\\''",
"]",
":",
"self",
".",
"_action",
"(",
"1",
")",
"else",
":",
"if",
"isAlphanum",
"(",
"self",
".",
"theA",
")",
":",
"self",
".",
"_action",
"(",
"1",
")",
"else",
":",
"self",
".",
"_action",
"(",
"3",
")",
"else",
":",
"self",
".",
"_action",
"(",
"1",
")"
] | Copy the input to the output, deleting the characters which are
insignificant to JavaScript. Comments will be removed. Tabs will be
replaced with spaces. Carriage returns will be replaced with linefeeds.
Most spaces and linefeeds will be removed. | [
"Copy",
"the",
"input",
"to",
"the",
"output",
"deleting",
"the",
"characters",
"which",
"are",
"insignificant",
"to",
"JavaScript",
".",
"Comments",
"will",
"be",
"removed",
".",
"Tabs",
"will",
"be",
"replaced",
"with",
"spaces",
".",
"Carriage",
"returns",
"will",
"be",
"replaced",
"with",
"linefeeds",
".",
"Most",
"spaces",
"and",
"linefeeds",
"will",
"be",
"removed",
"."
] | 43cb7298434fb606b15136801b79b03571a2f27e | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/lib/buildjs/jsmin.py#L180-L220 | train |
camptocamp/Studio | studio/controllers/layertemplates.py | LayertemplatesController._get_lts_from_user | def _get_lts_from_user(self, user):
""" Get layertemplates owned by a user from the database. """
req = meta.Session.query(LayerTemplate).select_from(join(LayerTemplate, User))
return req.filter(User.login==user).all() | python | def _get_lts_from_user(self, user):
""" Get layertemplates owned by a user from the database. """
req = meta.Session.query(LayerTemplate).select_from(join(LayerTemplate, User))
return req.filter(User.login==user).all() | [
"def",
"_get_lts_from_user",
"(",
"self",
",",
"user",
")",
":",
"req",
"=",
"meta",
".",
"Session",
".",
"query",
"(",
"LayerTemplate",
")",
".",
"select_from",
"(",
"join",
"(",
"LayerTemplate",
",",
"User",
")",
")",
"return",
"req",
".",
"filter",
"(",
"User",
".",
"login",
"==",
"user",
")",
".",
"all",
"(",
")"
] | Get layertemplates owned by a user from the database. | [
"Get",
"layertemplates",
"owned",
"by",
"a",
"user",
"from",
"the",
"database",
"."
] | 43cb7298434fb606b15136801b79b03571a2f27e | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/controllers/layertemplates.py#L121-L124 | train |
camptocamp/Studio | studio/controllers/layertemplates.py | LayertemplatesController._get_lt_from_user_by_id | def _get_lt_from_user_by_id(self, user, lt_id):
""" Get a layertemplate owned by a user from the database by lt_id. """
req = meta.Session.query(LayerTemplate).select_from(join(LayerTemplate, User))
try:
return req.filter(and_(User.login==user, LayerTemplate.id==lt_id)).one()
except Exception, e:
return None | python | def _get_lt_from_user_by_id(self, user, lt_id):
""" Get a layertemplate owned by a user from the database by lt_id. """
req = meta.Session.query(LayerTemplate).select_from(join(LayerTemplate, User))
try:
return req.filter(and_(User.login==user, LayerTemplate.id==lt_id)).one()
except Exception, e:
return None | [
"def",
"_get_lt_from_user_by_id",
"(",
"self",
",",
"user",
",",
"lt_id",
")",
":",
"req",
"=",
"meta",
".",
"Session",
".",
"query",
"(",
"LayerTemplate",
")",
".",
"select_from",
"(",
"join",
"(",
"LayerTemplate",
",",
"User",
")",
")",
"try",
":",
"return",
"req",
".",
"filter",
"(",
"and_",
"(",
"User",
".",
"login",
"==",
"user",
",",
"LayerTemplate",
".",
"id",
"==",
"lt_id",
")",
")",
".",
"one",
"(",
")",
"except",
"Exception",
",",
"e",
":",
"return",
"None"
] | Get a layertemplate owned by a user from the database by lt_id. | [
"Get",
"a",
"layertemplate",
"owned",
"by",
"a",
"user",
"from",
"the",
"database",
"by",
"lt_id",
"."
] | 43cb7298434fb606b15136801b79b03571a2f27e | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/controllers/layertemplates.py#L126-L132 | train |
MoseleyBioinformaticsLab/mwtab | mwtab/tokenizer.py | tokenizer | def tokenizer(text):
"""A lexical analyzer for the `mwtab` formatted files.
:param str text: `mwtab` formatted text.
:return: Tuples of data.
:rtype: py:class:`~collections.namedtuple`
"""
stream = deque(text.split("\n"))
while len(stream) > 0:
line = stream.popleft()
if line.startswith("#METABOLOMICS WORKBENCH"):
yield KeyValue("#METABOLOMICS WORKBENCH", "\n")
yield KeyValue("HEADER", line)
for identifier in line.split(" "):
if ":" in identifier:
key, value = identifier.split(":")
yield KeyValue(key, value)
elif line.startswith("#ANALYSIS TYPE"):
yield KeyValue("HEADER", line)
elif line.startswith("#SUBJECT_SAMPLE_FACTORS:"):
yield KeyValue("#ENDSECTION", "\n")
yield KeyValue("#SUBJECT_SAMPLE_FACTORS", "\n")
elif line.startswith("#"):
yield KeyValue("#ENDSECTION", "\n")
yield KeyValue(line.strip(), "\n")
elif line.startswith("SUBJECT_SAMPLE_FACTORS"):
key, subject_type, local_sample_id, factors, additional_sample_data = line.split("\t")
# factors = [dict([[i.strip() for i in f.split(":")]]) for f in factors.split("|")]
yield SubjectSampleFactors(key.strip(), subject_type, local_sample_id, factors, additional_sample_data)
elif line.endswith("_START"):
yield KeyValue(line, "\n")
while not line.endswith("_END"):
line = stream.popleft()
if line.endswith("_END"):
yield KeyValue(line.strip(), "\n")
else:
data = line.split("\t")
yield KeyValue(data[0], tuple(data))
else:
if line:
if line.startswith("MS:MS_RESULTS_FILE") or line.startswith("NM:NMR_RESULTS_FILE"):
try:
key, value, extra = line.split("\t")
extra_key, extra_value = extra.strip().split(":")
yield KeyValueExtra(key.strip()[3:], value, extra_key, extra_value)
except ValueError:
key, value = line.split("\t")
yield KeyValue(key.strip()[3:], value)
else:
try:
key, value = line.split("\t")
if ":" in key:
if key.startswith("MS_METABOLITE_DATA:UNITS"):
yield KeyValue(key.strip(), value)
else:
yield KeyValue(key.strip()[3:], value)
else:
yield KeyValue(key.strip(), value)
except ValueError:
print("LINE WITH ERROR:\n\t", repr(line))
raise
yield KeyValue("#ENDSECTION", "\n")
yield KeyValue("!#ENDFILE", "\n") | python | def tokenizer(text):
"""A lexical analyzer for the `mwtab` formatted files.
:param str text: `mwtab` formatted text.
:return: Tuples of data.
:rtype: py:class:`~collections.namedtuple`
"""
stream = deque(text.split("\n"))
while len(stream) > 0:
line = stream.popleft()
if line.startswith("#METABOLOMICS WORKBENCH"):
yield KeyValue("#METABOLOMICS WORKBENCH", "\n")
yield KeyValue("HEADER", line)
for identifier in line.split(" "):
if ":" in identifier:
key, value = identifier.split(":")
yield KeyValue(key, value)
elif line.startswith("#ANALYSIS TYPE"):
yield KeyValue("HEADER", line)
elif line.startswith("#SUBJECT_SAMPLE_FACTORS:"):
yield KeyValue("#ENDSECTION", "\n")
yield KeyValue("#SUBJECT_SAMPLE_FACTORS", "\n")
elif line.startswith("#"):
yield KeyValue("#ENDSECTION", "\n")
yield KeyValue(line.strip(), "\n")
elif line.startswith("SUBJECT_SAMPLE_FACTORS"):
key, subject_type, local_sample_id, factors, additional_sample_data = line.split("\t")
# factors = [dict([[i.strip() for i in f.split(":")]]) for f in factors.split("|")]
yield SubjectSampleFactors(key.strip(), subject_type, local_sample_id, factors, additional_sample_data)
elif line.endswith("_START"):
yield KeyValue(line, "\n")
while not line.endswith("_END"):
line = stream.popleft()
if line.endswith("_END"):
yield KeyValue(line.strip(), "\n")
else:
data = line.split("\t")
yield KeyValue(data[0], tuple(data))
else:
if line:
if line.startswith("MS:MS_RESULTS_FILE") or line.startswith("NM:NMR_RESULTS_FILE"):
try:
key, value, extra = line.split("\t")
extra_key, extra_value = extra.strip().split(":")
yield KeyValueExtra(key.strip()[3:], value, extra_key, extra_value)
except ValueError:
key, value = line.split("\t")
yield KeyValue(key.strip()[3:], value)
else:
try:
key, value = line.split("\t")
if ":" in key:
if key.startswith("MS_METABOLITE_DATA:UNITS"):
yield KeyValue(key.strip(), value)
else:
yield KeyValue(key.strip()[3:], value)
else:
yield KeyValue(key.strip(), value)
except ValueError:
print("LINE WITH ERROR:\n\t", repr(line))
raise
yield KeyValue("#ENDSECTION", "\n")
yield KeyValue("!#ENDFILE", "\n") | [
"def",
"tokenizer",
"(",
"text",
")",
":",
"stream",
"=",
"deque",
"(",
"text",
".",
"split",
"(",
"\"\\n\"",
")",
")",
"while",
"len",
"(",
"stream",
")",
">",
"0",
":",
"line",
"=",
"stream",
".",
"popleft",
"(",
")",
"if",
"line",
".",
"startswith",
"(",
"\"#METABOLOMICS WORKBENCH\"",
")",
":",
"yield",
"KeyValue",
"(",
"\"#METABOLOMICS WORKBENCH\"",
",",
"\"\\n\"",
")",
"yield",
"KeyValue",
"(",
"\"HEADER\"",
",",
"line",
")",
"for",
"identifier",
"in",
"line",
".",
"split",
"(",
"\" \"",
")",
":",
"if",
"\":\"",
"in",
"identifier",
":",
"key",
",",
"value",
"=",
"identifier",
".",
"split",
"(",
"\":\"",
")",
"yield",
"KeyValue",
"(",
"key",
",",
"value",
")",
"elif",
"line",
".",
"startswith",
"(",
"\"#ANALYSIS TYPE\"",
")",
":",
"yield",
"KeyValue",
"(",
"\"HEADER\"",
",",
"line",
")",
"elif",
"line",
".",
"startswith",
"(",
"\"#SUBJECT_SAMPLE_FACTORS:\"",
")",
":",
"yield",
"KeyValue",
"(",
"\"#ENDSECTION\"",
",",
"\"\\n\"",
")",
"yield",
"KeyValue",
"(",
"\"#SUBJECT_SAMPLE_FACTORS\"",
",",
"\"\\n\"",
")",
"elif",
"line",
".",
"startswith",
"(",
"\"#\"",
")",
":",
"yield",
"KeyValue",
"(",
"\"#ENDSECTION\"",
",",
"\"\\n\"",
")",
"yield",
"KeyValue",
"(",
"line",
".",
"strip",
"(",
")",
",",
"\"\\n\"",
")",
"elif",
"line",
".",
"startswith",
"(",
"\"SUBJECT_SAMPLE_FACTORS\"",
")",
":",
"key",
",",
"subject_type",
",",
"local_sample_id",
",",
"factors",
",",
"additional_sample_data",
"=",
"line",
".",
"split",
"(",
"\"\\t\"",
")",
"# factors = [dict([[i.strip() for i in f.split(\":\")]]) for f in factors.split(\"|\")]",
"yield",
"SubjectSampleFactors",
"(",
"key",
".",
"strip",
"(",
")",
",",
"subject_type",
",",
"local_sample_id",
",",
"factors",
",",
"additional_sample_data",
")",
"elif",
"line",
".",
"endswith",
"(",
"\"_START\"",
")",
":",
"yield",
"KeyValue",
"(",
"line",
",",
"\"\\n\"",
")",
"while",
"not",
"line",
".",
"endswith",
"(",
"\"_END\"",
")",
":",
"line",
"=",
"stream",
".",
"popleft",
"(",
")",
"if",
"line",
".",
"endswith",
"(",
"\"_END\"",
")",
":",
"yield",
"KeyValue",
"(",
"line",
".",
"strip",
"(",
")",
",",
"\"\\n\"",
")",
"else",
":",
"data",
"=",
"line",
".",
"split",
"(",
"\"\\t\"",
")",
"yield",
"KeyValue",
"(",
"data",
"[",
"0",
"]",
",",
"tuple",
"(",
"data",
")",
")",
"else",
":",
"if",
"line",
":",
"if",
"line",
".",
"startswith",
"(",
"\"MS:MS_RESULTS_FILE\"",
")",
"or",
"line",
".",
"startswith",
"(",
"\"NM:NMR_RESULTS_FILE\"",
")",
":",
"try",
":",
"key",
",",
"value",
",",
"extra",
"=",
"line",
".",
"split",
"(",
"\"\\t\"",
")",
"extra_key",
",",
"extra_value",
"=",
"extra",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\":\"",
")",
"yield",
"KeyValueExtra",
"(",
"key",
".",
"strip",
"(",
")",
"[",
"3",
":",
"]",
",",
"value",
",",
"extra_key",
",",
"extra_value",
")",
"except",
"ValueError",
":",
"key",
",",
"value",
"=",
"line",
".",
"split",
"(",
"\"\\t\"",
")",
"yield",
"KeyValue",
"(",
"key",
".",
"strip",
"(",
")",
"[",
"3",
":",
"]",
",",
"value",
")",
"else",
":",
"try",
":",
"key",
",",
"value",
"=",
"line",
".",
"split",
"(",
"\"\\t\"",
")",
"if",
"\":\"",
"in",
"key",
":",
"if",
"key",
".",
"startswith",
"(",
"\"MS_METABOLITE_DATA:UNITS\"",
")",
":",
"yield",
"KeyValue",
"(",
"key",
".",
"strip",
"(",
")",
",",
"value",
")",
"else",
":",
"yield",
"KeyValue",
"(",
"key",
".",
"strip",
"(",
")",
"[",
"3",
":",
"]",
",",
"value",
")",
"else",
":",
"yield",
"KeyValue",
"(",
"key",
".",
"strip",
"(",
")",
",",
"value",
")",
"except",
"ValueError",
":",
"print",
"(",
"\"LINE WITH ERROR:\\n\\t\"",
",",
"repr",
"(",
"line",
")",
")",
"raise",
"yield",
"KeyValue",
"(",
"\"#ENDSECTION\"",
",",
"\"\\n\"",
")",
"yield",
"KeyValue",
"(",
"\"!#ENDFILE\"",
",",
"\"\\n\"",
")"
] | A lexical analyzer for the `mwtab` formatted files.
:param str text: `mwtab` formatted text.
:return: Tuples of data.
:rtype: py:class:`~collections.namedtuple` | [
"A",
"lexical",
"analyzer",
"for",
"the",
"mwtab",
"formatted",
"files",
"."
] | 8c0ae8ab2aa621662f99589ed41e481cf8b7152b | https://github.com/MoseleyBioinformaticsLab/mwtab/blob/8c0ae8ab2aa621662f99589ed41e481cf8b7152b/mwtab/tokenizer.py#L28-L102 | train |
camptocamp/Studio | studio/controllers/mapfiles.py | MapfilesController._get_map_from_user_by_id | def _get_map_from_user_by_id(self, user, map_id):
""" Get a mapfile owned by a user from the database by
map_id. """
req = Session.query(Map).select_from(join(Map, User))
try:
return req.filter(and_(User.login==user, Map.id==map_id)).one()
except Exception, e:
return None | python | def _get_map_from_user_by_id(self, user, map_id):
""" Get a mapfile owned by a user from the database by
map_id. """
req = Session.query(Map).select_from(join(Map, User))
try:
return req.filter(and_(User.login==user, Map.id==map_id)).one()
except Exception, e:
return None | [
"def",
"_get_map_from_user_by_id",
"(",
"self",
",",
"user",
",",
"map_id",
")",
":",
"req",
"=",
"Session",
".",
"query",
"(",
"Map",
")",
".",
"select_from",
"(",
"join",
"(",
"Map",
",",
"User",
")",
")",
"try",
":",
"return",
"req",
".",
"filter",
"(",
"and_",
"(",
"User",
".",
"login",
"==",
"user",
",",
"Map",
".",
"id",
"==",
"map_id",
")",
")",
".",
"one",
"(",
")",
"except",
"Exception",
",",
"e",
":",
"return",
"None"
] | Get a mapfile owned by a user from the database by
map_id. | [
"Get",
"a",
"mapfile",
"owned",
"by",
"a",
"user",
"from",
"the",
"database",
"by",
"map_id",
"."
] | 43cb7298434fb606b15136801b79b03571a2f27e | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/controllers/mapfiles.py#L197-L204 | train |
camptocamp/Studio | studio/controllers/mapfiles.py | MapfilesController._get_maps_from_user | def _get_maps_from_user(self, user):
""" Get mapfiles owned by a user from the database. """
req = Session.query(Map).select_from(join(Map, User))
return req.filter(User.login==user).all() | python | def _get_maps_from_user(self, user):
""" Get mapfiles owned by a user from the database. """
req = Session.query(Map).select_from(join(Map, User))
return req.filter(User.login==user).all() | [
"def",
"_get_maps_from_user",
"(",
"self",
",",
"user",
")",
":",
"req",
"=",
"Session",
".",
"query",
"(",
"Map",
")",
".",
"select_from",
"(",
"join",
"(",
"Map",
",",
"User",
")",
")",
"return",
"req",
".",
"filter",
"(",
"User",
".",
"login",
"==",
"user",
")",
".",
"all",
"(",
")"
] | Get mapfiles owned by a user from the database. | [
"Get",
"mapfiles",
"owned",
"by",
"a",
"user",
"from",
"the",
"database",
"."
] | 43cb7298434fb606b15136801b79b03571a2f27e | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/controllers/mapfiles.py#L206-L209 | train |
camptocamp/Studio | studio/controllers/mapfiles.py | MapfilesController._new_map_from_user | def _new_map_from_user(self, user, name, filepath):
""" Create a new mapfile entry in database. """
map = Map(name, filepath)
map.user = Session.query(User).filter(User.login==user).one()
Session.add(map)
Session.commit()
return map | python | def _new_map_from_user(self, user, name, filepath):
""" Create a new mapfile entry in database. """
map = Map(name, filepath)
map.user = Session.query(User).filter(User.login==user).one()
Session.add(map)
Session.commit()
return map | [
"def",
"_new_map_from_user",
"(",
"self",
",",
"user",
",",
"name",
",",
"filepath",
")",
":",
"map",
"=",
"Map",
"(",
"name",
",",
"filepath",
")",
"map",
".",
"user",
"=",
"Session",
".",
"query",
"(",
"User",
")",
".",
"filter",
"(",
"User",
".",
"login",
"==",
"user",
")",
".",
"one",
"(",
")",
"Session",
".",
"add",
"(",
"map",
")",
"Session",
".",
"commit",
"(",
")",
"return",
"map"
] | Create a new mapfile entry in database. | [
"Create",
"a",
"new",
"mapfile",
"entry",
"in",
"database",
"."
] | 43cb7298434fb606b15136801b79b03571a2f27e | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/controllers/mapfiles.py#L228-L234 | train |
camptocamp/Studio | studio/controllers/mapfiles.py | MapfilesController._proxy | def _proxy(self, url, urlparams=None):
"""Do the actual action of proxying the call.
"""
for k,v in request.params.iteritems():
urlparams[k]=v
query = urlencode(urlparams)
full_url = url
if query:
if not full_url.endswith("?"):
full_url += "?"
full_url += query
# build the request with its headers
req = urllib2.Request(url=full_url)
for header in request.headers:
if header.lower() == "host":
req.add_header(header, urlparse.urlparse(url)[1])
else:
req.add_header(header, request.headers[header])
res = urllib2.urlopen(req)
# add response headers
i = res.info()
response.status = res.code
got_content_length = False
for header in i:
# We don't support serving the result as chunked
if header.lower() == "transfer-encoding":
continue
if header.lower() == "content-length":
got_content_length = True
response.headers[header] = i[header]
# return the result
result = res.read()
res.close()
#if not got_content_length:
# response.headers['content-length'] = str(len(result))
return result | python | def _proxy(self, url, urlparams=None):
"""Do the actual action of proxying the call.
"""
for k,v in request.params.iteritems():
urlparams[k]=v
query = urlencode(urlparams)
full_url = url
if query:
if not full_url.endswith("?"):
full_url += "?"
full_url += query
# build the request with its headers
req = urllib2.Request(url=full_url)
for header in request.headers:
if header.lower() == "host":
req.add_header(header, urlparse.urlparse(url)[1])
else:
req.add_header(header, request.headers[header])
res = urllib2.urlopen(req)
# add response headers
i = res.info()
response.status = res.code
got_content_length = False
for header in i:
# We don't support serving the result as chunked
if header.lower() == "transfer-encoding":
continue
if header.lower() == "content-length":
got_content_length = True
response.headers[header] = i[header]
# return the result
result = res.read()
res.close()
#if not got_content_length:
# response.headers['content-length'] = str(len(result))
return result | [
"def",
"_proxy",
"(",
"self",
",",
"url",
",",
"urlparams",
"=",
"None",
")",
":",
"for",
"k",
",",
"v",
"in",
"request",
".",
"params",
".",
"iteritems",
"(",
")",
":",
"urlparams",
"[",
"k",
"]",
"=",
"v",
"query",
"=",
"urlencode",
"(",
"urlparams",
")",
"full_url",
"=",
"url",
"if",
"query",
":",
"if",
"not",
"full_url",
".",
"endswith",
"(",
"\"?\"",
")",
":",
"full_url",
"+=",
"\"?\"",
"full_url",
"+=",
"query",
"# build the request with its headers",
"req",
"=",
"urllib2",
".",
"Request",
"(",
"url",
"=",
"full_url",
")",
"for",
"header",
"in",
"request",
".",
"headers",
":",
"if",
"header",
".",
"lower",
"(",
")",
"==",
"\"host\"",
":",
"req",
".",
"add_header",
"(",
"header",
",",
"urlparse",
".",
"urlparse",
"(",
"url",
")",
"[",
"1",
"]",
")",
"else",
":",
"req",
".",
"add_header",
"(",
"header",
",",
"request",
".",
"headers",
"[",
"header",
"]",
")",
"res",
"=",
"urllib2",
".",
"urlopen",
"(",
"req",
")",
"# add response headers",
"i",
"=",
"res",
".",
"info",
"(",
")",
"response",
".",
"status",
"=",
"res",
".",
"code",
"got_content_length",
"=",
"False",
"for",
"header",
"in",
"i",
":",
"# We don't support serving the result as chunked",
"if",
"header",
".",
"lower",
"(",
")",
"==",
"\"transfer-encoding\"",
":",
"continue",
"if",
"header",
".",
"lower",
"(",
")",
"==",
"\"content-length\"",
":",
"got_content_length",
"=",
"True",
"response",
".",
"headers",
"[",
"header",
"]",
"=",
"i",
"[",
"header",
"]",
"# return the result",
"result",
"=",
"res",
".",
"read",
"(",
")",
"res",
".",
"close",
"(",
")",
"#if not got_content_length:",
"# response.headers['content-length'] = str(len(result))",
"return",
"result"
] | Do the actual action of proxying the call. | [
"Do",
"the",
"actual",
"action",
"of",
"proxying",
"the",
"call",
"."
] | 43cb7298434fb606b15136801b79b03571a2f27e | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/controllers/mapfiles.py#L236-L275 | train |
uw-it-aca/uw-restclients-core | restclients_core/util/mock.py | open_file | def open_file(orig_file_path):
"""
Taking in a file path, attempt to open mock data files with it.
"""
unquoted = unquote(orig_file_path)
paths = [
convert_to_platform_safe(orig_file_path),
"%s/index.html" % (convert_to_platform_safe(orig_file_path)),
orig_file_path,
"%s/index.html" % orig_file_path,
convert_to_platform_safe(unquoted),
"%s/index.html" % (convert_to_platform_safe(unquoted)),
unquoted,
"%s/index.html" % unquoted,
]
file_path = None
handle = None
for path in paths:
try:
file_path = path
handle = open(path, "rb")
break
except IOError:
pass
return handle | python | def open_file(orig_file_path):
"""
Taking in a file path, attempt to open mock data files with it.
"""
unquoted = unquote(orig_file_path)
paths = [
convert_to_platform_safe(orig_file_path),
"%s/index.html" % (convert_to_platform_safe(orig_file_path)),
orig_file_path,
"%s/index.html" % orig_file_path,
convert_to_platform_safe(unquoted),
"%s/index.html" % (convert_to_platform_safe(unquoted)),
unquoted,
"%s/index.html" % unquoted,
]
file_path = None
handle = None
for path in paths:
try:
file_path = path
handle = open(path, "rb")
break
except IOError:
pass
return handle | [
"def",
"open_file",
"(",
"orig_file_path",
")",
":",
"unquoted",
"=",
"unquote",
"(",
"orig_file_path",
")",
"paths",
"=",
"[",
"convert_to_platform_safe",
"(",
"orig_file_path",
")",
",",
"\"%s/index.html\"",
"%",
"(",
"convert_to_platform_safe",
"(",
"orig_file_path",
")",
")",
",",
"orig_file_path",
",",
"\"%s/index.html\"",
"%",
"orig_file_path",
",",
"convert_to_platform_safe",
"(",
"unquoted",
")",
",",
"\"%s/index.html\"",
"%",
"(",
"convert_to_platform_safe",
"(",
"unquoted",
")",
")",
",",
"unquoted",
",",
"\"%s/index.html\"",
"%",
"unquoted",
",",
"]",
"file_path",
"=",
"None",
"handle",
"=",
"None",
"for",
"path",
"in",
"paths",
":",
"try",
":",
"file_path",
"=",
"path",
"handle",
"=",
"open",
"(",
"path",
",",
"\"rb\"",
")",
"break",
"except",
"IOError",
":",
"pass",
"return",
"handle"
] | Taking in a file path, attempt to open mock data files with it. | [
"Taking",
"in",
"a",
"file",
"path",
"attempt",
"to",
"open",
"mock",
"data",
"files",
"with",
"it",
"."
] | fda9380dceb6355ec6a3123e88c9ec66ae992682 | https://github.com/uw-it-aca/uw-restclients-core/blob/fda9380dceb6355ec6a3123e88c9ec66ae992682/restclients_core/util/mock.py#L84-L110 | train |
uw-it-aca/uw-restclients-core | restclients_core/util/mock.py | attempt_open_query_permutations | def attempt_open_query_permutations(url, orig_file_path, is_header_file):
"""
Attempt to open a given mock data file with different permutations of the
query parameters
"""
directory = dirname(convert_to_platform_safe(orig_file_path)) + "/"
# get all filenames in directory
try:
filenames = [f for f in os.listdir(directory)
if isfile(join(directory, f))]
except OSError:
return
# ensure that there are not extra parameters on any files
if is_header_file:
filenames = [f for f in filenames if ".http-headers" in f]
filenames = [f for f in filenames if
_compare_file_name(orig_file_path + ".http-headers",
directory,
f)]
else:
filenames = [f for f in filenames if ".http-headers" not in f]
filenames = [f for f in filenames if _compare_file_name(orig_file_path,
directory,
f)]
url_parts = url.split("/")
url_parts = url_parts[len(url_parts) - 1].split("?")
base = url_parts[0]
params = url_parts[1]
params = params.split("&")
# check to ensure that the base url matches
filenames = [f for f in filenames if f.startswith(base)]
params = [convert_to_platform_safe(unquote(p)) for p in params]
# ensure that all parameters are there
for param in params:
filenames = [f for f in filenames if param in f]
# if we only have one file, return it
if len(filenames) == 1:
path = join(directory, filenames[0])
return open_file(path)
# if there is more than one file, raise an exception
if len(filenames) > 1:
raise DataFailureException(url,
"Multiple mock data files matched the " +
"parameters provided!",
404) | python | def attempt_open_query_permutations(url, orig_file_path, is_header_file):
"""
Attempt to open a given mock data file with different permutations of the
query parameters
"""
directory = dirname(convert_to_platform_safe(orig_file_path)) + "/"
# get all filenames in directory
try:
filenames = [f for f in os.listdir(directory)
if isfile(join(directory, f))]
except OSError:
return
# ensure that there are not extra parameters on any files
if is_header_file:
filenames = [f for f in filenames if ".http-headers" in f]
filenames = [f for f in filenames if
_compare_file_name(orig_file_path + ".http-headers",
directory,
f)]
else:
filenames = [f for f in filenames if ".http-headers" not in f]
filenames = [f for f in filenames if _compare_file_name(orig_file_path,
directory,
f)]
url_parts = url.split("/")
url_parts = url_parts[len(url_parts) - 1].split("?")
base = url_parts[0]
params = url_parts[1]
params = params.split("&")
# check to ensure that the base url matches
filenames = [f for f in filenames if f.startswith(base)]
params = [convert_to_platform_safe(unquote(p)) for p in params]
# ensure that all parameters are there
for param in params:
filenames = [f for f in filenames if param in f]
# if we only have one file, return it
if len(filenames) == 1:
path = join(directory, filenames[0])
return open_file(path)
# if there is more than one file, raise an exception
if len(filenames) > 1:
raise DataFailureException(url,
"Multiple mock data files matched the " +
"parameters provided!",
404) | [
"def",
"attempt_open_query_permutations",
"(",
"url",
",",
"orig_file_path",
",",
"is_header_file",
")",
":",
"directory",
"=",
"dirname",
"(",
"convert_to_platform_safe",
"(",
"orig_file_path",
")",
")",
"+",
"\"/\"",
"# get all filenames in directory",
"try",
":",
"filenames",
"=",
"[",
"f",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"directory",
")",
"if",
"isfile",
"(",
"join",
"(",
"directory",
",",
"f",
")",
")",
"]",
"except",
"OSError",
":",
"return",
"# ensure that there are not extra parameters on any files",
"if",
"is_header_file",
":",
"filenames",
"=",
"[",
"f",
"for",
"f",
"in",
"filenames",
"if",
"\".http-headers\"",
"in",
"f",
"]",
"filenames",
"=",
"[",
"f",
"for",
"f",
"in",
"filenames",
"if",
"_compare_file_name",
"(",
"orig_file_path",
"+",
"\".http-headers\"",
",",
"directory",
",",
"f",
")",
"]",
"else",
":",
"filenames",
"=",
"[",
"f",
"for",
"f",
"in",
"filenames",
"if",
"\".http-headers\"",
"not",
"in",
"f",
"]",
"filenames",
"=",
"[",
"f",
"for",
"f",
"in",
"filenames",
"if",
"_compare_file_name",
"(",
"orig_file_path",
",",
"directory",
",",
"f",
")",
"]",
"url_parts",
"=",
"url",
".",
"split",
"(",
"\"/\"",
")",
"url_parts",
"=",
"url_parts",
"[",
"len",
"(",
"url_parts",
")",
"-",
"1",
"]",
".",
"split",
"(",
"\"?\"",
")",
"base",
"=",
"url_parts",
"[",
"0",
"]",
"params",
"=",
"url_parts",
"[",
"1",
"]",
"params",
"=",
"params",
".",
"split",
"(",
"\"&\"",
")",
"# check to ensure that the base url matches",
"filenames",
"=",
"[",
"f",
"for",
"f",
"in",
"filenames",
"if",
"f",
".",
"startswith",
"(",
"base",
")",
"]",
"params",
"=",
"[",
"convert_to_platform_safe",
"(",
"unquote",
"(",
"p",
")",
")",
"for",
"p",
"in",
"params",
"]",
"# ensure that all parameters are there",
"for",
"param",
"in",
"params",
":",
"filenames",
"=",
"[",
"f",
"for",
"f",
"in",
"filenames",
"if",
"param",
"in",
"f",
"]",
"# if we only have one file, return it",
"if",
"len",
"(",
"filenames",
")",
"==",
"1",
":",
"path",
"=",
"join",
"(",
"directory",
",",
"filenames",
"[",
"0",
"]",
")",
"return",
"open_file",
"(",
"path",
")",
"# if there is more than one file, raise an exception",
"if",
"len",
"(",
"filenames",
")",
">",
"1",
":",
"raise",
"DataFailureException",
"(",
"url",
",",
"\"Multiple mock data files matched the \"",
"+",
"\"parameters provided!\"",
",",
"404",
")"
] | Attempt to open a given mock data file with different permutations of the
query parameters | [
"Attempt",
"to",
"open",
"a",
"given",
"mock",
"data",
"file",
"with",
"different",
"permutations",
"of",
"the",
"query",
"parameters"
] | fda9380dceb6355ec6a3123e88c9ec66ae992682 | https://github.com/uw-it-aca/uw-restclients-core/blob/fda9380dceb6355ec6a3123e88c9ec66ae992682/restclients_core/util/mock.py#L113-L167 | train |
camptocamp/Studio | studio/lib/mapscriptutils.py | msConstants.lookup | def lookup(self,value):
""" return the first key in dict where value is name """
for k,v in self.iteritems():
if value == v:
return k
return None | python | def lookup(self,value):
""" return the first key in dict where value is name """
for k,v in self.iteritems():
if value == v:
return k
return None | [
"def",
"lookup",
"(",
"self",
",",
"value",
")",
":",
"for",
"k",
",",
"v",
"in",
"self",
".",
"iteritems",
"(",
")",
":",
"if",
"value",
"==",
"v",
":",
"return",
"k",
"return",
"None"
] | return the first key in dict where value is name | [
"return",
"the",
"first",
"key",
"in",
"dict",
"where",
"value",
"is",
"name"
] | 43cb7298434fb606b15136801b79b03571a2f27e | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/lib/mapscriptutils.py#L28-L33 | train |
SergeySatskiy/cdm-pythonparser | legacy/src/cdmbriefparser.py | ModuleInfoBase._getLPA | def _getLPA( self ):
" Provides line, pos and absPosition line as string "
return str( self.line ) + ":" + \
str( self.pos ) + ":" + \
str( self.absPosition ) | python | def _getLPA( self ):
" Provides line, pos and absPosition line as string "
return str( self.line ) + ":" + \
str( self.pos ) + ":" + \
str( self.absPosition ) | [
"def",
"_getLPA",
"(",
"self",
")",
":",
"return",
"str",
"(",
"self",
".",
"line",
")",
"+",
"\":\"",
"+",
"str",
"(",
"self",
".",
"pos",
")",
"+",
"\":\"",
"+",
"str",
"(",
"self",
".",
"absPosition",
")"
] | Provides line, pos and absPosition line as string | [
"Provides",
"line",
"pos",
"and",
"absPosition",
"line",
"as",
"string"
] | 7e933aca899b1853d744082313ffc3a8b1154505 | https://github.com/SergeySatskiy/cdm-pythonparser/blob/7e933aca899b1853d744082313ffc3a8b1154505/legacy/src/cdmbriefparser.py#L91-L95 | train |
SergeySatskiy/cdm-pythonparser | legacy/src/cdmbriefparser.py | BriefModuleInfo._onImport | def _onImport( self, name, line, pos, absPosition ):
" Memorizes an import "
if self.__lastImport is not None:
self.imports.append( self.__lastImport )
self.__lastImport = Import( name, line, pos, absPosition )
return | python | def _onImport( self, name, line, pos, absPosition ):
" Memorizes an import "
if self.__lastImport is not None:
self.imports.append( self.__lastImport )
self.__lastImport = Import( name, line, pos, absPosition )
return | [
"def",
"_onImport",
"(",
"self",
",",
"name",
",",
"line",
",",
"pos",
",",
"absPosition",
")",
":",
"if",
"self",
".",
"__lastImport",
"is",
"not",
"None",
":",
"self",
".",
"imports",
".",
"append",
"(",
"self",
".",
"__lastImport",
")",
"self",
".",
"__lastImport",
"=",
"Import",
"(",
"name",
",",
"line",
",",
"pos",
",",
"absPosition",
")",
"return"
] | Memorizes an import | [
"Memorizes",
"an",
"import"
] | 7e933aca899b1853d744082313ffc3a8b1154505 | https://github.com/SergeySatskiy/cdm-pythonparser/blob/7e933aca899b1853d744082313ffc3a8b1154505/legacy/src/cdmbriefparser.py#L497-L502 | train |
SergeySatskiy/cdm-pythonparser | legacy/src/cdmbriefparser.py | BriefModuleInfo._onAs | def _onAs( self, name ):
" Memorizes an alias for an import or an imported item "
if self.__lastImport.what:
self.__lastImport.what[ -1 ].alias = name
else:
self.__lastImport.alias = name
return | python | def _onAs( self, name ):
" Memorizes an alias for an import or an imported item "
if self.__lastImport.what:
self.__lastImport.what[ -1 ].alias = name
else:
self.__lastImport.alias = name
return | [
"def",
"_onAs",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"__lastImport",
".",
"what",
":",
"self",
".",
"__lastImport",
".",
"what",
"[",
"-",
"1",
"]",
".",
"alias",
"=",
"name",
"else",
":",
"self",
".",
"__lastImport",
".",
"alias",
"=",
"name",
"return"
] | Memorizes an alias for an import or an imported item | [
"Memorizes",
"an",
"alias",
"for",
"an",
"import",
"or",
"an",
"imported",
"item"
] | 7e933aca899b1853d744082313ffc3a8b1154505 | https://github.com/SergeySatskiy/cdm-pythonparser/blob/7e933aca899b1853d744082313ffc3a8b1154505/legacy/src/cdmbriefparser.py#L504-L510 | train |
Radi85/Comment | comment/templatetags/comment_tags.py | comment_count | def comment_count(obj):
""" returns the count of comments of an object """
model_object = type(obj).objects.get(id=obj.id)
return model_object.comments.all().count() | python | def comment_count(obj):
""" returns the count of comments of an object """
model_object = type(obj).objects.get(id=obj.id)
return model_object.comments.all().count() | [
"def",
"comment_count",
"(",
"obj",
")",
":",
"model_object",
"=",
"type",
"(",
"obj",
")",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"obj",
".",
"id",
")",
"return",
"model_object",
".",
"comments",
".",
"all",
"(",
")",
".",
"count",
"(",
")"
] | returns the count of comments of an object | [
"returns",
"the",
"count",
"of",
"comments",
"of",
"an",
"object"
] | c3c46afe51228cd7ee4e04f5e6164fff1be3a5bc | https://github.com/Radi85/Comment/blob/c3c46afe51228cd7ee4e04f5e6164fff1be3a5bc/comment/templatetags/comment_tags.py#L25-L28 | train |
Radi85/Comment | comment/templatetags/comment_tags.py | profile_url | def profile_url(obj, profile_app_name, profile_model_name):
""" returns profile url of user """
try:
content_type = ContentType.objects.get(
app_label=profile_app_name,
model=profile_model_name.lower()
)
profile = content_type.get_object_for_this_type(user=obj.user)
return profile.get_absolute_url()
except ContentType.DoesNotExist:
return ""
except AttributeError:
return "" | python | def profile_url(obj, profile_app_name, profile_model_name):
""" returns profile url of user """
try:
content_type = ContentType.objects.get(
app_label=profile_app_name,
model=profile_model_name.lower()
)
profile = content_type.get_object_for_this_type(user=obj.user)
return profile.get_absolute_url()
except ContentType.DoesNotExist:
return ""
except AttributeError:
return "" | [
"def",
"profile_url",
"(",
"obj",
",",
"profile_app_name",
",",
"profile_model_name",
")",
":",
"try",
":",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get",
"(",
"app_label",
"=",
"profile_app_name",
",",
"model",
"=",
"profile_model_name",
".",
"lower",
"(",
")",
")",
"profile",
"=",
"content_type",
".",
"get_object_for_this_type",
"(",
"user",
"=",
"obj",
".",
"user",
")",
"return",
"profile",
".",
"get_absolute_url",
"(",
")",
"except",
"ContentType",
".",
"DoesNotExist",
":",
"return",
"\"\"",
"except",
"AttributeError",
":",
"return",
"\"\""
] | returns profile url of user | [
"returns",
"profile",
"url",
"of",
"user"
] | c3c46afe51228cd7ee4e04f5e6164fff1be3a5bc | https://github.com/Radi85/Comment/blob/c3c46afe51228cd7ee4e04f5e6164fff1be3a5bc/comment/templatetags/comment_tags.py#L32-L44 | train |
Radi85/Comment | comment/templatetags/comment_tags.py | img_url | def img_url(obj, profile_app_name, profile_model_name):
""" returns url of profile image of a user """
try:
content_type = ContentType.objects.get(
app_label=profile_app_name,
model=profile_model_name.lower()
)
except ContentType.DoesNotExist:
return ""
except AttributeError:
return ""
Profile = content_type.model_class()
fields = Profile._meta.get_fields()
profile = content_type.model_class().objects.get(user=obj.user)
for field in fields:
if hasattr(field, "upload_to"):
return field.value_from_object(profile).url | python | def img_url(obj, profile_app_name, profile_model_name):
""" returns url of profile image of a user """
try:
content_type = ContentType.objects.get(
app_label=profile_app_name,
model=profile_model_name.lower()
)
except ContentType.DoesNotExist:
return ""
except AttributeError:
return ""
Profile = content_type.model_class()
fields = Profile._meta.get_fields()
profile = content_type.model_class().objects.get(user=obj.user)
for field in fields:
if hasattr(field, "upload_to"):
return field.value_from_object(profile).url | [
"def",
"img_url",
"(",
"obj",
",",
"profile_app_name",
",",
"profile_model_name",
")",
":",
"try",
":",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get",
"(",
"app_label",
"=",
"profile_app_name",
",",
"model",
"=",
"profile_model_name",
".",
"lower",
"(",
")",
")",
"except",
"ContentType",
".",
"DoesNotExist",
":",
"return",
"\"\"",
"except",
"AttributeError",
":",
"return",
"\"\"",
"Profile",
"=",
"content_type",
".",
"model_class",
"(",
")",
"fields",
"=",
"Profile",
".",
"_meta",
".",
"get_fields",
"(",
")",
"profile",
"=",
"content_type",
".",
"model_class",
"(",
")",
".",
"objects",
".",
"get",
"(",
"user",
"=",
"obj",
".",
"user",
")",
"for",
"field",
"in",
"fields",
":",
"if",
"hasattr",
"(",
"field",
",",
"\"upload_to\"",
")",
":",
"return",
"field",
".",
"value_from_object",
"(",
"profile",
")",
".",
"url"
] | returns url of profile image of a user | [
"returns",
"url",
"of",
"profile",
"image",
"of",
"a",
"user"
] | c3c46afe51228cd7ee4e04f5e6164fff1be3a5bc | https://github.com/Radi85/Comment/blob/c3c46afe51228cd7ee4e04f5e6164fff1be3a5bc/comment/templatetags/comment_tags.py#L48-L65 | train |
Radi85/Comment | comment/templatetags/comment_tags.py | get_comments | def get_comments(obj, request, oauth=False, paginate=False, cpp=10):
"""
Retrieves list of comments related to a certain object and renders
The appropriate template to view it
"""
model_object = type(obj).objects.get(id=obj.id)
comments = Comment.objects.filter_by_object(model_object)
comments_count = comments.count()
if paginate:
paginator = Paginator(comments, cpp)
page = request.GET.get('page')
try:
comments = paginator.page(page)
except PageNotAnInteger:
comments = paginator.page(1)
except EmptyPage:
comments = paginator.page(paginator.num_pages)
try:
profile_app_name = settings.PROFILE_APP_NAME
profile_model_name = settings.PROFILE_MODEL_NAME
except AttributeError:
profile_app_name = None
profile_model_name = None
try:
if settings.LOGIN_URL.startswith("/"):
login_url = settings.LOGIN_URL
else:
login_url = "/" + settings.LOGIN_URL
except AttributeError:
login_url = ""
return {
"commentform": CommentForm(),
"model_object": obj,
"user": request.user,
"comments": comments,
# "comments_count": comments_count,
"oauth": oauth,
"profile_app_name": profile_app_name,
"profile_model_name": profile_model_name,
"paginate": paginate,
"login_url": login_url,
"cpp": cpp
} | python | def get_comments(obj, request, oauth=False, paginate=False, cpp=10):
"""
Retrieves list of comments related to a certain object and renders
The appropriate template to view it
"""
model_object = type(obj).objects.get(id=obj.id)
comments = Comment.objects.filter_by_object(model_object)
comments_count = comments.count()
if paginate:
paginator = Paginator(comments, cpp)
page = request.GET.get('page')
try:
comments = paginator.page(page)
except PageNotAnInteger:
comments = paginator.page(1)
except EmptyPage:
comments = paginator.page(paginator.num_pages)
try:
profile_app_name = settings.PROFILE_APP_NAME
profile_model_name = settings.PROFILE_MODEL_NAME
except AttributeError:
profile_app_name = None
profile_model_name = None
try:
if settings.LOGIN_URL.startswith("/"):
login_url = settings.LOGIN_URL
else:
login_url = "/" + settings.LOGIN_URL
except AttributeError:
login_url = ""
return {
"commentform": CommentForm(),
"model_object": obj,
"user": request.user,
"comments": comments,
# "comments_count": comments_count,
"oauth": oauth,
"profile_app_name": profile_app_name,
"profile_model_name": profile_model_name,
"paginate": paginate,
"login_url": login_url,
"cpp": cpp
} | [
"def",
"get_comments",
"(",
"obj",
",",
"request",
",",
"oauth",
"=",
"False",
",",
"paginate",
"=",
"False",
",",
"cpp",
"=",
"10",
")",
":",
"model_object",
"=",
"type",
"(",
"obj",
")",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"obj",
".",
"id",
")",
"comments",
"=",
"Comment",
".",
"objects",
".",
"filter_by_object",
"(",
"model_object",
")",
"comments_count",
"=",
"comments",
".",
"count",
"(",
")",
"if",
"paginate",
":",
"paginator",
"=",
"Paginator",
"(",
"comments",
",",
"cpp",
")",
"page",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'page'",
")",
"try",
":",
"comments",
"=",
"paginator",
".",
"page",
"(",
"page",
")",
"except",
"PageNotAnInteger",
":",
"comments",
"=",
"paginator",
".",
"page",
"(",
"1",
")",
"except",
"EmptyPage",
":",
"comments",
"=",
"paginator",
".",
"page",
"(",
"paginator",
".",
"num_pages",
")",
"try",
":",
"profile_app_name",
"=",
"settings",
".",
"PROFILE_APP_NAME",
"profile_model_name",
"=",
"settings",
".",
"PROFILE_MODEL_NAME",
"except",
"AttributeError",
":",
"profile_app_name",
"=",
"None",
"profile_model_name",
"=",
"None",
"try",
":",
"if",
"settings",
".",
"LOGIN_URL",
".",
"startswith",
"(",
"\"/\"",
")",
":",
"login_url",
"=",
"settings",
".",
"LOGIN_URL",
"else",
":",
"login_url",
"=",
"\"/\"",
"+",
"settings",
".",
"LOGIN_URL",
"except",
"AttributeError",
":",
"login_url",
"=",
"\"\"",
"return",
"{",
"\"commentform\"",
":",
"CommentForm",
"(",
")",
",",
"\"model_object\"",
":",
"obj",
",",
"\"user\"",
":",
"request",
".",
"user",
",",
"\"comments\"",
":",
"comments",
",",
"# \"comments_count\": comments_count,",
"\"oauth\"",
":",
"oauth",
",",
"\"profile_app_name\"",
":",
"profile_app_name",
",",
"\"profile_model_name\"",
":",
"profile_model_name",
",",
"\"paginate\"",
":",
"paginate",
",",
"\"login_url\"",
":",
"login_url",
",",
"\"cpp\"",
":",
"cpp",
"}"
] | Retrieves list of comments related to a certain object and renders
The appropriate template to view it | [
"Retrieves",
"list",
"of",
"comments",
"related",
"to",
"a",
"certain",
"object",
"and",
"renders",
"The",
"appropriate",
"template",
"to",
"view",
"it"
] | c3c46afe51228cd7ee4e04f5e6164fff1be3a5bc | https://github.com/Radi85/Comment/blob/c3c46afe51228cd7ee4e04f5e6164fff1be3a5bc/comment/templatetags/comment_tags.py#L68-L113 | train |
pjamesjoyce/lcopt | lcopt/model.py | LcoptModel.save | def save(self):
"""save the instance as a .lcopt file"""
if self.save_option == 'curdir':
model_path = os.path.join(
os.getcwd(),
'{}.lcopt'.format(self.name)
)
else: # default to appdir
model_path = os.path.join(
storage.model_dir,
'{}.lcopt'.format(self.name)
)
model_path = fix_mac_path_escapes(model_path)
with open(model_path, 'wb') as model_file:
pickle.dump(self, model_file) | python | def save(self):
"""save the instance as a .lcopt file"""
if self.save_option == 'curdir':
model_path = os.path.join(
os.getcwd(),
'{}.lcopt'.format(self.name)
)
else: # default to appdir
model_path = os.path.join(
storage.model_dir,
'{}.lcopt'.format(self.name)
)
model_path = fix_mac_path_escapes(model_path)
with open(model_path, 'wb') as model_file:
pickle.dump(self, model_file) | [
"def",
"save",
"(",
"self",
")",
":",
"if",
"self",
".",
"save_option",
"==",
"'curdir'",
":",
"model_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"'{}.lcopt'",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"else",
":",
"# default to appdir",
"model_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"storage",
".",
"model_dir",
",",
"'{}.lcopt'",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"model_path",
"=",
"fix_mac_path_escapes",
"(",
"model_path",
")",
"with",
"open",
"(",
"model_path",
",",
"'wb'",
")",
"as",
"model_file",
":",
"pickle",
".",
"dump",
"(",
"self",
",",
"model_file",
")"
] | save the instance as a .lcopt file | [
"save",
"the",
"instance",
"as",
"a",
".",
"lcopt",
"file"
] | 3f1caca31fece4a3068a384900707e6d21d04597 | https://github.com/pjamesjoyce/lcopt/blob/3f1caca31fece4a3068a384900707e6d21d04597/lcopt/model.py#L253-L269 | train |
pjamesjoyce/lcopt | lcopt/model.py | LcoptModel.load | def load(self, filename):
"""load data from a saved .lcopt file"""
if filename[-6:] != ".lcopt":
filename += ".lcopt"
try:
savedInstance = pickle.load(open("{}".format(filename), "rb"))
except FileNotFoundError:
savedInstance = pickle.load(open(fix_mac_path_escapes(os.path.join(storage.model_dir, "{}".format(filename))), "rb"))
attributes = ['name',
'database',
'params',
'production_params',
'allocation_params',
'ext_params',
'matrix',
'names',
'parameter_sets',
'model_matrices',
'technosphere_matrices',
'leontif_matrices',
'external_databases',
'parameter_map',
'sandbox_positions',
'ecoinventName',
'biosphereName',
'forwastName',
'analysis_settings',
'technosphere_databases',
'biosphere_databases',
'result_set',
'evaluated_parameter_sets',
'useForwast',
'base_project_name',
'save_option',
'allow_allocation',
'ecoinvent_version',
'ecoinvent_system_model',
]
for attr in attributes:
if hasattr(savedInstance, attr):
setattr(self, attr, getattr(savedInstance, attr))
else:
pass
#print ("can't set {}".format(attr))
# use legacy save option if this is missing from the model
if not hasattr(savedInstance, 'save_option'):
setattr(self, 'save_option', LEGACY_SAVE_OPTION)
# figure out ecoinvent version and system model if these are missing from the model
if not hasattr(savedInstance, 'ecoinvent_version') or not hasattr(savedInstance, 'ecoinvent_system_model'):
parts = savedInstance.ecoinventName.split("_")
main_version = parts[0][-1]
sub_version = parts[1]
system_model = parts[2]
#print(parts)
setattr(self, 'ecoinvent_version', '{}.{}'.format(main_version, sub_version))
setattr(self, 'ecoinvent_system_model', system_model) | python | def load(self, filename):
"""load data from a saved .lcopt file"""
if filename[-6:] != ".lcopt":
filename += ".lcopt"
try:
savedInstance = pickle.load(open("{}".format(filename), "rb"))
except FileNotFoundError:
savedInstance = pickle.load(open(fix_mac_path_escapes(os.path.join(storage.model_dir, "{}".format(filename))), "rb"))
attributes = ['name',
'database',
'params',
'production_params',
'allocation_params',
'ext_params',
'matrix',
'names',
'parameter_sets',
'model_matrices',
'technosphere_matrices',
'leontif_matrices',
'external_databases',
'parameter_map',
'sandbox_positions',
'ecoinventName',
'biosphereName',
'forwastName',
'analysis_settings',
'technosphere_databases',
'biosphere_databases',
'result_set',
'evaluated_parameter_sets',
'useForwast',
'base_project_name',
'save_option',
'allow_allocation',
'ecoinvent_version',
'ecoinvent_system_model',
]
for attr in attributes:
if hasattr(savedInstance, attr):
setattr(self, attr, getattr(savedInstance, attr))
else:
pass
#print ("can't set {}".format(attr))
# use legacy save option if this is missing from the model
if not hasattr(savedInstance, 'save_option'):
setattr(self, 'save_option', LEGACY_SAVE_OPTION)
# figure out ecoinvent version and system model if these are missing from the model
if not hasattr(savedInstance, 'ecoinvent_version') or not hasattr(savedInstance, 'ecoinvent_system_model'):
parts = savedInstance.ecoinventName.split("_")
main_version = parts[0][-1]
sub_version = parts[1]
system_model = parts[2]
#print(parts)
setattr(self, 'ecoinvent_version', '{}.{}'.format(main_version, sub_version))
setattr(self, 'ecoinvent_system_model', system_model) | [
"def",
"load",
"(",
"self",
",",
"filename",
")",
":",
"if",
"filename",
"[",
"-",
"6",
":",
"]",
"!=",
"\".lcopt\"",
":",
"filename",
"+=",
"\".lcopt\"",
"try",
":",
"savedInstance",
"=",
"pickle",
".",
"load",
"(",
"open",
"(",
"\"{}\"",
".",
"format",
"(",
"filename",
")",
",",
"\"rb\"",
")",
")",
"except",
"FileNotFoundError",
":",
"savedInstance",
"=",
"pickle",
".",
"load",
"(",
"open",
"(",
"fix_mac_path_escapes",
"(",
"os",
".",
"path",
".",
"join",
"(",
"storage",
".",
"model_dir",
",",
"\"{}\"",
".",
"format",
"(",
"filename",
")",
")",
")",
",",
"\"rb\"",
")",
")",
"attributes",
"=",
"[",
"'name'",
",",
"'database'",
",",
"'params'",
",",
"'production_params'",
",",
"'allocation_params'",
",",
"'ext_params'",
",",
"'matrix'",
",",
"'names'",
",",
"'parameter_sets'",
",",
"'model_matrices'",
",",
"'technosphere_matrices'",
",",
"'leontif_matrices'",
",",
"'external_databases'",
",",
"'parameter_map'",
",",
"'sandbox_positions'",
",",
"'ecoinventName'",
",",
"'biosphereName'",
",",
"'forwastName'",
",",
"'analysis_settings'",
",",
"'technosphere_databases'",
",",
"'biosphere_databases'",
",",
"'result_set'",
",",
"'evaluated_parameter_sets'",
",",
"'useForwast'",
",",
"'base_project_name'",
",",
"'save_option'",
",",
"'allow_allocation'",
",",
"'ecoinvent_version'",
",",
"'ecoinvent_system_model'",
",",
"]",
"for",
"attr",
"in",
"attributes",
":",
"if",
"hasattr",
"(",
"savedInstance",
",",
"attr",
")",
":",
"setattr",
"(",
"self",
",",
"attr",
",",
"getattr",
"(",
"savedInstance",
",",
"attr",
")",
")",
"else",
":",
"pass",
"#print (\"can't set {}\".format(attr))",
"# use legacy save option if this is missing from the model",
"if",
"not",
"hasattr",
"(",
"savedInstance",
",",
"'save_option'",
")",
":",
"setattr",
"(",
"self",
",",
"'save_option'",
",",
"LEGACY_SAVE_OPTION",
")",
"# figure out ecoinvent version and system model if these are missing from the model",
"if",
"not",
"hasattr",
"(",
"savedInstance",
",",
"'ecoinvent_version'",
")",
"or",
"not",
"hasattr",
"(",
"savedInstance",
",",
"'ecoinvent_system_model'",
")",
":",
"parts",
"=",
"savedInstance",
".",
"ecoinventName",
".",
"split",
"(",
"\"_\"",
")",
"main_version",
"=",
"parts",
"[",
"0",
"]",
"[",
"-",
"1",
"]",
"sub_version",
"=",
"parts",
"[",
"1",
"]",
"system_model",
"=",
"parts",
"[",
"2",
"]",
"#print(parts)",
"setattr",
"(",
"self",
",",
"'ecoinvent_version'",
",",
"'{}.{}'",
".",
"format",
"(",
"main_version",
",",
"sub_version",
")",
")",
"setattr",
"(",
"self",
",",
"'ecoinvent_system_model'",
",",
"system_model",
")"
] | load data from a saved .lcopt file | [
"load",
"data",
"from",
"a",
"saved",
".",
"lcopt",
"file"
] | 3f1caca31fece4a3068a384900707e6d21d04597 | https://github.com/pjamesjoyce/lcopt/blob/3f1caca31fece4a3068a384900707e6d21d04597/lcopt/model.py#L271-L334 | train |
pjamesjoyce/lcopt | lcopt/model.py | LcoptModel.create_product | def create_product (self, name, location='GLO', unit='kg', **kwargs):
"""
Create a new product in the model database
"""
new_product = item_factory(name=name, location=location, unit=unit, type='product', **kwargs)
if not self.exists_in_database(new_product['code']):
self.add_to_database(new_product)
#print ('{} added to database'.format(name))
return self.get_exchange(name)
else:
#print('{} already exists in this database'.format(name))
return False | python | def create_product (self, name, location='GLO', unit='kg', **kwargs):
"""
Create a new product in the model database
"""
new_product = item_factory(name=name, location=location, unit=unit, type='product', **kwargs)
if not self.exists_in_database(new_product['code']):
self.add_to_database(new_product)
#print ('{} added to database'.format(name))
return self.get_exchange(name)
else:
#print('{} already exists in this database'.format(name))
return False | [
"def",
"create_product",
"(",
"self",
",",
"name",
",",
"location",
"=",
"'GLO'",
",",
"unit",
"=",
"'kg'",
",",
"*",
"*",
"kwargs",
")",
":",
"new_product",
"=",
"item_factory",
"(",
"name",
"=",
"name",
",",
"location",
"=",
"location",
",",
"unit",
"=",
"unit",
",",
"type",
"=",
"'product'",
",",
"*",
"*",
"kwargs",
")",
"if",
"not",
"self",
".",
"exists_in_database",
"(",
"new_product",
"[",
"'code'",
"]",
")",
":",
"self",
".",
"add_to_database",
"(",
"new_product",
")",
"#print ('{} added to database'.format(name))",
"return",
"self",
".",
"get_exchange",
"(",
"name",
")",
"else",
":",
"#print('{} already exists in this database'.format(name))",
"return",
"False"
] | Create a new product in the model database | [
"Create",
"a",
"new",
"product",
"in",
"the",
"model",
"database"
] | 3f1caca31fece4a3068a384900707e6d21d04597 | https://github.com/pjamesjoyce/lcopt/blob/3f1caca31fece4a3068a384900707e6d21d04597/lcopt/model.py#L338-L352 | train |
pjamesjoyce/lcopt | lcopt/model.py | LcoptModel.unlink_intermediate | def unlink_intermediate(self, sourceId, targetId):
"""
Remove a link between two processes
"""
source = self.database['items'][(self.database.get('name'), sourceId)]
target = self.database['items'][(self.database.get('name'), targetId)]
production_exchange = [x['input'] for x in source['exchanges'] if x['type'] == 'production'][0]
new_exchanges = [x for x in target['exchanges'] if x['input'] != production_exchange]
target['exchanges'] = new_exchanges
self.parameter_scan()
return True | python | def unlink_intermediate(self, sourceId, targetId):
"""
Remove a link between two processes
"""
source = self.database['items'][(self.database.get('name'), sourceId)]
target = self.database['items'][(self.database.get('name'), targetId)]
production_exchange = [x['input'] for x in source['exchanges'] if x['type'] == 'production'][0]
new_exchanges = [x for x in target['exchanges'] if x['input'] != production_exchange]
target['exchanges'] = new_exchanges
self.parameter_scan()
return True | [
"def",
"unlink_intermediate",
"(",
"self",
",",
"sourceId",
",",
"targetId",
")",
":",
"source",
"=",
"self",
".",
"database",
"[",
"'items'",
"]",
"[",
"(",
"self",
".",
"database",
".",
"get",
"(",
"'name'",
")",
",",
"sourceId",
")",
"]",
"target",
"=",
"self",
".",
"database",
"[",
"'items'",
"]",
"[",
"(",
"self",
".",
"database",
".",
"get",
"(",
"'name'",
")",
",",
"targetId",
")",
"]",
"production_exchange",
"=",
"[",
"x",
"[",
"'input'",
"]",
"for",
"x",
"in",
"source",
"[",
"'exchanges'",
"]",
"if",
"x",
"[",
"'type'",
"]",
"==",
"'production'",
"]",
"[",
"0",
"]",
"new_exchanges",
"=",
"[",
"x",
"for",
"x",
"in",
"target",
"[",
"'exchanges'",
"]",
"if",
"x",
"[",
"'input'",
"]",
"!=",
"production_exchange",
"]",
"target",
"[",
"'exchanges'",
"]",
"=",
"new_exchanges",
"self",
".",
"parameter_scan",
"(",
")",
"return",
"True"
] | Remove a link between two processes | [
"Remove",
"a",
"link",
"between",
"two",
"processes"
] | 3f1caca31fece4a3068a384900707e6d21d04597 | https://github.com/pjamesjoyce/lcopt/blob/3f1caca31fece4a3068a384900707e6d21d04597/lcopt/model.py#L440-L456 | train |
pjamesjoyce/lcopt | lcopt/model.py | LcoptModel.generate_parameter_set_excel_file | def generate_parameter_set_excel_file(self):
"""
Generate an excel file containing the parameter sets in a format you can import into SimaPro Developer.
The file will be called "ParameterSet_<ModelName>_input_file.xlsx"
"""
parameter_sets = self.parameter_sets
p_set = []
filename = "ParameterSet_{}_input_file.xlsx".format(self.name)
if self.save_option == 'curdir':
base_dir = os.getcwd()
else:
base_dir = os.path.join(storage.simapro_dir, self.name.replace(" ", "_"))
if not os.path.isdir(base_dir):
os.mkdir(base_dir)
p_set_name = os.path.join(base_dir, filename)
p = self.params
for k in p.keys():
if p[k]['function'] is None:
base_dict = {'id': k, 'name': p[k]['description'], 'unit': p[k]['unit']}
for s in parameter_sets.keys():
base_dict[s] = parameter_sets[s][k]
p_set.append(base_dict)
else:
pass
#print("{} is determined by a function".format(p[k]['description']))
for e in self.ext_params:
base_dict = {'id': '{}'.format(e['name']), 'type': 'external', 'name': e['description'], 'unit': ''}
for s in parameter_sets.keys():
base_dict[s] = parameter_sets[s][e['name']]
p_set.append(base_dict)
df = pd.DataFrame(p_set)
with pd.ExcelWriter(p_set_name, engine='xlsxwriter') as writer:
ps_columns = [k for k in parameter_sets.keys()]
#print (ps_columns)
my_columns = ['name', 'unit', 'id']
my_columns.extend(ps_columns)
#print (my_columns)
#print(df)
df.to_excel(writer, sheet_name=self.name, columns=my_columns, index=False, merge_cells=False)
return p_set_name | python | def generate_parameter_set_excel_file(self):
"""
Generate an excel file containing the parameter sets in a format you can import into SimaPro Developer.
The file will be called "ParameterSet_<ModelName>_input_file.xlsx"
"""
parameter_sets = self.parameter_sets
p_set = []
filename = "ParameterSet_{}_input_file.xlsx".format(self.name)
if self.save_option == 'curdir':
base_dir = os.getcwd()
else:
base_dir = os.path.join(storage.simapro_dir, self.name.replace(" ", "_"))
if not os.path.isdir(base_dir):
os.mkdir(base_dir)
p_set_name = os.path.join(base_dir, filename)
p = self.params
for k in p.keys():
if p[k]['function'] is None:
base_dict = {'id': k, 'name': p[k]['description'], 'unit': p[k]['unit']}
for s in parameter_sets.keys():
base_dict[s] = parameter_sets[s][k]
p_set.append(base_dict)
else:
pass
#print("{} is determined by a function".format(p[k]['description']))
for e in self.ext_params:
base_dict = {'id': '{}'.format(e['name']), 'type': 'external', 'name': e['description'], 'unit': ''}
for s in parameter_sets.keys():
base_dict[s] = parameter_sets[s][e['name']]
p_set.append(base_dict)
df = pd.DataFrame(p_set)
with pd.ExcelWriter(p_set_name, engine='xlsxwriter') as writer:
ps_columns = [k for k in parameter_sets.keys()]
#print (ps_columns)
my_columns = ['name', 'unit', 'id']
my_columns.extend(ps_columns)
#print (my_columns)
#print(df)
df.to_excel(writer, sheet_name=self.name, columns=my_columns, index=False, merge_cells=False)
return p_set_name | [
"def",
"generate_parameter_set_excel_file",
"(",
"self",
")",
":",
"parameter_sets",
"=",
"self",
".",
"parameter_sets",
"p_set",
"=",
"[",
"]",
"filename",
"=",
"\"ParameterSet_{}_input_file.xlsx\"",
".",
"format",
"(",
"self",
".",
"name",
")",
"if",
"self",
".",
"save_option",
"==",
"'curdir'",
":",
"base_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"else",
":",
"base_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"storage",
".",
"simapro_dir",
",",
"self",
".",
"name",
".",
"replace",
"(",
"\" \"",
",",
"\"_\"",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"base_dir",
")",
":",
"os",
".",
"mkdir",
"(",
"base_dir",
")",
"p_set_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base_dir",
",",
"filename",
")",
"p",
"=",
"self",
".",
"params",
"for",
"k",
"in",
"p",
".",
"keys",
"(",
")",
":",
"if",
"p",
"[",
"k",
"]",
"[",
"'function'",
"]",
"is",
"None",
":",
"base_dict",
"=",
"{",
"'id'",
":",
"k",
",",
"'name'",
":",
"p",
"[",
"k",
"]",
"[",
"'description'",
"]",
",",
"'unit'",
":",
"p",
"[",
"k",
"]",
"[",
"'unit'",
"]",
"}",
"for",
"s",
"in",
"parameter_sets",
".",
"keys",
"(",
")",
":",
"base_dict",
"[",
"s",
"]",
"=",
"parameter_sets",
"[",
"s",
"]",
"[",
"k",
"]",
"p_set",
".",
"append",
"(",
"base_dict",
")",
"else",
":",
"pass",
"#print(\"{} is determined by a function\".format(p[k]['description']))",
"for",
"e",
"in",
"self",
".",
"ext_params",
":",
"base_dict",
"=",
"{",
"'id'",
":",
"'{}'",
".",
"format",
"(",
"e",
"[",
"'name'",
"]",
")",
",",
"'type'",
":",
"'external'",
",",
"'name'",
":",
"e",
"[",
"'description'",
"]",
",",
"'unit'",
":",
"''",
"}",
"for",
"s",
"in",
"parameter_sets",
".",
"keys",
"(",
")",
":",
"base_dict",
"[",
"s",
"]",
"=",
"parameter_sets",
"[",
"s",
"]",
"[",
"e",
"[",
"'name'",
"]",
"]",
"p_set",
".",
"append",
"(",
"base_dict",
")",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"p_set",
")",
"with",
"pd",
".",
"ExcelWriter",
"(",
"p_set_name",
",",
"engine",
"=",
"'xlsxwriter'",
")",
"as",
"writer",
":",
"ps_columns",
"=",
"[",
"k",
"for",
"k",
"in",
"parameter_sets",
".",
"keys",
"(",
")",
"]",
"#print (ps_columns)",
"my_columns",
"=",
"[",
"'name'",
",",
"'unit'",
",",
"'id'",
"]",
"my_columns",
".",
"extend",
"(",
"ps_columns",
")",
"#print (my_columns)",
"#print(df)",
"df",
".",
"to_excel",
"(",
"writer",
",",
"sheet_name",
"=",
"self",
".",
"name",
",",
"columns",
"=",
"my_columns",
",",
"index",
"=",
"False",
",",
"merge_cells",
"=",
"False",
")",
"return",
"p_set_name"
] | Generate an excel file containing the parameter sets in a format you can import into SimaPro Developer.
The file will be called "ParameterSet_<ModelName>_input_file.xlsx" | [
"Generate",
"an",
"excel",
"file",
"containing",
"the",
"parameter",
"sets",
"in",
"a",
"format",
"you",
"can",
"import",
"into",
"SimaPro",
"Developer",
"."
] | 3f1caca31fece4a3068a384900707e6d21d04597 | https://github.com/pjamesjoyce/lcopt/blob/3f1caca31fece4a3068a384900707e6d21d04597/lcopt/model.py#L575-L633 | train |
pjamesjoyce/lcopt | lcopt/model.py | LcoptModel.add_parameter | def add_parameter(self, param_name, description=None, default=0, unit=None):
"""
Add a global parameter to the database that can be accessed by functions
"""
if description is None:
description = "Parameter called {}".format(param_name)
if unit is None:
unit = "-"
name_check = lambda x: x['name'] == param_name
name_check_list = list(filter(name_check, self.ext_params))
if len(name_check_list) == 0:
self.ext_params.append({'name': param_name, 'description': description, 'default': default, 'unit': unit})
else:
print('{} already exists - choose a different name'.format(param_name)) | python | def add_parameter(self, param_name, description=None, default=0, unit=None):
"""
Add a global parameter to the database that can be accessed by functions
"""
if description is None:
description = "Parameter called {}".format(param_name)
if unit is None:
unit = "-"
name_check = lambda x: x['name'] == param_name
name_check_list = list(filter(name_check, self.ext_params))
if len(name_check_list) == 0:
self.ext_params.append({'name': param_name, 'description': description, 'default': default, 'unit': unit})
else:
print('{} already exists - choose a different name'.format(param_name)) | [
"def",
"add_parameter",
"(",
"self",
",",
"param_name",
",",
"description",
"=",
"None",
",",
"default",
"=",
"0",
",",
"unit",
"=",
"None",
")",
":",
"if",
"description",
"is",
"None",
":",
"description",
"=",
"\"Parameter called {}\"",
".",
"format",
"(",
"param_name",
")",
"if",
"unit",
"is",
"None",
":",
"unit",
"=",
"\"-\"",
"name_check",
"=",
"lambda",
"x",
":",
"x",
"[",
"'name'",
"]",
"==",
"param_name",
"name_check_list",
"=",
"list",
"(",
"filter",
"(",
"name_check",
",",
"self",
".",
"ext_params",
")",
")",
"if",
"len",
"(",
"name_check_list",
")",
"==",
"0",
":",
"self",
".",
"ext_params",
".",
"append",
"(",
"{",
"'name'",
":",
"param_name",
",",
"'description'",
":",
"description",
",",
"'default'",
":",
"default",
",",
"'unit'",
":",
"unit",
"}",
")",
"else",
":",
"print",
"(",
"'{} already exists - choose a different name'",
".",
"format",
"(",
"param_name",
")",
")"
] | Add a global parameter to the database that can be accessed by functions | [
"Add",
"a",
"global",
"parameter",
"to",
"the",
"database",
"that",
"can",
"be",
"accessed",
"by",
"functions"
] | 3f1caca31fece4a3068a384900707e6d21d04597 | https://github.com/pjamesjoyce/lcopt/blob/3f1caca31fece4a3068a384900707e6d21d04597/lcopt/model.py#L635-L651 | train |
pjamesjoyce/lcopt | lcopt/model.py | LcoptModel.list_parameters_as_df | def list_parameters_as_df(self):
"""
Only really useful when running from a jupyter notebook.
Lists the parameters in the model in a pandas dataframe
Columns: id, matrix coordinates, description, function
"""
to_df = []
for i, e in enumerate(self.ext_params):
row = {}
row['id'] = e['name']
row['coords'] = "n/a"
row['description'] = e['description']
row['function'] = "n/a"
to_df.append(row)
for pk in self.params:
p = self.params[pk]
row = {}
row['id'] = pk
row['coords'] = p['coords']
row['description'] = p['description']
row['function'] = p['function']
to_df.append(row)
df = pd.DataFrame(to_df)
return df | python | def list_parameters_as_df(self):
"""
Only really useful when running from a jupyter notebook.
Lists the parameters in the model in a pandas dataframe
Columns: id, matrix coordinates, description, function
"""
to_df = []
for i, e in enumerate(self.ext_params):
row = {}
row['id'] = e['name']
row['coords'] = "n/a"
row['description'] = e['description']
row['function'] = "n/a"
to_df.append(row)
for pk in self.params:
p = self.params[pk]
row = {}
row['id'] = pk
row['coords'] = p['coords']
row['description'] = p['description']
row['function'] = p['function']
to_df.append(row)
df = pd.DataFrame(to_df)
return df | [
"def",
"list_parameters_as_df",
"(",
"self",
")",
":",
"to_df",
"=",
"[",
"]",
"for",
"i",
",",
"e",
"in",
"enumerate",
"(",
"self",
".",
"ext_params",
")",
":",
"row",
"=",
"{",
"}",
"row",
"[",
"'id'",
"]",
"=",
"e",
"[",
"'name'",
"]",
"row",
"[",
"'coords'",
"]",
"=",
"\"n/a\"",
"row",
"[",
"'description'",
"]",
"=",
"e",
"[",
"'description'",
"]",
"row",
"[",
"'function'",
"]",
"=",
"\"n/a\"",
"to_df",
".",
"append",
"(",
"row",
")",
"for",
"pk",
"in",
"self",
".",
"params",
":",
"p",
"=",
"self",
".",
"params",
"[",
"pk",
"]",
"row",
"=",
"{",
"}",
"row",
"[",
"'id'",
"]",
"=",
"pk",
"row",
"[",
"'coords'",
"]",
"=",
"p",
"[",
"'coords'",
"]",
"row",
"[",
"'description'",
"]",
"=",
"p",
"[",
"'description'",
"]",
"row",
"[",
"'function'",
"]",
"=",
"p",
"[",
"'function'",
"]",
"to_df",
".",
"append",
"(",
"row",
")",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"to_df",
")",
"return",
"df"
] | Only really useful when running from a jupyter notebook.
Lists the parameters in the model in a pandas dataframe
Columns: id, matrix coordinates, description, function | [
"Only",
"really",
"useful",
"when",
"running",
"from",
"a",
"jupyter",
"notebook",
"."
] | 3f1caca31fece4a3068a384900707e6d21d04597 | https://github.com/pjamesjoyce/lcopt/blob/3f1caca31fece4a3068a384900707e6d21d04597/lcopt/model.py#L653-L684 | train |
pjamesjoyce/lcopt | lcopt/model.py | LcoptModel.import_external_db | def import_external_db(self, db_file, db_type=None):
"""
Import an external database for use in lcopt
db_type must be one of ``technosphere`` or ``biosphere``
The best way to 'obtain' an external database is to 'export' it from brightway as a pickle file
e.g.::
import brightway2 as bw
bw.projects.set_current('MyModel')
db = bw.Database('MyDatabase')
db_as_dict = db.load()
import pickle
with open('MyExport.pickle', 'wb') as f:
pickle.dump(db_as_dict, f)
NOTE: The Ecoinvent cutoff 3.3 database and the full biosphere database are included in the lcopt model as standard - no need to import those
This can be useful if you have your own methods which require new biosphere flows that you want to analyse using lcopt
"""
db = pickle.load(open("{}.pickle".format(db_file), "rb"))
name = list(db.keys())[0][0]
new_db = {'items': db, 'name': name}
self.external_databases.append(new_db)
if db_type is None: # Assume its a technosphere database
db_type = 'technosphere'
if db_type == 'technosphere':
self.technosphere_databases.append(name)
elif db_type == 'biosphere':
self.biosphere_databases.append(name)
else:
raise Exception
print ("Database type must be 'technosphere' or 'biosphere'") | python | def import_external_db(self, db_file, db_type=None):
"""
Import an external database for use in lcopt
db_type must be one of ``technosphere`` or ``biosphere``
The best way to 'obtain' an external database is to 'export' it from brightway as a pickle file
e.g.::
import brightway2 as bw
bw.projects.set_current('MyModel')
db = bw.Database('MyDatabase')
db_as_dict = db.load()
import pickle
with open('MyExport.pickle', 'wb') as f:
pickle.dump(db_as_dict, f)
NOTE: The Ecoinvent cutoff 3.3 database and the full biosphere database are included in the lcopt model as standard - no need to import those
This can be useful if you have your own methods which require new biosphere flows that you want to analyse using lcopt
"""
db = pickle.load(open("{}.pickle".format(db_file), "rb"))
name = list(db.keys())[0][0]
new_db = {'items': db, 'name': name}
self.external_databases.append(new_db)
if db_type is None: # Assume its a technosphere database
db_type = 'technosphere'
if db_type == 'technosphere':
self.technosphere_databases.append(name)
elif db_type == 'biosphere':
self.biosphere_databases.append(name)
else:
raise Exception
print ("Database type must be 'technosphere' or 'biosphere'") | [
"def",
"import_external_db",
"(",
"self",
",",
"db_file",
",",
"db_type",
"=",
"None",
")",
":",
"db",
"=",
"pickle",
".",
"load",
"(",
"open",
"(",
"\"{}.pickle\"",
".",
"format",
"(",
"db_file",
")",
",",
"\"rb\"",
")",
")",
"name",
"=",
"list",
"(",
"db",
".",
"keys",
"(",
")",
")",
"[",
"0",
"]",
"[",
"0",
"]",
"new_db",
"=",
"{",
"'items'",
":",
"db",
",",
"'name'",
":",
"name",
"}",
"self",
".",
"external_databases",
".",
"append",
"(",
"new_db",
")",
"if",
"db_type",
"is",
"None",
":",
"# Assume its a technosphere database",
"db_type",
"=",
"'technosphere'",
"if",
"db_type",
"==",
"'technosphere'",
":",
"self",
".",
"technosphere_databases",
".",
"append",
"(",
"name",
")",
"elif",
"db_type",
"==",
"'biosphere'",
":",
"self",
".",
"biosphere_databases",
".",
"append",
"(",
"name",
")",
"else",
":",
"raise",
"Exception",
"print",
"(",
"\"Database type must be 'technosphere' or 'biosphere'\"",
")"
] | Import an external database for use in lcopt
db_type must be one of ``technosphere`` or ``biosphere``
The best way to 'obtain' an external database is to 'export' it from brightway as a pickle file
e.g.::
import brightway2 as bw
bw.projects.set_current('MyModel')
db = bw.Database('MyDatabase')
db_as_dict = db.load()
import pickle
with open('MyExport.pickle', 'wb') as f:
pickle.dump(db_as_dict, f)
NOTE: The Ecoinvent cutoff 3.3 database and the full biosphere database are included in the lcopt model as standard - no need to import those
This can be useful if you have your own methods which require new biosphere flows that you want to analyse using lcopt | [
"Import",
"an",
"external",
"database",
"for",
"use",
"in",
"lcopt"
] | 3f1caca31fece4a3068a384900707e6d21d04597 | https://github.com/pjamesjoyce/lcopt/blob/3f1caca31fece4a3068a384900707e6d21d04597/lcopt/model.py#L686-L725 | train |
pjamesjoyce/lcopt | lcopt/model.py | LcoptModel.search_databases | def search_databases(self, search_term, location=None, markets_only=False, databases_to_search=None, allow_internal=False):
"""
Search external databases linked to your lcopt model.
To restrict the search to particular databases (e.g. technosphere or biosphere only) use a list of database names in the ``database_to_search`` variable
"""
dict_list = []
if allow_internal:
internal_dict = {}
for k, v in self.database['items'].items():
if v.get('lcopt_type') == 'intermediate':
internal_dict[k] = v
dict_list.append(internal_dict)
if databases_to_search is None:
#Search all of the databases available
#data = Dictionaries(self.database['items'], *[x['items'] for x in self.external_databases])
dict_list += [x['items'] for x in self.external_databases]
else:
#data = Dictionaries(self.database['items'], *[x['items'] for x in self.external_databases if x['name'] in databases_to_search])
dict_list += [x['items'] for x in self.external_databases if x['name'] in databases_to_search]
data = Dictionaries(*dict_list)
#data = Dictionaries(self.database['items'], *[x['items'] for x in self.external_databases if x['name'] in databases_to_search])
query = Query()
if markets_only:
market_filter = Filter("name", "has", "market for")
query.add(market_filter)
if location is not None:
location_filter = Filter("location", "is", location)
query.add(location_filter)
query.add(Filter("name", "ihas", search_term))
result = query(data)
return result | python | def search_databases(self, search_term, location=None, markets_only=False, databases_to_search=None, allow_internal=False):
"""
Search external databases linked to your lcopt model.
To restrict the search to particular databases (e.g. technosphere or biosphere only) use a list of database names in the ``database_to_search`` variable
"""
dict_list = []
if allow_internal:
internal_dict = {}
for k, v in self.database['items'].items():
if v.get('lcopt_type') == 'intermediate':
internal_dict[k] = v
dict_list.append(internal_dict)
if databases_to_search is None:
#Search all of the databases available
#data = Dictionaries(self.database['items'], *[x['items'] for x in self.external_databases])
dict_list += [x['items'] for x in self.external_databases]
else:
#data = Dictionaries(self.database['items'], *[x['items'] for x in self.external_databases if x['name'] in databases_to_search])
dict_list += [x['items'] for x in self.external_databases if x['name'] in databases_to_search]
data = Dictionaries(*dict_list)
#data = Dictionaries(self.database['items'], *[x['items'] for x in self.external_databases if x['name'] in databases_to_search])
query = Query()
if markets_only:
market_filter = Filter("name", "has", "market for")
query.add(market_filter)
if location is not None:
location_filter = Filter("location", "is", location)
query.add(location_filter)
query.add(Filter("name", "ihas", search_term))
result = query(data)
return result | [
"def",
"search_databases",
"(",
"self",
",",
"search_term",
",",
"location",
"=",
"None",
",",
"markets_only",
"=",
"False",
",",
"databases_to_search",
"=",
"None",
",",
"allow_internal",
"=",
"False",
")",
":",
"dict_list",
"=",
"[",
"]",
"if",
"allow_internal",
":",
"internal_dict",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"self",
".",
"database",
"[",
"'items'",
"]",
".",
"items",
"(",
")",
":",
"if",
"v",
".",
"get",
"(",
"'lcopt_type'",
")",
"==",
"'intermediate'",
":",
"internal_dict",
"[",
"k",
"]",
"=",
"v",
"dict_list",
".",
"append",
"(",
"internal_dict",
")",
"if",
"databases_to_search",
"is",
"None",
":",
"#Search all of the databases available",
"#data = Dictionaries(self.database['items'], *[x['items'] for x in self.external_databases])",
"dict_list",
"+=",
"[",
"x",
"[",
"'items'",
"]",
"for",
"x",
"in",
"self",
".",
"external_databases",
"]",
"else",
":",
"#data = Dictionaries(self.database['items'], *[x['items'] for x in self.external_databases if x['name'] in databases_to_search])",
"dict_list",
"+=",
"[",
"x",
"[",
"'items'",
"]",
"for",
"x",
"in",
"self",
".",
"external_databases",
"if",
"x",
"[",
"'name'",
"]",
"in",
"databases_to_search",
"]",
"data",
"=",
"Dictionaries",
"(",
"*",
"dict_list",
")",
"#data = Dictionaries(self.database['items'], *[x['items'] for x in self.external_databases if x['name'] in databases_to_search])",
"query",
"=",
"Query",
"(",
")",
"if",
"markets_only",
":",
"market_filter",
"=",
"Filter",
"(",
"\"name\"",
",",
"\"has\"",
",",
"\"market for\"",
")",
"query",
".",
"add",
"(",
"market_filter",
")",
"if",
"location",
"is",
"not",
"None",
":",
"location_filter",
"=",
"Filter",
"(",
"\"location\"",
",",
"\"is\"",
",",
"location",
")",
"query",
".",
"add",
"(",
"location_filter",
")",
"query",
".",
"add",
"(",
"Filter",
"(",
"\"name\"",
",",
"\"ihas\"",
",",
"search_term",
")",
")",
"result",
"=",
"query",
"(",
"data",
")",
"return",
"result"
] | Search external databases linked to your lcopt model.
To restrict the search to particular databases (e.g. technosphere or biosphere only) use a list of database names in the ``database_to_search`` variable | [
"Search",
"external",
"databases",
"linked",
"to",
"your",
"lcopt",
"model",
"."
] | 3f1caca31fece4a3068a384900707e6d21d04597 | https://github.com/pjamesjoyce/lcopt/blob/3f1caca31fece4a3068a384900707e6d21d04597/lcopt/model.py#L727-L770 | train |
pjamesjoyce/lcopt | lcopt/model.py | LcoptModel.export_to_bw2 | def export_to_bw2(self):
"""
Export the lcopt model in the native brightway 2 format
returns name, database
to use it to export, then import to brightway::
name, db = model.export_to_bw2()
import brightway2 as bw
bw.projects.set_current('MyProject')
new_db = bw.Database(name)
new_db.write(db)
new_db.process()
"""
my_exporter = Bw2Exporter(self)
name, bw2db = my_exporter.export_to_bw2()
return name, bw2db | python | def export_to_bw2(self):
"""
Export the lcopt model in the native brightway 2 format
returns name, database
to use it to export, then import to brightway::
name, db = model.export_to_bw2()
import brightway2 as bw
bw.projects.set_current('MyProject')
new_db = bw.Database(name)
new_db.write(db)
new_db.process()
"""
my_exporter = Bw2Exporter(self)
name, bw2db = my_exporter.export_to_bw2()
return name, bw2db | [
"def",
"export_to_bw2",
"(",
"self",
")",
":",
"my_exporter",
"=",
"Bw2Exporter",
"(",
"self",
")",
"name",
",",
"bw2db",
"=",
"my_exporter",
".",
"export_to_bw2",
"(",
")",
"return",
"name",
",",
"bw2db"
] | Export the lcopt model in the native brightway 2 format
returns name, database
to use it to export, then import to brightway::
name, db = model.export_to_bw2()
import brightway2 as bw
bw.projects.set_current('MyProject')
new_db = bw.Database(name)
new_db.write(db)
new_db.process() | [
"Export",
"the",
"lcopt",
"model",
"in",
"the",
"native",
"brightway",
"2",
"format"
] | 3f1caca31fece4a3068a384900707e6d21d04597 | https://github.com/pjamesjoyce/lcopt/blob/3f1caca31fece4a3068a384900707e6d21d04597/lcopt/model.py#L969-L987 | train |
pjamesjoyce/lcopt | lcopt/model.py | LcoptModel.analyse | def analyse(self, demand_item, demand_item_code):
""" Run the analyis of the model
Doesn't return anything, but creates a new item ``LcoptModel.result_set`` containing the results
"""
my_analysis = Bw2Analysis(self)
self.result_set = my_analysis.run_analyses(demand_item, demand_item_code, **self.analysis_settings)
return True | python | def analyse(self, demand_item, demand_item_code):
""" Run the analyis of the model
Doesn't return anything, but creates a new item ``LcoptModel.result_set`` containing the results
"""
my_analysis = Bw2Analysis(self)
self.result_set = my_analysis.run_analyses(demand_item, demand_item_code, **self.analysis_settings)
return True | [
"def",
"analyse",
"(",
"self",
",",
"demand_item",
",",
"demand_item_code",
")",
":",
"my_analysis",
"=",
"Bw2Analysis",
"(",
"self",
")",
"self",
".",
"result_set",
"=",
"my_analysis",
".",
"run_analyses",
"(",
"demand_item",
",",
"demand_item_code",
",",
"*",
"*",
"self",
".",
"analysis_settings",
")",
"return",
"True"
] | Run the analyis of the model
Doesn't return anything, but creates a new item ``LcoptModel.result_set`` containing the results | [
"Run",
"the",
"analyis",
"of",
"the",
"model",
"Doesn",
"t",
"return",
"anything",
"but",
"creates",
"a",
"new",
"item",
"LcoptModel",
".",
"result_set",
"containing",
"the",
"results"
] | 3f1caca31fece4a3068a384900707e6d21d04597 | https://github.com/pjamesjoyce/lcopt/blob/3f1caca31fece4a3068a384900707e6d21d04597/lcopt/model.py#L989-L996 | train |
cocaine/cocaine-tools | cocaine/tools/dispatch.py | locate | def locate(name, **kwargs):
"""
Show resolve information about specified service.
"""
ctx = Context(**kwargs)
ctx.execute_action('locate', **{
'name': name,
'locator': ctx.locator,
}) | python | def locate(name, **kwargs):
"""
Show resolve information about specified service.
"""
ctx = Context(**kwargs)
ctx.execute_action('locate', **{
'name': name,
'locator': ctx.locator,
}) | [
"def",
"locate",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'locate'",
",",
"*",
"*",
"{",
"'name'",
":",
"name",
",",
"'locator'",
":",
"ctx",
".",
"locator",
",",
"}",
")"
] | Show resolve information about specified service. | [
"Show",
"resolve",
"information",
"about",
"specified",
"service",
"."
] | d8834f8e04ca42817d5f4e368d471484d4b3419f | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L364-L372 | train |
cocaine/cocaine-tools | cocaine/tools/dispatch.py | routing | def routing(name, **kwargs):
"""
Show information about the requested routing group.
"""
ctx = Context(**kwargs)
ctx.execute_action('routing', **{
'name': name,
'locator': ctx.locator,
}) | python | def routing(name, **kwargs):
"""
Show information about the requested routing group.
"""
ctx = Context(**kwargs)
ctx.execute_action('routing', **{
'name': name,
'locator': ctx.locator,
}) | [
"def",
"routing",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'routing'",
",",
"*",
"*",
"{",
"'name'",
":",
"name",
",",
"'locator'",
":",
"ctx",
".",
"locator",
",",
"}",
")"
] | Show information about the requested routing group. | [
"Show",
"information",
"about",
"the",
"requested",
"routing",
"group",
"."
] | d8834f8e04ca42817d5f4e368d471484d4b3419f | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L378-L386 | train |
cocaine/cocaine-tools | cocaine/tools/dispatch.py | cluster | def cluster(resolve, **kwargs):
"""
Show cluster info.
"""
# Actually we have IPs and we need not do anything to resolve them to IPs. So the default
# behavior fits better to this option name.
ctx = Context(**kwargs)
ctx.execute_action('cluster', **{
'locator': ctx.locator,
'resolve': resolve,
}) | python | def cluster(resolve, **kwargs):
"""
Show cluster info.
"""
# Actually we have IPs and we need not do anything to resolve them to IPs. So the default
# behavior fits better to this option name.
ctx = Context(**kwargs)
ctx.execute_action('cluster', **{
'locator': ctx.locator,
'resolve': resolve,
}) | [
"def",
"cluster",
"(",
"resolve",
",",
"*",
"*",
"kwargs",
")",
":",
"# Actually we have IPs and we need not do anything to resolve them to IPs. So the default",
"# behavior fits better to this option name.",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'cluster'",
",",
"*",
"*",
"{",
"'locator'",
":",
"ctx",
".",
"locator",
",",
"'resolve'",
":",
"resolve",
",",
"}",
")"
] | Show cluster info. | [
"Show",
"cluster",
"info",
"."
] | d8834f8e04ca42817d5f4e368d471484d4b3419f | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L404-L415 | train |
cocaine/cocaine-tools | cocaine/tools/dispatch.py | info | def info(name, m, p, b, w, **kwargs):
"""
Show information about cocaine runtime.
Return json-like string with information about cocaine-runtime.
If the name option is not specified, shows information about all applications. Flags can be
specified for fine-grained control of the output verbosity.
"""
m = (m << 1) & 0b010
p = (p << 2) & 0b100
# Brief disables all further flags.
if b:
flags = 0b000
else:
flags = m | p | 0b001
ctx = Context(**kwargs)
ctx.execute_action('info', **{
'node': ctx.repo.create_secure_service('node'),
'locator': ctx.locator,
'name': name,
'flags': flags,
'use_wildcard': w,
'timeout': ctx.timeout,
}) | python | def info(name, m, p, b, w, **kwargs):
"""
Show information about cocaine runtime.
Return json-like string with information about cocaine-runtime.
If the name option is not specified, shows information about all applications. Flags can be
specified for fine-grained control of the output verbosity.
"""
m = (m << 1) & 0b010
p = (p << 2) & 0b100
# Brief disables all further flags.
if b:
flags = 0b000
else:
flags = m | p | 0b001
ctx = Context(**kwargs)
ctx.execute_action('info', **{
'node': ctx.repo.create_secure_service('node'),
'locator': ctx.locator,
'name': name,
'flags': flags,
'use_wildcard': w,
'timeout': ctx.timeout,
}) | [
"def",
"info",
"(",
"name",
",",
"m",
",",
"p",
",",
"b",
",",
"w",
",",
"*",
"*",
"kwargs",
")",
":",
"m",
"=",
"(",
"m",
"<<",
"1",
")",
"&",
"0b010",
"p",
"=",
"(",
"p",
"<<",
"2",
")",
"&",
"0b100",
"# Brief disables all further flags.",
"if",
"b",
":",
"flags",
"=",
"0b000",
"else",
":",
"flags",
"=",
"m",
"|",
"p",
"|",
"0b001",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'info'",
",",
"*",
"*",
"{",
"'node'",
":",
"ctx",
".",
"repo",
".",
"create_secure_service",
"(",
"'node'",
")",
",",
"'locator'",
":",
"ctx",
".",
"locator",
",",
"'name'",
":",
"name",
",",
"'flags'",
":",
"flags",
",",
"'use_wildcard'",
":",
"w",
",",
"'timeout'",
":",
"ctx",
".",
"timeout",
",",
"}",
")"
] | Show information about cocaine runtime.
Return json-like string with information about cocaine-runtime.
If the name option is not specified, shows information about all applications. Flags can be
specified for fine-grained control of the output verbosity. | [
"Show",
"information",
"about",
"cocaine",
"runtime",
"."
] | d8834f8e04ca42817d5f4e368d471484d4b3419f | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L425-L451 | train |
cocaine/cocaine-tools | cocaine/tools/dispatch.py | metrics | def metrics(ty, query, query_type, **kwargs):
"""
Outputs runtime metrics collected from cocaine-runtime and its services.
This command shows runtime metrics collected from cocaine-runtime and its services during their
lifetime.
There are four kind of metrics available: gauges, counters, meters and timers.
\b
- Gauges - an instantaneous measurement of a value.
- Counters - just a gauge for an atomic integer instance.
- Meters - measures the rate of events over time (e.g., "requests per second"). In addition
to the mean rate, meters also track 1-, 5-, and 15-minute moving averages.
- Timers - measures both the rate that a particular piece of code is called and the
distribution of its duration.
Every metric in has a unique name, which is just a dotted-name string like "connections.count"
or "node.queue.size".
An output type can be configured using --type option. The default one results in plain
formatting where there is only one depth level.
As an alternative you can expanded the JSON tree by specifying --type=json option. The depth of
the result tree depends on metric name which is split by dot symbol.
The result output will be probably too large without any customization. To reduce this output
there are custom filters, which can be specified using --query option. Technically it's a
special metrics query language (MQL) which supports the following operations and functions:
\b
- contains(<expr>, <expr>) - checks whether the result of second expression contains in the
result of first expression. These expressions must resolve in strings. An output type of this
function is bool.
- name() - resolves in metric name.
- type() - resolves in metric type (counter, meter, etc.).
- tag(<expr>) - extracts custom metric tag and results in string.
- && - combines several expressions in one, which applies when all of them apply.
- || - combines several expressions in one, which applies when any of them apply.
- == - compares two expressions for equality.
- != - compares two expressions for an non-equality.
- Also string literals (alphanumeric with dots) can be used as an expressions, for
example "name() == locator.connections.accepted".
Priorities can be specified using braces as in usual math expressions.
The grammar for this query language is:
\b
expr ::= term ((AND | OR) term)*
term ::= factor ((EQ | NE) factor)*
factor ::= func | literal | number | LPAREN expr RPAREN
func ::= literal LPAREN expr (,expr)* RPAREN
literal ::= alphanum | .
number ::= <floating point number>
An example of the query, which returns all meters (for all services) and the number of accepted
connections for the Locator
service: "contains(type(), meter) || name() == locator.connections.accepted".
"""
ctx = Context(**kwargs)
ctx.execute_action('metrics', **{
'metrics': ctx.repo.create_secure_service('metrics'),
'ty': ty,
'query': query,
'query_type': query_type,
}) | python | def metrics(ty, query, query_type, **kwargs):
"""
Outputs runtime metrics collected from cocaine-runtime and its services.
This command shows runtime metrics collected from cocaine-runtime and its services during their
lifetime.
There are four kind of metrics available: gauges, counters, meters and timers.
\b
- Gauges - an instantaneous measurement of a value.
- Counters - just a gauge for an atomic integer instance.
- Meters - measures the rate of events over time (e.g., "requests per second"). In addition
to the mean rate, meters also track 1-, 5-, and 15-minute moving averages.
- Timers - measures both the rate that a particular piece of code is called and the
distribution of its duration.
Every metric in has a unique name, which is just a dotted-name string like "connections.count"
or "node.queue.size".
An output type can be configured using --type option. The default one results in plain
formatting where there is only one depth level.
As an alternative you can expanded the JSON tree by specifying --type=json option. The depth of
the result tree depends on metric name which is split by dot symbol.
The result output will be probably too large without any customization. To reduce this output
there are custom filters, which can be specified using --query option. Technically it's a
special metrics query language (MQL) which supports the following operations and functions:
\b
- contains(<expr>, <expr>) - checks whether the result of second expression contains in the
result of first expression. These expressions must resolve in strings. An output type of this
function is bool.
- name() - resolves in metric name.
- type() - resolves in metric type (counter, meter, etc.).
- tag(<expr>) - extracts custom metric tag and results in string.
- && - combines several expressions in one, which applies when all of them apply.
- || - combines several expressions in one, which applies when any of them apply.
- == - compares two expressions for equality.
- != - compares two expressions for an non-equality.
- Also string literals (alphanumeric with dots) can be used as an expressions, for
example "name() == locator.connections.accepted".
Priorities can be specified using braces as in usual math expressions.
The grammar for this query language is:
\b
expr ::= term ((AND | OR) term)*
term ::= factor ((EQ | NE) factor)*
factor ::= func | literal | number | LPAREN expr RPAREN
func ::= literal LPAREN expr (,expr)* RPAREN
literal ::= alphanum | .
number ::= <floating point number>
An example of the query, which returns all meters (for all services) and the number of accepted
connections for the Locator
service: "contains(type(), meter) || name() == locator.connections.accepted".
"""
ctx = Context(**kwargs)
ctx.execute_action('metrics', **{
'metrics': ctx.repo.create_secure_service('metrics'),
'ty': ty,
'query': query,
'query_type': query_type,
}) | [
"def",
"metrics",
"(",
"ty",
",",
"query",
",",
"query_type",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'metrics'",
",",
"*",
"*",
"{",
"'metrics'",
":",
"ctx",
".",
"repo",
".",
"create_secure_service",
"(",
"'metrics'",
")",
",",
"'ty'",
":",
"ty",
",",
"'query'",
":",
"query",
",",
"'query_type'",
":",
"query_type",
",",
"}",
")"
] | Outputs runtime metrics collected from cocaine-runtime and its services.
This command shows runtime metrics collected from cocaine-runtime and its services during their
lifetime.
There are four kind of metrics available: gauges, counters, meters and timers.
\b
- Gauges - an instantaneous measurement of a value.
- Counters - just a gauge for an atomic integer instance.
- Meters - measures the rate of events over time (e.g., "requests per second"). In addition
to the mean rate, meters also track 1-, 5-, and 15-minute moving averages.
- Timers - measures both the rate that a particular piece of code is called and the
distribution of its duration.
Every metric in has a unique name, which is just a dotted-name string like "connections.count"
or "node.queue.size".
An output type can be configured using --type option. The default one results in plain
formatting where there is only one depth level.
As an alternative you can expanded the JSON tree by specifying --type=json option. The depth of
the result tree depends on metric name which is split by dot symbol.
The result output will be probably too large without any customization. To reduce this output
there are custom filters, which can be specified using --query option. Technically it's a
special metrics query language (MQL) which supports the following operations and functions:
\b
- contains(<expr>, <expr>) - checks whether the result of second expression contains in the
result of first expression. These expressions must resolve in strings. An output type of this
function is bool.
- name() - resolves in metric name.
- type() - resolves in metric type (counter, meter, etc.).
- tag(<expr>) - extracts custom metric tag and results in string.
- && - combines several expressions in one, which applies when all of them apply.
- || - combines several expressions in one, which applies when any of them apply.
- == - compares two expressions for equality.
- != - compares two expressions for an non-equality.
- Also string literals (alphanumeric with dots) can be used as an expressions, for
example "name() == locator.connections.accepted".
Priorities can be specified using braces as in usual math expressions.
The grammar for this query language is:
\b
expr ::= term ((AND | OR) term)*
term ::= factor ((EQ | NE) factor)*
factor ::= func | literal | number | LPAREN expr RPAREN
func ::= literal LPAREN expr (,expr)* RPAREN
literal ::= alphanum | .
number ::= <floating point number>
An example of the query, which returns all meters (for all services) and the number of accepted
connections for the Locator
service: "contains(type(), meter) || name() == locator.connections.accepted". | [
"Outputs",
"runtime",
"metrics",
"collected",
"from",
"cocaine",
"-",
"runtime",
"and",
"its",
"services",
"."
] | d8834f8e04ca42817d5f4e368d471484d4b3419f | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L579-L645 | train |
cocaine/cocaine-tools | cocaine/tools/dispatch.py | app_list | def app_list(**kwargs):
"""
Show uploaded applications.
"""
ctx = Context(**kwargs)
ctx.execute_action('app:list', **{
'storage': ctx.repo.create_secure_service('storage'),
}) | python | def app_list(**kwargs):
"""
Show uploaded applications.
"""
ctx = Context(**kwargs)
ctx.execute_action('app:list', **{
'storage': ctx.repo.create_secure_service('storage'),
}) | [
"def",
"app_list",
"(",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'app:list'",
",",
"*",
"*",
"{",
"'storage'",
":",
"ctx",
".",
"repo",
".",
"create_secure_service",
"(",
"'storage'",
")",
",",
"}",
")"
] | Show uploaded applications. | [
"Show",
"uploaded",
"applications",
"."
] | d8834f8e04ca42817d5f4e368d471484d4b3419f | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L650-L657 | train |
cocaine/cocaine-tools | cocaine/tools/dispatch.py | app_view | def app_view(name, **kwargs):
"""
Show manifest content for an application.
If application is not uploaded, an error will be displayed.
"""
ctx = Context(**kwargs)
ctx.execute_action('app:view', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name,
}) | python | def app_view(name, **kwargs):
"""
Show manifest content for an application.
If application is not uploaded, an error will be displayed.
"""
ctx = Context(**kwargs)
ctx.execute_action('app:view', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name,
}) | [
"def",
"app_view",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'app:view'",
",",
"*",
"*",
"{",
"'storage'",
":",
"ctx",
".",
"repo",
".",
"create_secure_service",
"(",
"'storage'",
")",
",",
"'name'",
":",
"name",
",",
"}",
")"
] | Show manifest content for an application.
If application is not uploaded, an error will be displayed. | [
"Show",
"manifest",
"content",
"for",
"an",
"application",
"."
] | d8834f8e04ca42817d5f4e368d471484d4b3419f | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L663-L673 | train |
cocaine/cocaine-tools | cocaine/tools/dispatch.py | app_import | def app_import(path, name, manifest, container_url, docker_address, registry, **kwargs):
"""
Import application Docker container.
"""
lower_limit = 120.0
ctx = Context(**kwargs)
if ctx.timeout < lower_limit:
ctx.timeout = lower_limit
log.info('shifted timeout to the %.2fs', ctx.timeout)
if container_url and docker_address:
ctx.execute_action('app:import-docker', **{
'storage': ctx.repo.create_secure_service('storage'),
'path': path,
'name': name,
'manifest': manifest,
'container': container_url,
'address': docker_address,
'registry': registry
})
else:
raise ValueError("both `container_url` and `docker_address` options must not be empty") | python | def app_import(path, name, manifest, container_url, docker_address, registry, **kwargs):
"""
Import application Docker container.
"""
lower_limit = 120.0
ctx = Context(**kwargs)
if ctx.timeout < lower_limit:
ctx.timeout = lower_limit
log.info('shifted timeout to the %.2fs', ctx.timeout)
if container_url and docker_address:
ctx.execute_action('app:import-docker', **{
'storage': ctx.repo.create_secure_service('storage'),
'path': path,
'name': name,
'manifest': manifest,
'container': container_url,
'address': docker_address,
'registry': registry
})
else:
raise ValueError("both `container_url` and `docker_address` options must not be empty") | [
"def",
"app_import",
"(",
"path",
",",
"name",
",",
"manifest",
",",
"container_url",
",",
"docker_address",
",",
"registry",
",",
"*",
"*",
"kwargs",
")",
":",
"lower_limit",
"=",
"120.0",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"if",
"ctx",
".",
"timeout",
"<",
"lower_limit",
":",
"ctx",
".",
"timeout",
"=",
"lower_limit",
"log",
".",
"info",
"(",
"'shifted timeout to the %.2fs'",
",",
"ctx",
".",
"timeout",
")",
"if",
"container_url",
"and",
"docker_address",
":",
"ctx",
".",
"execute_action",
"(",
"'app:import-docker'",
",",
"*",
"*",
"{",
"'storage'",
":",
"ctx",
".",
"repo",
".",
"create_secure_service",
"(",
"'storage'",
")",
",",
"'path'",
":",
"path",
",",
"'name'",
":",
"name",
",",
"'manifest'",
":",
"manifest",
",",
"'container'",
":",
"container_url",
",",
"'address'",
":",
"docker_address",
",",
"'registry'",
":",
"registry",
"}",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"both `container_url` and `docker_address` options must not be empty\"",
")"
] | Import application Docker container. | [
"Import",
"application",
"Docker",
"container",
"."
] | d8834f8e04ca42817d5f4e368d471484d4b3419f | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L761-L783 | train |
cocaine/cocaine-tools | cocaine/tools/dispatch.py | app_remove | def app_remove(name, **kwargs):
"""
Remove application from storage.
No error messages will display if specified application is not uploaded.
"""
ctx = Context(**kwargs)
ctx.execute_action('app:remove', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name,
}) | python | def app_remove(name, **kwargs):
"""
Remove application from storage.
No error messages will display if specified application is not uploaded.
"""
ctx = Context(**kwargs)
ctx.execute_action('app:remove', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name,
}) | [
"def",
"app_remove",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'app:remove'",
",",
"*",
"*",
"{",
"'storage'",
":",
"ctx",
".",
"repo",
".",
"create_secure_service",
"(",
"'storage'",
")",
",",
"'name'",
":",
"name",
",",
"}",
")"
] | Remove application from storage.
No error messages will display if specified application is not uploaded. | [
"Remove",
"application",
"from",
"storage",
"."
] | d8834f8e04ca42817d5f4e368d471484d4b3419f | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L789-L799 | train |
cocaine/cocaine-tools | cocaine/tools/dispatch.py | app_start | def app_start(name, profile, **kwargs):
"""
Start an application with specified profile.
Does nothing if application is already running.
"""
ctx = Context(**kwargs)
ctx.execute_action('app:start', **{
'node': ctx.repo.create_secure_service('node'),
'name': name,
'profile': profile
}) | python | def app_start(name, profile, **kwargs):
"""
Start an application with specified profile.
Does nothing if application is already running.
"""
ctx = Context(**kwargs)
ctx.execute_action('app:start', **{
'node': ctx.repo.create_secure_service('node'),
'name': name,
'profile': profile
}) | [
"def",
"app_start",
"(",
"name",
",",
"profile",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'app:start'",
",",
"*",
"*",
"{",
"'node'",
":",
"ctx",
".",
"repo",
".",
"create_secure_service",
"(",
"'node'",
")",
",",
"'name'",
":",
"name",
",",
"'profile'",
":",
"profile",
"}",
")"
] | Start an application with specified profile.
Does nothing if application is already running. | [
"Start",
"an",
"application",
"with",
"specified",
"profile",
"."
] | d8834f8e04ca42817d5f4e368d471484d4b3419f | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L806-L817 | train |
cocaine/cocaine-tools | cocaine/tools/dispatch.py | app_restart | def app_restart(name, profile, **kwargs):
"""
Restart application.
Executes ```cocaine-tool app pause``` and ```cocaine-tool app start``` sequentially.
It can be used to quickly change application profile.
"""
ctx = Context(**kwargs)
ctx.execute_action('app:restart', **{
'node': ctx.repo.create_secure_service('node'),
'locator': ctx.locator,
'name': name,
'profile': profile,
}) | python | def app_restart(name, profile, **kwargs):
"""
Restart application.
Executes ```cocaine-tool app pause``` and ```cocaine-tool app start``` sequentially.
It can be used to quickly change application profile.
"""
ctx = Context(**kwargs)
ctx.execute_action('app:restart', **{
'node': ctx.repo.create_secure_service('node'),
'locator': ctx.locator,
'name': name,
'profile': profile,
}) | [
"def",
"app_restart",
"(",
"name",
",",
"profile",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'app:restart'",
",",
"*",
"*",
"{",
"'node'",
":",
"ctx",
".",
"repo",
".",
"create_secure_service",
"(",
"'node'",
")",
",",
"'locator'",
":",
"ctx",
".",
"locator",
",",
"'name'",
":",
"name",
",",
"'profile'",
":",
"profile",
",",
"}",
")"
] | Restart application.
Executes ```cocaine-tool app pause``` and ```cocaine-tool app start``` sequentially.
It can be used to quickly change application profile. | [
"Restart",
"application",
"."
] | d8834f8e04ca42817d5f4e368d471484d4b3419f | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L854-L868 | train |
cocaine/cocaine-tools | cocaine/tools/dispatch.py | check | def check(name, **kwargs):
"""
Check application status.
"""
ctx = Context(**kwargs)
ctx.execute_action('app:check', **{
'node': ctx.repo.create_secure_service('node'),
'name': name,
}) | python | def check(name, **kwargs):
"""
Check application status.
"""
ctx = Context(**kwargs)
ctx.execute_action('app:check', **{
'node': ctx.repo.create_secure_service('node'),
'name': name,
}) | [
"def",
"check",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'app:check'",
",",
"*",
"*",
"{",
"'node'",
":",
"ctx",
".",
"repo",
".",
"create_secure_service",
"(",
"'node'",
")",
",",
"'name'",
":",
"name",
",",
"}",
")"
] | Check application status. | [
"Check",
"application",
"status",
"."
] | d8834f8e04ca42817d5f4e368d471484d4b3419f | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L874-L882 | train |
cocaine/cocaine-tools | cocaine/tools/dispatch.py | profile_list | def profile_list(**kwargs):
"""
Show uploaded profiles.
"""
ctx = Context(**kwargs)
ctx.execute_action('profile:list', **{
'storage': ctx.repo.create_secure_service('storage'),
}) | python | def profile_list(**kwargs):
"""
Show uploaded profiles.
"""
ctx = Context(**kwargs)
ctx.execute_action('profile:list', **{
'storage': ctx.repo.create_secure_service('storage'),
}) | [
"def",
"profile_list",
"(",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'profile:list'",
",",
"*",
"*",
"{",
"'storage'",
":",
"ctx",
".",
"repo",
".",
"create_secure_service",
"(",
"'storage'",
")",
",",
"}",
")"
] | Show uploaded profiles. | [
"Show",
"uploaded",
"profiles",
"."
] | d8834f8e04ca42817d5f4e368d471484d4b3419f | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L887-L894 | train |
cocaine/cocaine-tools | cocaine/tools/dispatch.py | profile_view | def profile_view(name, **kwargs):
"""
Show profile configuration content.
"""
ctx = Context(**kwargs)
ctx.execute_action('profile:view', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name,
}) | python | def profile_view(name, **kwargs):
"""
Show profile configuration content.
"""
ctx = Context(**kwargs)
ctx.execute_action('profile:view', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name,
}) | [
"def",
"profile_view",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'profile:view'",
",",
"*",
"*",
"{",
"'storage'",
":",
"ctx",
".",
"repo",
".",
"create_secure_service",
"(",
"'storage'",
")",
",",
"'name'",
":",
"name",
",",
"}",
")"
] | Show profile configuration content. | [
"Show",
"profile",
"configuration",
"content",
"."
] | d8834f8e04ca42817d5f4e368d471484d4b3419f | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L900-L908 | train |
cocaine/cocaine-tools | cocaine/tools/dispatch.py | profile_remove | def profile_remove(name, **kwargs):
"""
Remove profile from the storage.
"""
ctx = Context(**kwargs)
ctx.execute_action('profile:remove', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name,
}) | python | def profile_remove(name, **kwargs):
"""
Remove profile from the storage.
"""
ctx = Context(**kwargs)
ctx.execute_action('profile:remove', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name,
}) | [
"def",
"profile_remove",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'profile:remove'",
",",
"*",
"*",
"{",
"'storage'",
":",
"ctx",
".",
"repo",
".",
"create_secure_service",
"(",
"'storage'",
")",
",",
"'name'",
":",
"name",
",",
"}",
")"
] | Remove profile from the storage. | [
"Remove",
"profile",
"from",
"the",
"storage",
"."
] | d8834f8e04ca42817d5f4e368d471484d4b3419f | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L945-L953 | train |
cocaine/cocaine-tools | cocaine/tools/dispatch.py | runlist_list | def runlist_list(**kwargs):
"""
Show uploaded runlists.
"""
ctx = Context(**kwargs)
ctx.execute_action('runlist:list', **{
'storage': ctx.repo.create_secure_service('storage'),
}) | python | def runlist_list(**kwargs):
"""
Show uploaded runlists.
"""
ctx = Context(**kwargs)
ctx.execute_action('runlist:list', **{
'storage': ctx.repo.create_secure_service('storage'),
}) | [
"def",
"runlist_list",
"(",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'runlist:list'",
",",
"*",
"*",
"{",
"'storage'",
":",
"ctx",
".",
"repo",
".",
"create_secure_service",
"(",
"'storage'",
")",
",",
"}",
")"
] | Show uploaded runlists. | [
"Show",
"uploaded",
"runlists",
"."
] | d8834f8e04ca42817d5f4e368d471484d4b3419f | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L990-L997 | train |
cocaine/cocaine-tools | cocaine/tools/dispatch.py | runlist_view | def runlist_view(name, **kwargs):
"""
Show configuration content for a specified runlist.
"""
ctx = Context(**kwargs)
ctx.execute_action('runlist:view', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name
}) | python | def runlist_view(name, **kwargs):
"""
Show configuration content for a specified runlist.
"""
ctx = Context(**kwargs)
ctx.execute_action('runlist:view', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name
}) | [
"def",
"runlist_view",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'runlist:view'",
",",
"*",
"*",
"{",
"'storage'",
":",
"ctx",
".",
"repo",
".",
"create_secure_service",
"(",
"'storage'",
")",
",",
"'name'",
":",
"name",
"}",
")"
] | Show configuration content for a specified runlist. | [
"Show",
"configuration",
"content",
"for",
"a",
"specified",
"runlist",
"."
] | d8834f8e04ca42817d5f4e368d471484d4b3419f | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L1003-L1011 | train |
cocaine/cocaine-tools | cocaine/tools/dispatch.py | runlist_upload | def runlist_upload(name, runlist, **kwargs):
"""
Upload runlist with context into the storage.
"""
ctx = Context(**kwargs)
ctx.execute_action('runlist:upload', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name,
'runlist': runlist,
}) | python | def runlist_upload(name, runlist, **kwargs):
"""
Upload runlist with context into the storage.
"""
ctx = Context(**kwargs)
ctx.execute_action('runlist:upload', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name,
'runlist': runlist,
}) | [
"def",
"runlist_upload",
"(",
"name",
",",
"runlist",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'runlist:upload'",
",",
"*",
"*",
"{",
"'storage'",
":",
"ctx",
".",
"repo",
".",
"create_secure_service",
"(",
"'storage'",
")",
",",
"'name'",
":",
"name",
",",
"'runlist'",
":",
"runlist",
",",
"}",
")"
] | Upload runlist with context into the storage. | [
"Upload",
"runlist",
"with",
"context",
"into",
"the",
"storage",
"."
] | d8834f8e04ca42817d5f4e368d471484d4b3419f | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L1034-L1043 | train |
cocaine/cocaine-tools | cocaine/tools/dispatch.py | runlist_create | def runlist_create(name, **kwargs):
"""
Create runlist and upload it into the storage.
"""
ctx = Context(**kwargs)
ctx.execute_action('runlist:create', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name,
}) | python | def runlist_create(name, **kwargs):
"""
Create runlist and upload it into the storage.
"""
ctx = Context(**kwargs)
ctx.execute_action('runlist:create', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name,
}) | [
"def",
"runlist_create",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'runlist:create'",
",",
"*",
"*",
"{",
"'storage'",
":",
"ctx",
".",
"repo",
".",
"create_secure_service",
"(",
"'storage'",
")",
",",
"'name'",
":",
"name",
",",
"}",
")"
] | Create runlist and upload it into the storage. | [
"Create",
"runlist",
"and",
"upload",
"it",
"into",
"the",
"storage",
"."
] | d8834f8e04ca42817d5f4e368d471484d4b3419f | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L1049-L1057 | train |
cocaine/cocaine-tools | cocaine/tools/dispatch.py | runlist_remove | def runlist_remove(name, **kwargs):
"""
Remove runlist from the storage.
"""
ctx = Context(**kwargs)
ctx.execute_action('runlist:remove', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name,
}) | python | def runlist_remove(name, **kwargs):
"""
Remove runlist from the storage.
"""
ctx = Context(**kwargs)
ctx.execute_action('runlist:remove', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name,
}) | [
"def",
"runlist_remove",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'runlist:remove'",
",",
"*",
"*",
"{",
"'storage'",
":",
"ctx",
".",
"repo",
".",
"create_secure_service",
"(",
"'storage'",
")",
",",
"'name'",
":",
"name",
",",
"}",
")"
] | Remove runlist from the storage. | [
"Remove",
"runlist",
"from",
"the",
"storage",
"."
] | d8834f8e04ca42817d5f4e368d471484d4b3419f | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L1063-L1071 | train |
cocaine/cocaine-tools | cocaine/tools/dispatch.py | runlist_add_app | def runlist_add_app(name, app, profile, force, **kwargs):
"""
Add specified application with profile to the specified runlist.
Existence of application or profile is not checked.
"""
ctx = Context(**kwargs)
ctx.execute_action('runlist:add-app', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name,
'app': app,
'profile': profile,
'force': force
}) | python | def runlist_add_app(name, app, profile, force, **kwargs):
"""
Add specified application with profile to the specified runlist.
Existence of application or profile is not checked.
"""
ctx = Context(**kwargs)
ctx.execute_action('runlist:add-app', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name,
'app': app,
'profile': profile,
'force': force
}) | [
"def",
"runlist_add_app",
"(",
"name",
",",
"app",
",",
"profile",
",",
"force",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'runlist:add-app'",
",",
"*",
"*",
"{",
"'storage'",
":",
"ctx",
".",
"repo",
".",
"create_secure_service",
"(",
"'storage'",
")",
",",
"'name'",
":",
"name",
",",
"'app'",
":",
"app",
",",
"'profile'",
":",
"profile",
",",
"'force'",
":",
"force",
"}",
")"
] | Add specified application with profile to the specified runlist.
Existence of application or profile is not checked. | [
"Add",
"specified",
"application",
"with",
"profile",
"to",
"the",
"specified",
"runlist",
"."
] | d8834f8e04ca42817d5f4e368d471484d4b3419f | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L1112-L1125 | train |
cocaine/cocaine-tools | cocaine/tools/dispatch.py | crashlog_status | def crashlog_status(**kwargs):
"""
Show crashlogs status.
"""
ctx = Context(**kwargs)
ctx.execute_action('crashlog:status', **{
'storage': ctx.repo.create_secure_service('storage'),
}) | python | def crashlog_status(**kwargs):
"""
Show crashlogs status.
"""
ctx = Context(**kwargs)
ctx.execute_action('crashlog:status', **{
'storage': ctx.repo.create_secure_service('storage'),
}) | [
"def",
"crashlog_status",
"(",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'crashlog:status'",
",",
"*",
"*",
"{",
"'storage'",
":",
"ctx",
".",
"repo",
".",
"create_secure_service",
"(",
"'storage'",
")",
",",
"}",
")"
] | Show crashlogs status. | [
"Show",
"crashlogs",
"status",
"."
] | d8834f8e04ca42817d5f4e368d471484d4b3419f | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L1146-L1153 | train |
cocaine/cocaine-tools | cocaine/tools/dispatch.py | crashlog_list | def crashlog_list(name, day, **kwargs):
"""
Show crashlogs list for application.
Prints crashlog list in "Unix Timestamp - UUID" format.
Filtering by day accepts the following variants: today, yesterday, %d, %d-%m or %d-%m-%Y.
For example given today is a 06-12-2016 crashlogs for yesterday can be listed using:
`--day=yesterday`, `--day=5`, `--day=05-12` or `--day=05-12-2016`.
"""
ctx = Context(**kwargs)
ctx.execute_action('crashlog:list', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name,
'day_string': day,
}) | python | def crashlog_list(name, day, **kwargs):
"""
Show crashlogs list for application.
Prints crashlog list in "Unix Timestamp - UUID" format.
Filtering by day accepts the following variants: today, yesterday, %d, %d-%m or %d-%m-%Y.
For example given today is a 06-12-2016 crashlogs for yesterday can be listed using:
`--day=yesterday`, `--day=5`, `--day=05-12` or `--day=05-12-2016`.
"""
ctx = Context(**kwargs)
ctx.execute_action('crashlog:list', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name,
'day_string': day,
}) | [
"def",
"crashlog_list",
"(",
"name",
",",
"day",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'crashlog:list'",
",",
"*",
"*",
"{",
"'storage'",
":",
"ctx",
".",
"repo",
".",
"create_secure_service",
"(",
"'storage'",
")",
",",
"'name'",
":",
"name",
",",
"'day_string'",
":",
"day",
",",
"}",
")"
] | Show crashlogs list for application.
Prints crashlog list in "Unix Timestamp - UUID" format.
Filtering by day accepts the following variants: today, yesterday, %d, %d-%m or %d-%m-%Y.
For example given today is a 06-12-2016 crashlogs for yesterday can be listed using:
`--day=yesterday`, `--day=5`, `--day=05-12` or `--day=05-12-2016`. | [
"Show",
"crashlogs",
"list",
"for",
"application",
"."
] | d8834f8e04ca42817d5f4e368d471484d4b3419f | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L1160-L1175 | train |
cocaine/cocaine-tools | cocaine/tools/dispatch.py | crashlog_view | def crashlog_view(name, timestamp, **kwargs):
"""
Show crashlog for application with specified timestamp.
Last crashlog for a given application will be displayed unless timestamp option is specified.
"""
ctx = Context(**kwargs)
ctx.execute_action('crashlog:view', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name,
'timestamp': timestamp,
}) | python | def crashlog_view(name, timestamp, **kwargs):
"""
Show crashlog for application with specified timestamp.
Last crashlog for a given application will be displayed unless timestamp option is specified.
"""
ctx = Context(**kwargs)
ctx.execute_action('crashlog:view', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name,
'timestamp': timestamp,
}) | [
"def",
"crashlog_view",
"(",
"name",
",",
"timestamp",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'crashlog:view'",
",",
"*",
"*",
"{",
"'storage'",
":",
"ctx",
".",
"repo",
".",
"create_secure_service",
"(",
"'storage'",
")",
",",
"'name'",
":",
"name",
",",
"'timestamp'",
":",
"timestamp",
",",
"}",
")"
] | Show crashlog for application with specified timestamp.
Last crashlog for a given application will be displayed unless timestamp option is specified. | [
"Show",
"crashlog",
"for",
"application",
"with",
"specified",
"timestamp",
"."
] | d8834f8e04ca42817d5f4e368d471484d4b3419f | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L1182-L1193 | train |
cocaine/cocaine-tools | cocaine/tools/dispatch.py | crashlog_removeall | def crashlog_removeall(name, **kwargs):
"""
Remove all crashlogs for application from the storage.
"""
ctx = Context(**kwargs)
ctx.execute_action('crashlog:removeall', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name,
}) | python | def crashlog_removeall(name, **kwargs):
"""
Remove all crashlogs for application from the storage.
"""
ctx = Context(**kwargs)
ctx.execute_action('crashlog:removeall', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name,
}) | [
"def",
"crashlog_removeall",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'crashlog:removeall'",
",",
"*",
"*",
"{",
"'storage'",
":",
"ctx",
".",
"repo",
".",
"create_secure_service",
"(",
"'storage'",
")",
",",
"'name'",
":",
"name",
",",
"}",
")"
] | Remove all crashlogs for application from the storage. | [
"Remove",
"all",
"crashlogs",
"for",
"application",
"from",
"the",
"storage",
"."
] | d8834f8e04ca42817d5f4e368d471484d4b3419f | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L1215-L1223 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.