repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
SmartTeleMax/iktomi | iktomi/web/app.py | Application.handle_error | def handle_error(self, env):
'''
Unhandled exception handler.
You can put any logging, error warning, etc here.'''
logger.exception('Exception for %s %s :',
env.request.method, env.request.url) | python | def handle_error(self, env):
'''
Unhandled exception handler.
You can put any logging, error warning, etc here.'''
logger.exception('Exception for %s %s :',
env.request.method, env.request.url) | [
"def",
"handle_error",
"(",
"self",
",",
"env",
")",
":",
"logger",
".",
"exception",
"(",
"'Exception for %s %s :'",
",",
"env",
".",
"request",
".",
"method",
",",
"env",
".",
"request",
".",
"url",
")"
] | Unhandled exception handler.
You can put any logging, error warning, etc here. | [
"Unhandled",
"exception",
"handler",
".",
"You",
"can",
"put",
"any",
"logging",
"error",
"warning",
"etc",
"here",
"."
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/web/app.py#L92-L97 |
SmartTeleMax/iktomi | iktomi/web/app.py | Application.handle | def handle(self, env, data):
'''
Calls application and handles following cases:
* catches `webob.HTTPException` errors.
* catches unhandled exceptions, calls `handle_error` method
and returns 500.
* returns 404 if the app has returned None`.
'''
try:
response = self.handler(env, data)
if response is None:
logger.debug('Application returned None '
'instead of Response object')
response = HTTPNotFound()
except HTTPException as e:
response = e
except Exception as e:
self.handle_error(env)
response = HTTPInternalServerError()
return response | python | def handle(self, env, data):
'''
Calls application and handles following cases:
* catches `webob.HTTPException` errors.
* catches unhandled exceptions, calls `handle_error` method
and returns 500.
* returns 404 if the app has returned None`.
'''
try:
response = self.handler(env, data)
if response is None:
logger.debug('Application returned None '
'instead of Response object')
response = HTTPNotFound()
except HTTPException as e:
response = e
except Exception as e:
self.handle_error(env)
response = HTTPInternalServerError()
return response | [
"def",
"handle",
"(",
"self",
",",
"env",
",",
"data",
")",
":",
"try",
":",
"response",
"=",
"self",
".",
"handler",
"(",
"env",
",",
"data",
")",
"if",
"response",
"is",
"None",
":",
"logger",
".",
"debug",
"(",
"'Application returned None '",
"'inst... | Calls application and handles following cases:
* catches `webob.HTTPException` errors.
* catches unhandled exceptions, calls `handle_error` method
and returns 500.
* returns 404 if the app has returned None`. | [
"Calls",
"application",
"and",
"handles",
"following",
"cases",
":",
"*",
"catches",
"webob",
".",
"HTTPException",
"errors",
".",
"*",
"catches",
"unhandled",
"exceptions",
"calls",
"handle_error",
"method",
"and",
"returns",
"500",
".",
"*",
"returns",
"404",
... | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/web/app.py#L99-L118 |
twisted/epsilon | epsilon/expose.py | Exposer.expose | def expose(self, key=None):
"""
Expose the decorated method for this L{Exposer} with the given key. A
method which is exposed will be able to be retrieved by this
L{Exposer}'s C{get} method with that key. If no key is provided, the
key is the method name of the exposed method.
Use like so::
class MyClass:
@someExposer.expose()
def foo(): ...
or::
class MyClass:
@someExposer.expose('foo')
def unrelatedMethodName(): ...
@param key: a hashable object, used by L{Exposer.get} to look up the
decorated method later. If None, the key is the exposed method's name.
@return: a 1-argument callable which records its input as exposed, then
returns it.
"""
def decorator(function):
rkey = key
if rkey is None:
if isinstance(function, FunctionType):
rkey = function.__name__
else:
raise NameRequired()
if rkey not in self._exposed:
self._exposed[rkey] = []
self._exposed[rkey].append(function)
return function
return decorator | python | def expose(self, key=None):
"""
Expose the decorated method for this L{Exposer} with the given key. A
method which is exposed will be able to be retrieved by this
L{Exposer}'s C{get} method with that key. If no key is provided, the
key is the method name of the exposed method.
Use like so::
class MyClass:
@someExposer.expose()
def foo(): ...
or::
class MyClass:
@someExposer.expose('foo')
def unrelatedMethodName(): ...
@param key: a hashable object, used by L{Exposer.get} to look up the
decorated method later. If None, the key is the exposed method's name.
@return: a 1-argument callable which records its input as exposed, then
returns it.
"""
def decorator(function):
rkey = key
if rkey is None:
if isinstance(function, FunctionType):
rkey = function.__name__
else:
raise NameRequired()
if rkey not in self._exposed:
self._exposed[rkey] = []
self._exposed[rkey].append(function)
return function
return decorator | [
"def",
"expose",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"function",
")",
":",
"rkey",
"=",
"key",
"if",
"rkey",
"is",
"None",
":",
"if",
"isinstance",
"(",
"function",
",",
"FunctionType",
")",
":",
"rkey",
"=",
"f... | Expose the decorated method for this L{Exposer} with the given key. A
method which is exposed will be able to be retrieved by this
L{Exposer}'s C{get} method with that key. If no key is provided, the
key is the method name of the exposed method.
Use like so::
class MyClass:
@someExposer.expose()
def foo(): ...
or::
class MyClass:
@someExposer.expose('foo')
def unrelatedMethodName(): ...
@param key: a hashable object, used by L{Exposer.get} to look up the
decorated method later. If None, the key is the exposed method's name.
@return: a 1-argument callable which records its input as exposed, then
returns it. | [
"Expose",
"the",
"decorated",
"method",
"for",
"this",
"L",
"{",
"Exposer",
"}",
"with",
"the",
"given",
"key",
".",
"A",
"method",
"which",
"is",
"exposed",
"will",
"be",
"able",
"to",
"be",
"retrieved",
"by",
"this",
"L",
"{",
"Exposer",
"}",
"s",
... | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/expose.py#L78-L114 |
twisted/epsilon | epsilon/expose.py | Exposer.get | def get(self, obj, key):
"""
Retrieve 'key' from an instance of a class which previously exposed it.
@param key: a hashable object, previously passed to L{Exposer.expose}.
@return: the object which was exposed with the given name on obj's key.
@raise MethodNotExposed: when the key in question was not exposed with
this exposer.
"""
if key not in self._exposed:
raise MethodNotExposed()
rightFuncs = self._exposed[key]
T = obj.__class__
seen = {}
for subT in inspect.getmro(T):
for name, value in subT.__dict__.items():
for rightFunc in rightFuncs:
if value is rightFunc:
if name in seen:
raise MethodNotExposed()
return value.__get__(obj, T)
seen[name] = True
raise MethodNotExposed() | python | def get(self, obj, key):
"""
Retrieve 'key' from an instance of a class which previously exposed it.
@param key: a hashable object, previously passed to L{Exposer.expose}.
@return: the object which was exposed with the given name on obj's key.
@raise MethodNotExposed: when the key in question was not exposed with
this exposer.
"""
if key not in self._exposed:
raise MethodNotExposed()
rightFuncs = self._exposed[key]
T = obj.__class__
seen = {}
for subT in inspect.getmro(T):
for name, value in subT.__dict__.items():
for rightFunc in rightFuncs:
if value is rightFunc:
if name in seen:
raise MethodNotExposed()
return value.__get__(obj, T)
seen[name] = True
raise MethodNotExposed() | [
"def",
"get",
"(",
"self",
",",
"obj",
",",
"key",
")",
":",
"if",
"key",
"not",
"in",
"self",
".",
"_exposed",
":",
"raise",
"MethodNotExposed",
"(",
")",
"rightFuncs",
"=",
"self",
".",
"_exposed",
"[",
"key",
"]",
"T",
"=",
"obj",
".",
"__class_... | Retrieve 'key' from an instance of a class which previously exposed it.
@param key: a hashable object, previously passed to L{Exposer.expose}.
@return: the object which was exposed with the given name on obj's key.
@raise MethodNotExposed: when the key in question was not exposed with
this exposer. | [
"Retrieve",
"key",
"from",
"an",
"instance",
"of",
"a",
"class",
"which",
"previously",
"exposed",
"it",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/expose.py#L117-L141 |
SmartTeleMax/iktomi | iktomi/utils/url.py | repercent_broken_unicode | def repercent_broken_unicode(path):
"""
As per section 3.2 of RFC 3987, step three of converting a URI into an IRI,
we need to re-percent-encode any octet produced that is not part of a
strictly legal UTF-8 octet sequence.
"""
# originally from django.utils.encoding
while True:
try:
return path.decode('utf-8')
except UnicodeDecodeError as e:
repercent = quote(path[e.start:e.end], safe=b"/#%[]=:;$&()+,!?*@'~")
path = path[:e.start] + repercent.encode('ascii') + path[e.end:] | python | def repercent_broken_unicode(path):
"""
As per section 3.2 of RFC 3987, step three of converting a URI into an IRI,
we need to re-percent-encode any octet produced that is not part of a
strictly legal UTF-8 octet sequence.
"""
# originally from django.utils.encoding
while True:
try:
return path.decode('utf-8')
except UnicodeDecodeError as e:
repercent = quote(path[e.start:e.end], safe=b"/#%[]=:;$&()+,!?*@'~")
path = path[:e.start] + repercent.encode('ascii') + path[e.end:] | [
"def",
"repercent_broken_unicode",
"(",
"path",
")",
":",
"# originally from django.utils.encoding",
"while",
"True",
":",
"try",
":",
"return",
"path",
".",
"decode",
"(",
"'utf-8'",
")",
"except",
"UnicodeDecodeError",
"as",
"e",
":",
"repercent",
"=",
"quote",
... | As per section 3.2 of RFC 3987, step three of converting a URI into an IRI,
we need to re-percent-encode any octet produced that is not part of a
strictly legal UTF-8 octet sequence. | [
"As",
"per",
"section",
"3",
".",
"2",
"of",
"RFC",
"3987",
"step",
"three",
"of",
"converting",
"a",
"URI",
"into",
"an",
"IRI",
"we",
"need",
"to",
"re",
"-",
"percent",
"-",
"encode",
"any",
"octet",
"produced",
"that",
"is",
"not",
"part",
"of",
... | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/utils/url.py#L49-L61 |
SmartTeleMax/iktomi | iktomi/utils/url.py | uri_to_iri_parts | def uri_to_iri_parts(path, query, fragment):
r"""
Converts a URI parts to corresponding IRI parts in a given charset.
Examples for URI versus IRI:
:param path: The path of URI to convert.
:param query: The query string of URI to convert.
:param fragment: The fragment of URI to convert.
"""
path = url_unquote(path, '%/;?')
query = url_unquote(query, '%;/?:@&=+,$#')
fragment = url_unquote(fragment, '%;/?:@&=+,$#')
return path, query, fragment | python | def uri_to_iri_parts(path, query, fragment):
r"""
Converts a URI parts to corresponding IRI parts in a given charset.
Examples for URI versus IRI:
:param path: The path of URI to convert.
:param query: The query string of URI to convert.
:param fragment: The fragment of URI to convert.
"""
path = url_unquote(path, '%/;?')
query = url_unquote(query, '%;/?:@&=+,$#')
fragment = url_unquote(fragment, '%;/?:@&=+,$#')
return path, query, fragment | [
"def",
"uri_to_iri_parts",
"(",
"path",
",",
"query",
",",
"fragment",
")",
":",
"path",
"=",
"url_unquote",
"(",
"path",
",",
"'%/;?'",
")",
"query",
"=",
"url_unquote",
"(",
"query",
",",
"'%;/?:@&=+,$#'",
")",
"fragment",
"=",
"url_unquote",
"(",
"fragm... | r"""
Converts a URI parts to corresponding IRI parts in a given charset.
Examples for URI versus IRI:
:param path: The path of URI to convert.
:param query: The query string of URI to convert.
:param fragment: The fragment of URI to convert. | [
"r",
"Converts",
"a",
"URI",
"parts",
"to",
"corresponding",
"IRI",
"parts",
"in",
"a",
"given",
"charset",
"."
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/utils/url.py#L64-L77 |
CivicSpleen/ambry | ambry/support/__init__.py | default_bundle_config | def default_bundle_config():
"""Return the default bundle config file as an AttrDict."""
import os
from ambry.util import AttrDict
config = AttrDict()
f = os.path.join(
os.path.dirname(
os.path.realpath(__file__)),
'bundle.yaml')
config.update_yaml(f)
return config | python | def default_bundle_config():
"""Return the default bundle config file as an AttrDict."""
import os
from ambry.util import AttrDict
config = AttrDict()
f = os.path.join(
os.path.dirname(
os.path.realpath(__file__)),
'bundle.yaml')
config.update_yaml(f)
return config | [
"def",
"default_bundle_config",
"(",
")",
":",
"import",
"os",
"from",
"ambry",
".",
"util",
"import",
"AttrDict",
"config",
"=",
"AttrDict",
"(",
")",
"f",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
... | Return the default bundle config file as an AttrDict. | [
"Return",
"the",
"default",
"bundle",
"config",
"file",
"as",
"an",
"AttrDict",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/support/__init__.py#L2-L16 |
CivicSpleen/ambry | setup.py | find_package_data | def find_package_data():
""" Returns package_data, because setuptools is too stupid to handle nested directories.
Returns:
dict: key is "ambry", value is list of paths.
"""
l = list()
for start in ('ambry/support', 'ambry/bundle/default_files'):
for root, dirs, files in os.walk(start):
for f in files:
if f.endswith('.pyc'):
continue
path = os.path.join(root, f).replace('ambry/', '')
l.append(path)
return {'ambry': l} | python | def find_package_data():
""" Returns package_data, because setuptools is too stupid to handle nested directories.
Returns:
dict: key is "ambry", value is list of paths.
"""
l = list()
for start in ('ambry/support', 'ambry/bundle/default_files'):
for root, dirs, files in os.walk(start):
for f in files:
if f.endswith('.pyc'):
continue
path = os.path.join(root, f).replace('ambry/', '')
l.append(path)
return {'ambry': l} | [
"def",
"find_package_data",
"(",
")",
":",
"l",
"=",
"list",
"(",
")",
"for",
"start",
"in",
"(",
"'ambry/support'",
",",
"'ambry/bundle/default_files'",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"start",
")",
":... | Returns package_data, because setuptools is too stupid to handle nested directories.
Returns:
dict: key is "ambry", value is list of paths. | [
"Returns",
"package_data",
"because",
"setuptools",
"is",
"too",
"stupid",
"to",
"handle",
"nested",
"directories",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/setup.py#L29-L49 |
CivicSpleen/ambry | ambry/orm/file.py | File.update | def update(self, of):
"""Update a file from another file, for copying"""
# The other values should be set when the file object is created with dataset.bsfile()
for p in ('mime_type', 'preference', 'state', 'hash', 'modified', 'size', 'contents', 'source_hash', 'data'):
setattr(self, p, getattr(of, p))
return self | python | def update(self, of):
"""Update a file from another file, for copying"""
# The other values should be set when the file object is created with dataset.bsfile()
for p in ('mime_type', 'preference', 'state', 'hash', 'modified', 'size', 'contents', 'source_hash', 'data'):
setattr(self, p, getattr(of, p))
return self | [
"def",
"update",
"(",
"self",
",",
"of",
")",
":",
"# The other values should be set when the file object is created with dataset.bsfile()",
"for",
"p",
"in",
"(",
"'mime_type'",
",",
"'preference'",
",",
"'state'",
",",
"'hash'",
",",
"'modified'",
",",
"'size'",
","... | Update a file from another file, for copying | [
"Update",
"a",
"file",
"from",
"another",
"file",
"for",
"copying"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/file.py#L80-L87 |
CivicSpleen/ambry | ambry/orm/file.py | File.unpacked_contents | def unpacked_contents(self):
"""
:return:
"""
from nbformat import read
import msgpack
if self.mime_type == 'text/plain':
return self.contents.decode('utf-8')
elif self.mime_type == 'application/msgpack':
# FIXME: Note: I'm not sure that encoding='utf-8' will not break old data.
# We need utf-8 to make python3 to work. (kazbek)
# return msgpack.unpackb(self.contents)
return msgpack.unpackb(self.contents, encoding='utf-8')
else:
return self.contents | python | def unpacked_contents(self):
"""
:return:
"""
from nbformat import read
import msgpack
if self.mime_type == 'text/plain':
return self.contents.decode('utf-8')
elif self.mime_type == 'application/msgpack':
# FIXME: Note: I'm not sure that encoding='utf-8' will not break old data.
# We need utf-8 to make python3 to work. (kazbek)
# return msgpack.unpackb(self.contents)
return msgpack.unpackb(self.contents, encoding='utf-8')
else:
return self.contents | [
"def",
"unpacked_contents",
"(",
"self",
")",
":",
"from",
"nbformat",
"import",
"read",
"import",
"msgpack",
"if",
"self",
".",
"mime_type",
"==",
"'text/plain'",
":",
"return",
"self",
".",
"contents",
".",
"decode",
"(",
"'utf-8'",
")",
"elif",
"self",
... | :return: | [
":",
"return",
":"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/file.py#L90-L107 |
CivicSpleen/ambry | ambry/orm/file.py | File.dict_row_reader | def dict_row_reader(self):
""" Unpacks message pack rows into a stream of dicts. """
rows = self.unpacked_contents
if not rows:
return
header = rows.pop(0)
for row in rows:
yield dict(list(zip(header, row))) | python | def dict_row_reader(self):
""" Unpacks message pack rows into a stream of dicts. """
rows = self.unpacked_contents
if not rows:
return
header = rows.pop(0)
for row in rows:
yield dict(list(zip(header, row))) | [
"def",
"dict_row_reader",
"(",
"self",
")",
":",
"rows",
"=",
"self",
".",
"unpacked_contents",
"if",
"not",
"rows",
":",
"return",
"header",
"=",
"rows",
".",
"pop",
"(",
"0",
")",
"for",
"row",
"in",
"rows",
":",
"yield",
"dict",
"(",
"list",
"(",
... | Unpacks message pack rows into a stream of dicts. | [
"Unpacks",
"message",
"pack",
"rows",
"into",
"a",
"stream",
"of",
"dicts",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/file.py#L110-L121 |
CivicSpleen/ambry | ambry/orm/file.py | File.update_contents | def update_contents(self, contents, mime_type):
"""Update the contents and set the hash and modification time"""
import hashlib
import time
new_size = len(contents)
self.mime_type = mime_type
if mime_type == 'text/plain':
self.contents = contents.encode('utf-8')
else:
self.contents = contents
old_hash = self.hash
self.hash = hashlib.md5(self.contents).hexdigest()
if self.size and (old_hash != self.hash):
self.modified = int(time.time())
self.size = new_size | python | def update_contents(self, contents, mime_type):
"""Update the contents and set the hash and modification time"""
import hashlib
import time
new_size = len(contents)
self.mime_type = mime_type
if mime_type == 'text/plain':
self.contents = contents.encode('utf-8')
else:
self.contents = contents
old_hash = self.hash
self.hash = hashlib.md5(self.contents).hexdigest()
if self.size and (old_hash != self.hash):
self.modified = int(time.time())
self.size = new_size | [
"def",
"update_contents",
"(",
"self",
",",
"contents",
",",
"mime_type",
")",
":",
"import",
"hashlib",
"import",
"time",
"new_size",
"=",
"len",
"(",
"contents",
")",
"self",
".",
"mime_type",
"=",
"mime_type",
"if",
"mime_type",
"==",
"'text/plain'",
":",... | Update the contents and set the hash and modification time | [
"Update",
"the",
"contents",
"and",
"set",
"the",
"hash",
"and",
"modification",
"time"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/file.py#L123-L144 |
CivicSpleen/ambry | ambry/orm/file.py | File.dict | def dict(self):
"""A dict that holds key/values for all of the properties in the
object.
:return:
"""
d = {p.key: getattr(self, p.key) for p in self.__mapper__.attrs
if p.key not in ('contents', 'dataset')}
d['modified_datetime'] = self.modified_datetime
d['modified_ago'] = self.modified_ago
return d | python | def dict(self):
"""A dict that holds key/values for all of the properties in the
object.
:return:
"""
d = {p.key: getattr(self, p.key) for p in self.__mapper__.attrs
if p.key not in ('contents', 'dataset')}
d['modified_datetime'] = self.modified_datetime
d['modified_ago'] = self.modified_ago
return d | [
"def",
"dict",
"(",
"self",
")",
":",
"d",
"=",
"{",
"p",
".",
"key",
":",
"getattr",
"(",
"self",
",",
"p",
".",
"key",
")",
"for",
"p",
"in",
"self",
".",
"__mapper__",
".",
"attrs",
"if",
"p",
".",
"key",
"not",
"in",
"(",
"'contents'",
",... | A dict that holds key/values for all of the properties in the
object.
:return: | [
"A",
"dict",
"that",
"holds",
"key",
"/",
"values",
"for",
"all",
"of",
"the",
"properties",
"in",
"the",
"object",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/file.py#L180-L193 |
CivicSpleen/ambry | ambry/orm/file.py | File.before_insert | def before_insert(mapper, conn, target):
"""event.listen method for Sqlalchemy to set the sequence for this
object and create an ObjectNumber value for the id_"""
from sqlalchemy import text
if not target.id:
sql = text('SELECT max(f_id)+1 FROM files WHERE f_d_vid = :did')
target.id, = conn.execute(sql, did=target.d_vid).fetchone()
if not target.id:
target.id = 1
if target.contents and isinstance(target.contents, six.text_type):
target.contents = target.contents.encode('utf-8')
File.before_update(mapper, conn, target) | python | def before_insert(mapper, conn, target):
"""event.listen method for Sqlalchemy to set the sequence for this
object and create an ObjectNumber value for the id_"""
from sqlalchemy import text
if not target.id:
sql = text('SELECT max(f_id)+1 FROM files WHERE f_d_vid = :did')
target.id, = conn.execute(sql, did=target.d_vid).fetchone()
if not target.id:
target.id = 1
if target.contents and isinstance(target.contents, six.text_type):
target.contents = target.contents.encode('utf-8')
File.before_update(mapper, conn, target) | [
"def",
"before_insert",
"(",
"mapper",
",",
"conn",
",",
"target",
")",
":",
"from",
"sqlalchemy",
"import",
"text",
"if",
"not",
"target",
".",
"id",
":",
"sql",
"=",
"text",
"(",
"'SELECT max(f_id)+1 FROM files WHERE f_d_vid = :did'",
")",
"target",
".",
"id... | event.listen method for Sqlalchemy to set the sequence for this
object and create an ObjectNumber value for the id_ | [
"event",
".",
"listen",
"method",
"for",
"Sqlalchemy",
"to",
"set",
"the",
"sequence",
"for",
"this",
"object",
"and",
"create",
"an",
"ObjectNumber",
"value",
"for",
"the",
"id_"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/file.py#L206-L222 |
project-ncl/pnc-cli | pnc_cli/swagger_client/api_client.py | ApiClient.__deserialize_primitive | def __deserialize_primitive(self, data, klass):
"""
Deserializes string to primitive type.
:param data: str.
:param klass: class literal.
:return: int, long, float, str, bool.
"""
try:
return klass(data)
except UnicodeEncodeError:
return text(data)
except TypeError:
return data | python | def __deserialize_primitive(self, data, klass):
"""
Deserializes string to primitive type.
:param data: str.
:param klass: class literal.
:return: int, long, float, str, bool.
"""
try:
return klass(data)
except UnicodeEncodeError:
return text(data)
except TypeError:
return data | [
"def",
"__deserialize_primitive",
"(",
"self",
",",
"data",
",",
"klass",
")",
":",
"try",
":",
"return",
"klass",
"(",
"data",
")",
"except",
"UnicodeEncodeError",
":",
"return",
"text",
"(",
"data",
")",
"except",
"TypeError",
":",
"return",
"data"
] | Deserializes string to primitive type.
:param data: str.
:param klass: class literal.
:return: int, long, float, str, bool. | [
"Deserializes",
"string",
"to",
"primitive",
"type",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/api_client.py#L547-L561 |
project-ncl/pnc-cli | pnc_cli/swagger_client/api_client.py | ApiClient.__deserialize_datetime | def __deserialize_datetime(self, string):
"""
Deserializes string to datetime.
The string should be in iso8601 datetime format.
:param string: str.
:return: datetime.
"""
try:
from dateutil.parser import parse
timestr = str(datetime.fromtimestamp(string/1000))
return parse(timestr)
except ImportError:
return string
except ValueError:
raise ApiException(
status=0,
reason=(
"Failed to parse `{0}` into a datetime object"
.format(string)
)
) | python | def __deserialize_datetime(self, string):
"""
Deserializes string to datetime.
The string should be in iso8601 datetime format.
:param string: str.
:return: datetime.
"""
try:
from dateutil.parser import parse
timestr = str(datetime.fromtimestamp(string/1000))
return parse(timestr)
except ImportError:
return string
except ValueError:
raise ApiException(
status=0,
reason=(
"Failed to parse `{0}` into a datetime object"
.format(string)
)
) | [
"def",
"__deserialize_datetime",
"(",
"self",
",",
"string",
")",
":",
"try",
":",
"from",
"dateutil",
".",
"parser",
"import",
"parse",
"timestr",
"=",
"str",
"(",
"datetime",
".",
"fromtimestamp",
"(",
"string",
"/",
"1000",
")",
")",
"return",
"parse",
... | Deserializes string to datetime.
The string should be in iso8601 datetime format.
:param string: str.
:return: datetime. | [
"Deserializes",
"string",
"to",
"datetime",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/api_client.py#L589-L611 |
solidsnack/tsv | tsv.py | un | def un(source, wrapper=list, error_bad_lines=True):
"""Parse a text stream to TSV
If the source is a string, it is converted to a line-iterable stream. If
it is a file handle or other object, we assume that we can iterate over
the lines in it.
The result is a generator, and what it contains depends on whether the
second argument is set and what it is set to.
If the second argument is set to list, the default, then each element of
the result is a list of strings. If it is set to a class generated with
namedtuple(), then each element is an instance of this class, or None if
there were too many or too few fields.
Although newline separated input is preferred, carriage-return-newline is
accepted on every platform.
Since there is no definite order to the fields of a dict, there is no
consistent way to format dicts for output. To avoid the asymmetry of a
type that can be read but not written, plain dictionary parsing is
omitted.
"""
if isinstance(source, six.string_types):
source = six.StringIO(source)
# Prepare source lines for reading
rows = parse_lines(source)
# Get columns
if is_namedtuple(wrapper):
columns = wrapper._fields
wrapper = wrapper._make
else:
columns = next(rows, None)
if columns is not None:
i, columns = columns
yield wrapper(columns)
# Get values
for i, values in rows:
if check_line_consistency(columns, values, i, error_bad_lines):
yield wrapper(values) | python | def un(source, wrapper=list, error_bad_lines=True):
"""Parse a text stream to TSV
If the source is a string, it is converted to a line-iterable stream. If
it is a file handle or other object, we assume that we can iterate over
the lines in it.
The result is a generator, and what it contains depends on whether the
second argument is set and what it is set to.
If the second argument is set to list, the default, then each element of
the result is a list of strings. If it is set to a class generated with
namedtuple(), then each element is an instance of this class, or None if
there were too many or too few fields.
Although newline separated input is preferred, carriage-return-newline is
accepted on every platform.
Since there is no definite order to the fields of a dict, there is no
consistent way to format dicts for output. To avoid the asymmetry of a
type that can be read but not written, plain dictionary parsing is
omitted.
"""
if isinstance(source, six.string_types):
source = six.StringIO(source)
# Prepare source lines for reading
rows = parse_lines(source)
# Get columns
if is_namedtuple(wrapper):
columns = wrapper._fields
wrapper = wrapper._make
else:
columns = next(rows, None)
if columns is not None:
i, columns = columns
yield wrapper(columns)
# Get values
for i, values in rows:
if check_line_consistency(columns, values, i, error_bad_lines):
yield wrapper(values) | [
"def",
"un",
"(",
"source",
",",
"wrapper",
"=",
"list",
",",
"error_bad_lines",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"source",
",",
"six",
".",
"string_types",
")",
":",
"source",
"=",
"six",
".",
"StringIO",
"(",
"source",
")",
"# Prepare ... | Parse a text stream to TSV
If the source is a string, it is converted to a line-iterable stream. If
it is a file handle or other object, we assume that we can iterate over
the lines in it.
The result is a generator, and what it contains depends on whether the
second argument is set and what it is set to.
If the second argument is set to list, the default, then each element of
the result is a list of strings. If it is set to a class generated with
namedtuple(), then each element is an instance of this class, or None if
there were too many or too few fields.
Although newline separated input is preferred, carriage-return-newline is
accepted on every platform.
Since there is no definite order to the fields of a dict, there is no
consistent way to format dicts for output. To avoid the asymmetry of a
type that can be read but not written, plain dictionary parsing is
omitted. | [
"Parse",
"a",
"text",
"stream",
"to",
"TSV"
] | train | https://github.com/solidsnack/tsv/blob/2d3c0f45477c8ffbed5cd61050855c4e4617e6be/tsv.py#L10-L52 |
solidsnack/tsv | tsv.py | to | def to(items, output=None):
"""Present a collection of items as TSV
The items in the collection can themselves be any iterable collection.
(Single field structures should be represented as one tuples.)
With no output parameter, a generator of strings is returned. If an output
parameter is passed, it should be a file-like object. Output is always
newline separated.
"""
strings = (format_collection(item) for item in items)
if output is None:
return strings
else:
for s in strings:
output.write(s + '\n') | python | def to(items, output=None):
"""Present a collection of items as TSV
The items in the collection can themselves be any iterable collection.
(Single field structures should be represented as one tuples.)
With no output parameter, a generator of strings is returned. If an output
parameter is passed, it should be a file-like object. Output is always
newline separated.
"""
strings = (format_collection(item) for item in items)
if output is None:
return strings
else:
for s in strings:
output.write(s + '\n') | [
"def",
"to",
"(",
"items",
",",
"output",
"=",
"None",
")",
":",
"strings",
"=",
"(",
"format_collection",
"(",
"item",
")",
"for",
"item",
"in",
"items",
")",
"if",
"output",
"is",
"None",
":",
"return",
"strings",
"else",
":",
"for",
"s",
"in",
"... | Present a collection of items as TSV
The items in the collection can themselves be any iterable collection.
(Single field structures should be represented as one tuples.)
With no output parameter, a generator of strings is returned. If an output
parameter is passed, it should be a file-like object. Output is always
newline separated. | [
"Present",
"a",
"collection",
"of",
"items",
"as",
"TSV"
] | train | https://github.com/solidsnack/tsv/blob/2d3c0f45477c8ffbed5cd61050855c4e4617e6be/tsv.py#L112-L127 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/users_api.py | UsersApi.get_logged_user | def get_logged_user(self, **kwargs):
"""
Gets logged user and in case not existing creates a new one
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_logged_user(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: UserSingleton
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_logged_user_with_http_info(**kwargs)
else:
(data) = self.get_logged_user_with_http_info(**kwargs)
return data | python | def get_logged_user(self, **kwargs):
"""
Gets logged user and in case not existing creates a new one
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_logged_user(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: UserSingleton
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_logged_user_with_http_info(**kwargs)
else:
(data) = self.get_logged_user_with_http_info(**kwargs)
return data | [
"def",
"get_logged_user",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"get_logged_user_with_http_info",
"(",
"*",... | Gets logged user and in case not existing creates a new one
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_logged_user(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: UserSingleton
If the method is called asynchronously,
returns the request thread. | [
"Gets",
"logged",
"user",
"and",
"in",
"case",
"not",
"existing",
"creates",
"a",
"new",
"one",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/users_api.py#L382-L405 |
CivicSpleen/ambry | ambry/cli/bundle.py | get_bundle_ref | def get_bundle_ref(args, l, use_history=False):
""" Use a variety of methods to determine which bundle to use
:param args:
:return:
"""
if not use_history:
if args.id:
return (args.id, '-i argument')
if hasattr(args, 'bundle_ref') and args.bundle_ref:
return (args.bundle_ref, 'bundle_ref argument')
if 'AMBRY_BUNDLE' in os.environ:
return (os.environ['AMBRY_BUNDLE'], 'environment')
cwd_bundle = os.path.join(os.getcwd(), 'bundle.yaml')
if os.path.exists(cwd_bundle):
with open(cwd_bundle) as f:
from ambry.identity import Identity
config = yaml.load(f)
try:
ident = Identity.from_dict(config['identity'])
return (ident.vid, 'directory')
except KeyError:
pass
history = l.edit_history()
if history:
return (history[0].d_vid, 'history')
return None, None | python | def get_bundle_ref(args, l, use_history=False):
""" Use a variety of methods to determine which bundle to use
:param args:
:return:
"""
if not use_history:
if args.id:
return (args.id, '-i argument')
if hasattr(args, 'bundle_ref') and args.bundle_ref:
return (args.bundle_ref, 'bundle_ref argument')
if 'AMBRY_BUNDLE' in os.environ:
return (os.environ['AMBRY_BUNDLE'], 'environment')
cwd_bundle = os.path.join(os.getcwd(), 'bundle.yaml')
if os.path.exists(cwd_bundle):
with open(cwd_bundle) as f:
from ambry.identity import Identity
config = yaml.load(f)
try:
ident = Identity.from_dict(config['identity'])
return (ident.vid, 'directory')
except KeyError:
pass
history = l.edit_history()
if history:
return (history[0].d_vid, 'history')
return None, None | [
"def",
"get_bundle_ref",
"(",
"args",
",",
"l",
",",
"use_history",
"=",
"False",
")",
":",
"if",
"not",
"use_history",
":",
"if",
"args",
".",
"id",
":",
"return",
"(",
"args",
".",
"id",
",",
"'-i argument'",
")",
"if",
"hasattr",
"(",
"args",
",",... | Use a variety of methods to determine which bundle to use
:param args:
:return: | [
"Use",
"a",
"variety",
"of",
"methods",
"to",
"determine",
"which",
"bundle",
"to",
"use"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/cli/bundle.py#L535-L573 |
CivicSpleen/ambry | ambry/cli/bundle.py | bundle_variant | def bundle_variant(args, l, rc):
"""Create a new bundle as a variant of an existing bundle"""
from ambry.orm.exc import ConflictError
ob = l.bundle(args.ref)
d = dict(
dataset=args.dataset or ob.identity.dataset,
revision=args.revision,
source=args.source or ob.identity.source,
bspace=args.space or ob.identity.bspace,
subset=args.subset or ob.identity.subset,
btime=args.time or ob.identity.btime,
variation=args.variation or ob.identity.variation)
try:
ambry_account = rc.accounts.get('ambry', {})
except:
ambry_account = None
if not ambry_account:
fatal("Failed to get an accounts.ambry entry from the configuration. ")
if not ambry_account.get('name') or not ambry_account.get('email'):
fatal('Must set accounts.ambry.email and accounts.ambry.name n account config file')
try:
b = l.new_bundle(assignment_class=args.key, **d)
b.metadata.contacts.wrangler.name = ambry_account.get('name')
b.metadata.contacts.wrangler.email = ambry_account.get('email')
b.commit()
except ConflictError:
fatal("Can't create dataset; one with a conflicting name already exists")
# Now, need to copy over all of the partitions into the new bundle.
for p in ob.partitions:
ds = b.dataset.new_source(p.name, ref=p.name, reftype='partition')
print ds
b.build_source_files.sources.objects_to_record()
b.commit() | python | def bundle_variant(args, l, rc):
"""Create a new bundle as a variant of an existing bundle"""
from ambry.orm.exc import ConflictError
ob = l.bundle(args.ref)
d = dict(
dataset=args.dataset or ob.identity.dataset,
revision=args.revision,
source=args.source or ob.identity.source,
bspace=args.space or ob.identity.bspace,
subset=args.subset or ob.identity.subset,
btime=args.time or ob.identity.btime,
variation=args.variation or ob.identity.variation)
try:
ambry_account = rc.accounts.get('ambry', {})
except:
ambry_account = None
if not ambry_account:
fatal("Failed to get an accounts.ambry entry from the configuration. ")
if not ambry_account.get('name') or not ambry_account.get('email'):
fatal('Must set accounts.ambry.email and accounts.ambry.name n account config file')
try:
b = l.new_bundle(assignment_class=args.key, **d)
b.metadata.contacts.wrangler.name = ambry_account.get('name')
b.metadata.contacts.wrangler.email = ambry_account.get('email')
b.commit()
except ConflictError:
fatal("Can't create dataset; one with a conflicting name already exists")
# Now, need to copy over all of the partitions into the new bundle.
for p in ob.partitions:
ds = b.dataset.new_source(p.name, ref=p.name, reftype='partition')
print ds
b.build_source_files.sources.objects_to_record()
b.commit() | [
"def",
"bundle_variant",
"(",
"args",
",",
"l",
",",
"rc",
")",
":",
"from",
"ambry",
".",
"orm",
".",
"exc",
"import",
"ConflictError",
"ob",
"=",
"l",
".",
"bundle",
"(",
"args",
".",
"ref",
")",
"d",
"=",
"dict",
"(",
"dataset",
"=",
"args",
"... | Create a new bundle as a variant of an existing bundle | [
"Create",
"a",
"new",
"bundle",
"as",
"a",
"variant",
"of",
"an",
"existing",
"bundle"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/cli/bundle.py#L802-L845 |
CivicSpleen/ambry | ambry/cli/bundle.py | bundle_new | def bundle_new(args, l, rc):
"""Create a new bundle"""
from ambry.orm.exc import ConflictError
d = dict(
dataset=args.dataset,
revision=args.revision,
source=args.source,
bspace=args.space,
subset=args.subset,
btime=args.time,
variation=args.variation)
try:
ambry_account = rc.accounts.get('ambry', {})
except:
ambry_account = None
if not ambry_account:
fatal("Failed to get an accounts.ambry entry from the configuration. ")
if not ambry_account.get('name') or not ambry_account.get('email'):
fatal('Must set accounts.ambry.email and accounts.ambry.name n account config file')
if args.dryrun:
from ..identity import Identity
d['revision'] = 1
d['id'] = 'dXXX'
print(str(Identity.from_dict(d)))
return
try:
b = l.new_bundle(assignment_class=args.key, **d)
if ambry_account:
b.metadata.contacts.wrangler = ambry_account
b.build_source_files.bundle_meta.objects_to_record()
b.commit()
except ConflictError:
fatal("Can't create dataset; one with a conflicting name already exists")
print(b.identity.fqname) | python | def bundle_new(args, l, rc):
"""Create a new bundle"""
from ambry.orm.exc import ConflictError
d = dict(
dataset=args.dataset,
revision=args.revision,
source=args.source,
bspace=args.space,
subset=args.subset,
btime=args.time,
variation=args.variation)
try:
ambry_account = rc.accounts.get('ambry', {})
except:
ambry_account = None
if not ambry_account:
fatal("Failed to get an accounts.ambry entry from the configuration. ")
if not ambry_account.get('name') or not ambry_account.get('email'):
fatal('Must set accounts.ambry.email and accounts.ambry.name n account config file')
if args.dryrun:
from ..identity import Identity
d['revision'] = 1
d['id'] = 'dXXX'
print(str(Identity.from_dict(d)))
return
try:
b = l.new_bundle(assignment_class=args.key, **d)
if ambry_account:
b.metadata.contacts.wrangler = ambry_account
b.build_source_files.bundle_meta.objects_to_record()
b.commit()
except ConflictError:
fatal("Can't create dataset; one with a conflicting name already exists")
print(b.identity.fqname) | [
"def",
"bundle_new",
"(",
"args",
",",
"l",
",",
"rc",
")",
":",
"from",
"ambry",
".",
"orm",
".",
"exc",
"import",
"ConflictError",
"d",
"=",
"dict",
"(",
"dataset",
"=",
"args",
".",
"dataset",
",",
"revision",
"=",
"args",
".",
"revision",
",",
... | Create a new bundle | [
"Create",
"a",
"new",
"bundle"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/cli/bundle.py#L1408-L1452 |
ambitioninc/django-dynamic-initial-data | dynamic_initial_data/base.py | InitialDataUpdater.load_app | def load_app(self, app):
"""
Tries to load an initial data class for a specified app. If the specified file does not exist,
an error will be raised. If the class does exist, but it isn't a subclass of `BaseInitialData`
then None will be returned.
:param app: The name of the app in which to load the initial data class. This should be the same
path as defined in settings.INSTALLED_APPS
:type app: str
:return: A subclass instance of BaseInitialData or None
:rtype: BaseInitialData or None
"""
if self.loaded_apps.get(app):
return self.loaded_apps.get(app)
self.loaded_apps[app] = None
initial_data_class = import_string(self.get_class_path(app))
if issubclass(initial_data_class, BaseInitialData):
self.log('Loaded app {0}'.format(app))
self.loaded_apps[app] = initial_data_class
return self.loaded_apps[app] | python | def load_app(self, app):
"""
Tries to load an initial data class for a specified app. If the specified file does not exist,
an error will be raised. If the class does exist, but it isn't a subclass of `BaseInitialData`
then None will be returned.
:param app: The name of the app in which to load the initial data class. This should be the same
path as defined in settings.INSTALLED_APPS
:type app: str
:return: A subclass instance of BaseInitialData or None
:rtype: BaseInitialData or None
"""
if self.loaded_apps.get(app):
return self.loaded_apps.get(app)
self.loaded_apps[app] = None
initial_data_class = import_string(self.get_class_path(app))
if issubclass(initial_data_class, BaseInitialData):
self.log('Loaded app {0}'.format(app))
self.loaded_apps[app] = initial_data_class
return self.loaded_apps[app] | [
"def",
"load_app",
"(",
"self",
",",
"app",
")",
":",
"if",
"self",
".",
"loaded_apps",
".",
"get",
"(",
"app",
")",
":",
"return",
"self",
".",
"loaded_apps",
".",
"get",
"(",
"app",
")",
"self",
".",
"loaded_apps",
"[",
"app",
"]",
"=",
"None",
... | Tries to load an initial data class for a specified app. If the specified file does not exist,
an error will be raised. If the class does exist, but it isn't a subclass of `BaseInitialData`
then None will be returned.
:param app: The name of the app in which to load the initial data class. This should be the same
path as defined in settings.INSTALLED_APPS
:type app: str
:return: A subclass instance of BaseInitialData or None
:rtype: BaseInitialData or None | [
"Tries",
"to",
"load",
"an",
"initial",
"data",
"class",
"for",
"a",
"specified",
"app",
".",
"If",
"the",
"specified",
"file",
"does",
"not",
"exist",
"an",
"error",
"will",
"be",
"raised",
".",
"If",
"the",
"class",
"does",
"exist",
"but",
"it",
"isn... | train | https://github.com/ambitioninc/django-dynamic-initial-data/blob/27b7bf4ac31b465cc14127832d0d4b97362cc40f/dynamic_initial_data/base.py#L75-L95 |
ambitioninc/django-dynamic-initial-data | dynamic_initial_data/base.py | InitialDataUpdater.update_app | def update_app(self, app):
"""
Loads and runs `update_initial_data` of the specified app. Any dependencies contained within the
initial data class will be run recursively. Dependency cycles are checked for and a cache is built
for updated apps to prevent updating the same app more than once.
:param app: The name of the app to update. This should be the same path as defined
in settings.INSTALLED_APPS
:type app: str
"""
# don't update this app if it has already been updated
if app in self.updated_apps:
return
# load the initial data class
try:
initial_data_class = self.load_app(app)
except ImportError as e:
message = str(e)
# Check if this error is simply the app not having initial data
if 'No module named' in message and 'fixtures' in message:
self.log('No initial data file for {0}'.format(app))
return
else:
# This is an actual import error we should know about
raise
self.log('Checking dependencies for {0}'.format(app))
# get dependency list
dependencies = self.get_dependency_call_list(app)
# update initial data of dependencies
for dependency in dependencies:
self.update_app(dependency)
self.log('Updating app {0}'.format(app))
# Update the initial data of the app and gather any objects returned for deletion. Objects registered for
# deletion can either be returned from the update_initial_data function or programmatically added with the
# register_for_deletion function in the BaseInitialData class.
initial_data_instance = initial_data_class()
model_objs_registered_for_deletion = initial_data_instance.update_initial_data() or []
model_objs_registered_for_deletion.extend(initial_data_instance.get_model_objs_registered_for_deletion())
# Add the objects to be deleted from the app to the global list of objects to be deleted.
self.model_objs_registered_for_deletion.extend(model_objs_registered_for_deletion)
# keep track that this app has been updated
self.updated_apps.add(app) | python | def update_app(self, app):
"""
Loads and runs `update_initial_data` of the specified app. Any dependencies contained within the
initial data class will be run recursively. Dependency cycles are checked for and a cache is built
for updated apps to prevent updating the same app more than once.
:param app: The name of the app to update. This should be the same path as defined
in settings.INSTALLED_APPS
:type app: str
"""
# don't update this app if it has already been updated
if app in self.updated_apps:
return
# load the initial data class
try:
initial_data_class = self.load_app(app)
except ImportError as e:
message = str(e)
# Check if this error is simply the app not having initial data
if 'No module named' in message and 'fixtures' in message:
self.log('No initial data file for {0}'.format(app))
return
else:
# This is an actual import error we should know about
raise
self.log('Checking dependencies for {0}'.format(app))
# get dependency list
dependencies = self.get_dependency_call_list(app)
# update initial data of dependencies
for dependency in dependencies:
self.update_app(dependency)
self.log('Updating app {0}'.format(app))
# Update the initial data of the app and gather any objects returned for deletion. Objects registered for
# deletion can either be returned from the update_initial_data function or programmatically added with the
# register_for_deletion function in the BaseInitialData class.
initial_data_instance = initial_data_class()
model_objs_registered_for_deletion = initial_data_instance.update_initial_data() or []
model_objs_registered_for_deletion.extend(initial_data_instance.get_model_objs_registered_for_deletion())
# Add the objects to be deleted from the app to the global list of objects to be deleted.
self.model_objs_registered_for_deletion.extend(model_objs_registered_for_deletion)
# keep track that this app has been updated
self.updated_apps.add(app) | [
"def",
"update_app",
"(",
"self",
",",
"app",
")",
":",
"# don't update this app if it has already been updated",
"if",
"app",
"in",
"self",
".",
"updated_apps",
":",
"return",
"# load the initial data class",
"try",
":",
"initial_data_class",
"=",
"self",
".",
"load_... | Loads and runs `update_initial_data` of the specified app. Any dependencies contained within the
initial data class will be run recursively. Dependency cycles are checked for and a cache is built
for updated apps to prevent updating the same app more than once.
:param app: The name of the app to update. This should be the same path as defined
in settings.INSTALLED_APPS
:type app: str | [
"Loads",
"and",
"runs",
"update_initial_data",
"of",
"the",
"specified",
"app",
".",
"Any",
"dependencies",
"contained",
"within",
"the",
"initial",
"data",
"class",
"will",
"be",
"run",
"recursively",
".",
"Dependency",
"cycles",
"are",
"checked",
"for",
"and",... | train | https://github.com/ambitioninc/django-dynamic-initial-data/blob/27b7bf4ac31b465cc14127832d0d4b97362cc40f/dynamic_initial_data/base.py#L98-L147 |
ambitioninc/django-dynamic-initial-data | dynamic_initial_data/base.py | InitialDataUpdater.handle_deletions | def handle_deletions(self):
"""
Manages handling deletions of objects that were previously managed by the initial data process but no longer
managed. It does so by mantaining a list of receipts for model objects that are registered for deletion on
each round of initial data processing. Any receipts that are from previous rounds and not the current
round will be deleted.
"""
deduplicated_objs = {}
for model in self.model_objs_registered_for_deletion:
key = '{0}:{1}'.format(
ContentType.objects.get_for_model(model, for_concrete_model=False),
model.id
)
deduplicated_objs[key] = model
# Create receipts for every object registered for deletion
now = timezone.now()
registered_for_deletion_receipts = [
RegisteredForDeletionReceipt(
model_obj_type=ContentType.objects.get_for_model(model_obj, for_concrete_model=False),
model_obj_id=model_obj.id,
register_time=now)
for model_obj in deduplicated_objs.values()
]
# Do a bulk upsert on all of the receipts, updating their registration time.
RegisteredForDeletionReceipt.objects.bulk_upsert(
registered_for_deletion_receipts, ['model_obj_type_id', 'model_obj_id'], update_fields=['register_time'])
# Delete all receipts and their associated model objects that weren't updated
for receipt in RegisteredForDeletionReceipt.objects.exclude(register_time=now):
try:
receipt.model_obj.delete()
except: # noqa
# The model object may no longer be there, its ctype may be invalid, or it might be protected.
# Regardless, the model object cannot be deleted, so go ahead and delete its receipt.
pass
receipt.delete() | python | def handle_deletions(self):
"""
Manages handling deletions of objects that were previously managed by the initial data process but no longer
managed. It does so by mantaining a list of receipts for model objects that are registered for deletion on
each round of initial data processing. Any receipts that are from previous rounds and not the current
round will be deleted.
"""
deduplicated_objs = {}
for model in self.model_objs_registered_for_deletion:
key = '{0}:{1}'.format(
ContentType.objects.get_for_model(model, for_concrete_model=False),
model.id
)
deduplicated_objs[key] = model
# Create receipts for every object registered for deletion
now = timezone.now()
registered_for_deletion_receipts = [
RegisteredForDeletionReceipt(
model_obj_type=ContentType.objects.get_for_model(model_obj, for_concrete_model=False),
model_obj_id=model_obj.id,
register_time=now)
for model_obj in deduplicated_objs.values()
]
# Do a bulk upsert on all of the receipts, updating their registration time.
RegisteredForDeletionReceipt.objects.bulk_upsert(
registered_for_deletion_receipts, ['model_obj_type_id', 'model_obj_id'], update_fields=['register_time'])
# Delete all receipts and their associated model objects that weren't updated
for receipt in RegisteredForDeletionReceipt.objects.exclude(register_time=now):
try:
receipt.model_obj.delete()
except: # noqa
# The model object may no longer be there, its ctype may be invalid, or it might be protected.
# Regardless, the model object cannot be deleted, so go ahead and delete its receipt.
pass
receipt.delete() | [
"def",
"handle_deletions",
"(",
"self",
")",
":",
"deduplicated_objs",
"=",
"{",
"}",
"for",
"model",
"in",
"self",
".",
"model_objs_registered_for_deletion",
":",
"key",
"=",
"'{0}:{1}'",
".",
"format",
"(",
"ContentType",
".",
"objects",
".",
"get_for_model",
... | Manages handling deletions of objects that were previously managed by the initial data process but no longer
managed. It does so by mantaining a list of receipts for model objects that are registered for deletion on
each round of initial data processing. Any receipts that are from previous rounds and not the current
round will be deleted. | [
"Manages",
"handling",
"deletions",
"of",
"objects",
"that",
"were",
"previously",
"managed",
"by",
"the",
"initial",
"data",
"process",
"but",
"no",
"longer",
"managed",
".",
"It",
"does",
"so",
"by",
"mantaining",
"a",
"list",
"of",
"receipts",
"for",
"mod... | train | https://github.com/ambitioninc/django-dynamic-initial-data/blob/27b7bf4ac31b465cc14127832d0d4b97362cc40f/dynamic_initial_data/base.py#L149-L187 |
ambitioninc/django-dynamic-initial-data | dynamic_initial_data/base.py | InitialDataUpdater.update_all_apps | def update_all_apps(self):
"""
Loops through all app names contained in settings.INSTALLED_APPS and calls `update_app`
on each one. Handles any object deletions that happened after all apps have been initialized.
"""
for app in apps.get_app_configs():
self.update_app(app.name)
# During update_app, all apps added model objects that were registered for deletion.
# Delete all objects that were previously managed by the initial data process
self.handle_deletions() | python | def update_all_apps(self):
"""
Loops through all app names contained in settings.INSTALLED_APPS and calls `update_app`
on each one. Handles any object deletions that happened after all apps have been initialized.
"""
for app in apps.get_app_configs():
self.update_app(app.name)
# During update_app, all apps added model objects that were registered for deletion.
# Delete all objects that were previously managed by the initial data process
self.handle_deletions() | [
"def",
"update_all_apps",
"(",
"self",
")",
":",
"for",
"app",
"in",
"apps",
".",
"get_app_configs",
"(",
")",
":",
"self",
".",
"update_app",
"(",
"app",
".",
"name",
")",
"# During update_app, all apps added model objects that were registered for deletion.",
"# Dele... | Loops through all app names contained in settings.INSTALLED_APPS and calls `update_app`
on each one. Handles any object deletions that happened after all apps have been initialized. | [
"Loops",
"through",
"all",
"app",
"names",
"contained",
"in",
"settings",
".",
"INSTALLED_APPS",
"and",
"calls",
"update_app",
"on",
"each",
"one",
".",
"Handles",
"any",
"object",
"deletions",
"that",
"happened",
"after",
"all",
"apps",
"have",
"been",
"initi... | train | https://github.com/ambitioninc/django-dynamic-initial-data/blob/27b7bf4ac31b465cc14127832d0d4b97362cc40f/dynamic_initial_data/base.py#L190-L200 |
ambitioninc/django-dynamic-initial-data | dynamic_initial_data/base.py | InitialDataUpdater.get_dependency_call_list | def get_dependency_call_list(self, app, call_list=None):
"""
Recursively detects any dependency cycles based on the specific app. A running list of
app calls is kept and passed to each function call. If a circular dependency is detected
an `InitialDataCircularDependency` exception will be raised. If a dependency does not exist,
an `InitialDataMissingApp` exception will be raised.
:param app: The name of the app in which to detect cycles. This should be the same path as defined
in settings.INSTALLED_APPS
:type app: str
:param call_list: A running list of which apps will be updated in this branch of dependencies
:type call_list: list
"""
# start the call_list with the current app if one wasn't passed in recursively
call_list = call_list or [app]
# load the initial data class for the app
try:
initial_data_class = self.load_app(app)
except ImportError:
raise InitialDataMissingApp(dep=app)
dependencies = initial_data_class.dependencies
# loop through each dependency and check recursively for cycles
for dep in dependencies:
if dep in call_list:
raise InitialDataCircularDependency(dep=dep, call_list=call_list)
else:
self.get_dependency_call_list(dep, call_list + [dep])
call_list.extend(dependencies)
return call_list[1:] | python | def get_dependency_call_list(self, app, call_list=None):
"""
Recursively detects any dependency cycles based on the specific app. A running list of
app calls is kept and passed to each function call. If a circular dependency is detected
an `InitialDataCircularDependency` exception will be raised. If a dependency does not exist,
an `InitialDataMissingApp` exception will be raised.
:param app: The name of the app in which to detect cycles. This should be the same path as defined
in settings.INSTALLED_APPS
:type app: str
:param call_list: A running list of which apps will be updated in this branch of dependencies
:type call_list: list
"""
# start the call_list with the current app if one wasn't passed in recursively
call_list = call_list or [app]
# load the initial data class for the app
try:
initial_data_class = self.load_app(app)
except ImportError:
raise InitialDataMissingApp(dep=app)
dependencies = initial_data_class.dependencies
# loop through each dependency and check recursively for cycles
for dep in dependencies:
if dep in call_list:
raise InitialDataCircularDependency(dep=dep, call_list=call_list)
else:
self.get_dependency_call_list(dep, call_list + [dep])
call_list.extend(dependencies)
return call_list[1:] | [
"def",
"get_dependency_call_list",
"(",
"self",
",",
"app",
",",
"call_list",
"=",
"None",
")",
":",
"# start the call_list with the current app if one wasn't passed in recursively",
"call_list",
"=",
"call_list",
"or",
"[",
"app",
"]",
"# load the initial data class for the ... | Recursively detects any dependency cycles based on the specific app. A running list of
app calls is kept and passed to each function call. If a circular dependency is detected
an `InitialDataCircularDependency` exception will be raised. If a dependency does not exist,
an `InitialDataMissingApp` exception will be raised.
:param app: The name of the app in which to detect cycles. This should be the same path as defined
in settings.INSTALLED_APPS
:type app: str
:param call_list: A running list of which apps will be updated in this branch of dependencies
:type call_list: list | [
"Recursively",
"detects",
"any",
"dependency",
"cycles",
"based",
"on",
"the",
"specific",
"app",
".",
"A",
"running",
"list",
"of",
"app",
"calls",
"is",
"kept",
"and",
"passed",
"to",
"each",
"function",
"call",
".",
"If",
"a",
"circular",
"dependency",
... | train | https://github.com/ambitioninc/django-dynamic-initial-data/blob/27b7bf4ac31b465cc14127832d0d4b97362cc40f/dynamic_initial_data/base.py#L202-L232 |
CivicSpleen/ambry | ambry/library/search_backends/base.py | BaseSearchBackend.reset | def reset(self):
""" Resets (deletes) all indexes. """
self.dataset_index.reset()
self.partition_index.reset()
self.identifier_index.reset() | python | def reset(self):
""" Resets (deletes) all indexes. """
self.dataset_index.reset()
self.partition_index.reset()
self.identifier_index.reset() | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"dataset_index",
".",
"reset",
"(",
")",
"self",
".",
"partition_index",
".",
"reset",
"(",
")",
"self",
".",
"identifier_index",
".",
"reset",
"(",
")"
] | Resets (deletes) all indexes. | [
"Resets",
"(",
"deletes",
")",
"all",
"indexes",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/base.py#L157-L161 |
CivicSpleen/ambry | ambry/library/search_backends/base.py | BaseSearchBackend._or_join | def _or_join(self, terms):
""" Joins terms using OR operator.
Args:
terms (list): terms to join
Examples:
self._or_join(['term1', 'term2']) -> 'term1 OR term2'
Returns:
str
"""
if isinstance(terms, (tuple, list)):
if len(terms) > 1:
return '(' + ' OR '.join(terms) + ')'
else:
return terms[0]
else:
return terms | python | def _or_join(self, terms):
""" Joins terms using OR operator.
Args:
terms (list): terms to join
Examples:
self._or_join(['term1', 'term2']) -> 'term1 OR term2'
Returns:
str
"""
if isinstance(terms, (tuple, list)):
if len(terms) > 1:
return '(' + ' OR '.join(terms) + ')'
else:
return terms[0]
else:
return terms | [
"def",
"_or_join",
"(",
"self",
",",
"terms",
")",
":",
"if",
"isinstance",
"(",
"terms",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"if",
"len",
"(",
"terms",
")",
">",
"1",
":",
"return",
"'('",
"+",
"' OR '",
".",
"join",
"(",
"terms",
"... | Joins terms using OR operator.
Args:
terms (list): terms to join
Examples:
self._or_join(['term1', 'term2']) -> 'term1 OR term2'
Returns:
str | [
"Joins",
"terms",
"using",
"OR",
"operator",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/base.py#L178-L197 |
CivicSpleen/ambry | ambry/library/search_backends/base.py | BaseSearchBackend._and_join | def _and_join(self, terms):
""" Joins terms using AND operator.
Args:
terms (list): terms to join
Examples:
self._and_join(['term1']) -> 'term1'
self._and_join(['term1', 'term2']) -> 'term1 AND term2'
self._and_join(['term1', 'term2', 'term3']) -> 'term1 AND term2 AND term3'
Returns:
str
"""
if len(terms) > 1:
return ' AND '.join([self._or_join(t) for t in terms])
else:
return self._or_join(terms[0]) | python | def _and_join(self, terms):
""" Joins terms using AND operator.
Args:
terms (list): terms to join
Examples:
self._and_join(['term1']) -> 'term1'
self._and_join(['term1', 'term2']) -> 'term1 AND term2'
self._and_join(['term1', 'term2', 'term3']) -> 'term1 AND term2 AND term3'
Returns:
str
"""
if len(terms) > 1:
return ' AND '.join([self._or_join(t) for t in terms])
else:
return self._or_join(terms[0]) | [
"def",
"_and_join",
"(",
"self",
",",
"terms",
")",
":",
"if",
"len",
"(",
"terms",
")",
">",
"1",
":",
"return",
"' AND '",
".",
"join",
"(",
"[",
"self",
".",
"_or_join",
"(",
"t",
")",
"for",
"t",
"in",
"terms",
"]",
")",
"else",
":",
"retur... | Joins terms using AND operator.
Args:
terms (list): terms to join
Examples:
self._and_join(['term1']) -> 'term1'
self._and_join(['term1', 'term2']) -> 'term1 AND term2'
self._and_join(['term1', 'term2', 'term3']) -> 'term1 AND term2 AND term3'
Returns:
str | [
"Joins",
"terms",
"using",
"AND",
"operator",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/base.py#L204-L221 |
CivicSpleen/ambry | ambry/library/search_backends/base.py | BaseIndex.index_one | def index_one(self, instance, force=False):
""" Indexes exactly one object of the Ambry system.
Args:
instance (any): instance to index.
force (boolean): if True replace document in the index.
Returns:
boolean: True if document added to index, False if document already exists in the index.
"""
if not self.is_indexed(instance) and not force:
doc = self._as_document(instance)
self._index_document(doc, force=force)
logger.debug('{} indexed as\n {}'.format(instance.__class__, pformat(doc)))
return True
logger.debug('{} already indexed.'.format(instance.__class__))
return False | python | def index_one(self, instance, force=False):
""" Indexes exactly one object of the Ambry system.
Args:
instance (any): instance to index.
force (boolean): if True replace document in the index.
Returns:
boolean: True if document added to index, False if document already exists in the index.
"""
if not self.is_indexed(instance) and not force:
doc = self._as_document(instance)
self._index_document(doc, force=force)
logger.debug('{} indexed as\n {}'.format(instance.__class__, pformat(doc)))
return True
logger.debug('{} already indexed.'.format(instance.__class__))
return False | [
"def",
"index_one",
"(",
"self",
",",
"instance",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"is_indexed",
"(",
"instance",
")",
"and",
"not",
"force",
":",
"doc",
"=",
"self",
".",
"_as_document",
"(",
"instance",
")",
"self",
"... | Indexes exactly one object of the Ambry system.
Args:
instance (any): instance to index.
force (boolean): if True replace document in the index.
Returns:
boolean: True if document added to index, False if document already exists in the index. | [
"Indexes",
"exactly",
"one",
"object",
"of",
"the",
"Ambry",
"system",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/base.py#L258-L275 |
CivicSpleen/ambry | ambry/library/search_backends/base.py | BaseDatasetIndex._as_document | def _as_document(self, dataset):
""" Converts dataset to document indexed by to FTS index.
Args:
dataset (orm.Dataset): dataset to convert.
Returns:
dict with structure matches to BaseDatasetIndex._schema.
"""
# find tables.
assert isinstance(dataset, Dataset)
execute = object_session(dataset).connection().execute
query = text("""
SELECT t_name, c_name, c_description
FROM columns
JOIN tables ON c_t_vid = t_vid WHERE t_d_vid = :dataset_vid;""")
columns = u('\n').join(
[u(' ').join(list(text_type(e) for e in t)) for t in execute(query, dataset_vid=str(dataset.identity.vid))])
doc = '\n'.join([u('{}').format(x) for x in [dataset.config.metadata.about.title,
dataset.config.metadata.about.summary,
dataset.identity.id_,
dataset.identity.vid,
dataset.identity.source,
dataset.identity.name,
dataset.identity.vname,
columns]])
# From the source, make a variety of combinations for keywords:
# foo.bar.com -> "foo foo.bar foo.bar.com bar.com"
parts = u('{}').format(dataset.identity.source).split('.')
sources = (['.'.join(g) for g in [parts[-i:] for i in range(2, len(parts) + 1)]]
+ ['.'.join(g) for g in [parts[:i] for i in range(0, len(parts))]])
# Re-calculate the summarization of grains, since the geoid 0.0.7 package had a bug where state level
# summaries had the same value as state-level allvals
def resum(g):
try:
return str(GVid.parse(g).summarize())
except (KeyError, ValueError):
return g
def as_list(value):
""" Converts value to the list. """
if not value:
return []
if isinstance(value, string_types):
lst = [value]
else:
try:
lst = list(value)
except TypeError:
lst = [value]
return lst
about_time = as_list(dataset.config.metadata.about.time)
about_grain = as_list(dataset.config.metadata.about.grain)
keywords = (
list(dataset.config.metadata.about.groups) +
list(dataset.config.metadata.about.tags) +
about_time +
[resum(g) for g in about_grain] +
sources)
document = dict(
vid=u('{}').format(dataset.identity.vid),
title=u('{} {}').format(dataset.identity.name, dataset.config.metadata.about.title),
doc=u('{}').format(doc),
keywords=' '.join(u('{}').format(x) for x in keywords)
)
return document | python | def _as_document(self, dataset):
""" Converts dataset to document indexed by to FTS index.
Args:
dataset (orm.Dataset): dataset to convert.
Returns:
dict with structure matches to BaseDatasetIndex._schema.
"""
# find tables.
assert isinstance(dataset, Dataset)
execute = object_session(dataset).connection().execute
query = text("""
SELECT t_name, c_name, c_description
FROM columns
JOIN tables ON c_t_vid = t_vid WHERE t_d_vid = :dataset_vid;""")
columns = u('\n').join(
[u(' ').join(list(text_type(e) for e in t)) for t in execute(query, dataset_vid=str(dataset.identity.vid))])
doc = '\n'.join([u('{}').format(x) for x in [dataset.config.metadata.about.title,
dataset.config.metadata.about.summary,
dataset.identity.id_,
dataset.identity.vid,
dataset.identity.source,
dataset.identity.name,
dataset.identity.vname,
columns]])
# From the source, make a variety of combinations for keywords:
# foo.bar.com -> "foo foo.bar foo.bar.com bar.com"
parts = u('{}').format(dataset.identity.source).split('.')
sources = (['.'.join(g) for g in [parts[-i:] for i in range(2, len(parts) + 1)]]
+ ['.'.join(g) for g in [parts[:i] for i in range(0, len(parts))]])
# Re-calculate the summarization of grains, since the geoid 0.0.7 package had a bug where state level
# summaries had the same value as state-level allvals
def resum(g):
try:
return str(GVid.parse(g).summarize())
except (KeyError, ValueError):
return g
def as_list(value):
""" Converts value to the list. """
if not value:
return []
if isinstance(value, string_types):
lst = [value]
else:
try:
lst = list(value)
except TypeError:
lst = [value]
return lst
about_time = as_list(dataset.config.metadata.about.time)
about_grain = as_list(dataset.config.metadata.about.grain)
keywords = (
list(dataset.config.metadata.about.groups) +
list(dataset.config.metadata.about.tags) +
about_time +
[resum(g) for g in about_grain] +
sources)
document = dict(
vid=u('{}').format(dataset.identity.vid),
title=u('{} {}').format(dataset.identity.name, dataset.config.metadata.about.title),
doc=u('{}').format(doc),
keywords=' '.join(u('{}').format(x) for x in keywords)
)
return document | [
"def",
"_as_document",
"(",
"self",
",",
"dataset",
")",
":",
"# find tables.",
"assert",
"isinstance",
"(",
"dataset",
",",
"Dataset",
")",
"execute",
"=",
"object_session",
"(",
"dataset",
")",
".",
"connection",
"(",
")",
".",
"execute",
"query",
"=",
"... | Converts dataset to document indexed by to FTS index.
Args:
dataset (orm.Dataset): dataset to convert.
Returns:
dict with structure matches to BaseDatasetIndex._schema. | [
"Converts",
"dataset",
"to",
"document",
"indexed",
"by",
"to",
"FTS",
"index",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/base.py#L332-L410 |
CivicSpleen/ambry | ambry/library/search_backends/base.py | BaseDatasetIndex._expand_terms | def _expand_terms(self, terms):
""" Expands terms of the dataset to the appropriate fields. It will parse the search phrase
and return only the search term components that are applicable to a Dataset query.
Args:
terms (dict or str):
Returns:
dict: keys are field names, values are query strings
"""
ret = {
'keywords': list(),
'doc': list()}
if not isinstance(terms, dict):
stp = SearchTermParser()
terms = stp.parse(terms, term_join=self.backend._and_join)
if 'about' in terms:
ret['doc'].append(terms['about'])
if 'source' in terms:
ret['keywords'].append(terms['source'])
return ret | python | def _expand_terms(self, terms):
""" Expands terms of the dataset to the appropriate fields. It will parse the search phrase
and return only the search term components that are applicable to a Dataset query.
Args:
terms (dict or str):
Returns:
dict: keys are field names, values are query strings
"""
ret = {
'keywords': list(),
'doc': list()}
if not isinstance(terms, dict):
stp = SearchTermParser()
terms = stp.parse(terms, term_join=self.backend._and_join)
if 'about' in terms:
ret['doc'].append(terms['about'])
if 'source' in terms:
ret['keywords'].append(terms['source'])
return ret | [
"def",
"_expand_terms",
"(",
"self",
",",
"terms",
")",
":",
"ret",
"=",
"{",
"'keywords'",
":",
"list",
"(",
")",
",",
"'doc'",
":",
"list",
"(",
")",
"}",
"if",
"not",
"isinstance",
"(",
"terms",
",",
"dict",
")",
":",
"stp",
"=",
"SearchTermPars... | Expands terms of the dataset to the appropriate fields. It will parse the search phrase
and return only the search term components that are applicable to a Dataset query.
Args:
terms (dict or str):
Returns:
dict: keys are field names, values are query strings | [
"Expands",
"terms",
"of",
"the",
"dataset",
"to",
"the",
"appropriate",
"fields",
".",
"It",
"will",
"parse",
"the",
"search",
"phrase",
"and",
"return",
"only",
"the",
"search",
"term",
"components",
"that",
"are",
"applicable",
"to",
"a",
"Dataset",
"query... | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/base.py#L412-L436 |
CivicSpleen/ambry | ambry/library/search_backends/base.py | BasePartitionIndex._as_document | def _as_document(self, partition):
""" Converts given partition to the document indexed by FTS backend.
Args:
partition (orm.Partition): partition to convert.
Returns:
dict with structure matches to BasePartitionIndex._schema.
"""
schema = ' '.join(
u'{} {} {} {} {}'.format(
c.id,
c.vid,
c.name,
c.altname,
c.description) for c in partition.table.columns)
values = ''
for stat in partition.stats:
if stat.uvalues :
# SOme geometry vlaues are super long. They should not be in uvbalues, but when they are,
# need to cut them down.
values += ' '.join(e[:200] for e in stat.uvalues) + '\n'
# Re-calculate the summarization of grains, since the geoid 0.0.7 package had a bug where state level
# summaries had the same value as state-level allvals
def resum(g):
try:
return str(GVid.parse(g).summarize())
except KeyError:
return g
except ValueError:
logger.debug("Failed to parse gvid '{}' from partition '{}' grain coverage"
.format(g, partition.identity.vname))
return g
keywords = (
' '.join(partition.space_coverage) + ' ' +
' '.join([resum(g) for g in partition.grain_coverage if resum(g)]) + ' ' +
' '.join(str(x) for x in partition.time_coverage)
)
doc_field = u('{} {} {} {} {} {}').format(
values,
schema,
' '.join([
u('{}').format(partition.identity.vid),
u('{}').format(partition.identity.id_),
u('{}').format(partition.identity.name),
u('{}').format(partition.identity.vname)]),
partition.display.title,
partition.display.description,
partition.display.sub_description,
partition.display.time_description,
partition.display.geo_description
)
document = dict(
vid=u('{}').format(partition.identity.vid),
dataset_vid=u('{}').format(partition.identity.as_dataset().vid),
title=u('{}').format(partition.table.description),
keywords=u('{}').format(keywords),
doc=doc_field)
return document | python | def _as_document(self, partition):
""" Converts given partition to the document indexed by FTS backend.
Args:
partition (orm.Partition): partition to convert.
Returns:
dict with structure matches to BasePartitionIndex._schema.
"""
schema = ' '.join(
u'{} {} {} {} {}'.format(
c.id,
c.vid,
c.name,
c.altname,
c.description) for c in partition.table.columns)
values = ''
for stat in partition.stats:
if stat.uvalues :
# SOme geometry vlaues are super long. They should not be in uvbalues, but when they are,
# need to cut them down.
values += ' '.join(e[:200] for e in stat.uvalues) + '\n'
# Re-calculate the summarization of grains, since the geoid 0.0.7 package had a bug where state level
# summaries had the same value as state-level allvals
def resum(g):
try:
return str(GVid.parse(g).summarize())
except KeyError:
return g
except ValueError:
logger.debug("Failed to parse gvid '{}' from partition '{}' grain coverage"
.format(g, partition.identity.vname))
return g
keywords = (
' '.join(partition.space_coverage) + ' ' +
' '.join([resum(g) for g in partition.grain_coverage if resum(g)]) + ' ' +
' '.join(str(x) for x in partition.time_coverage)
)
doc_field = u('{} {} {} {} {} {}').format(
values,
schema,
' '.join([
u('{}').format(partition.identity.vid),
u('{}').format(partition.identity.id_),
u('{}').format(partition.identity.name),
u('{}').format(partition.identity.vname)]),
partition.display.title,
partition.display.description,
partition.display.sub_description,
partition.display.time_description,
partition.display.geo_description
)
document = dict(
vid=u('{}').format(partition.identity.vid),
dataset_vid=u('{}').format(partition.identity.as_dataset().vid),
title=u('{}').format(partition.table.description),
keywords=u('{}').format(keywords),
doc=doc_field)
return document | [
"def",
"_as_document",
"(",
"self",
",",
"partition",
")",
":",
"schema",
"=",
"' '",
".",
"join",
"(",
"u'{} {} {} {} {}'",
".",
"format",
"(",
"c",
".",
"id",
",",
"c",
".",
"vid",
",",
"c",
".",
"name",
",",
"c",
".",
"altname",
",",
"c",
".",... | Converts given partition to the document indexed by FTS backend.
Args:
partition (orm.Partition): partition to convert.
Returns:
dict with structure matches to BasePartitionIndex._schema. | [
"Converts",
"given",
"partition",
"to",
"the",
"document",
"indexed",
"by",
"FTS",
"backend",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/base.py#L448-L515 |
CivicSpleen/ambry | ambry/library/search_backends/base.py | BasePartitionIndex._expand_terms | def _expand_terms(self, terms):
""" Expands partition terms to the appropriate fields.
Args:
terms (dict or str):
Returns:
dict: keys are field names, values are query strings
"""
ret = {
'keywords': list(),
'doc': list(),
'from': None,
'to': None}
if not isinstance(terms, dict):
stp = SearchTermParser()
terms = stp.parse(terms, term_join=self.backend._and_join)
if 'about' in terms:
ret['doc'].append(terms['about'])
if 'with' in terms:
ret['doc'].append(terms['with'])
if 'in' in terms:
place_vids = self._expand_place_ids(terms['in'])
ret['keywords'].append(place_vids)
if 'by' in terms:
ret['keywords'].append(terms['by'])
ret['from'] = terms.get('from', None)
ret['to'] = terms.get('to', None)
return ret | python | def _expand_terms(self, terms):
""" Expands partition terms to the appropriate fields.
Args:
terms (dict or str):
Returns:
dict: keys are field names, values are query strings
"""
ret = {
'keywords': list(),
'doc': list(),
'from': None,
'to': None}
if not isinstance(terms, dict):
stp = SearchTermParser()
terms = stp.parse(terms, term_join=self.backend._and_join)
if 'about' in terms:
ret['doc'].append(terms['about'])
if 'with' in terms:
ret['doc'].append(terms['with'])
if 'in' in terms:
place_vids = self._expand_place_ids(terms['in'])
ret['keywords'].append(place_vids)
if 'by' in terms:
ret['keywords'].append(terms['by'])
ret['from'] = terms.get('from', None)
ret['to'] = terms.get('to', None)
return ret | [
"def",
"_expand_terms",
"(",
"self",
",",
"terms",
")",
":",
"ret",
"=",
"{",
"'keywords'",
":",
"list",
"(",
")",
",",
"'doc'",
":",
"list",
"(",
")",
",",
"'from'",
":",
"None",
",",
"'to'",
":",
"None",
"}",
"if",
"not",
"isinstance",
"(",
"te... | Expands partition terms to the appropriate fields.
Args:
terms (dict or str):
Returns:
dict: keys are field names, values are query strings | [
"Expands",
"partition",
"terms",
"to",
"the",
"appropriate",
"fields",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/base.py#L517-L550 |
CivicSpleen/ambry | ambry/library/search_backends/base.py | BasePartitionIndex._expand_place_ids | def _expand_place_ids(self, terms):
""" Lookups all of the place identifiers to get gvids
Args:
terms (str or unicode): terms to lookup
Returns:
str or list: given terms if no identifiers found, otherwise list of identifiers.
"""
place_vids = []
first_type = None
for result in self.backend.identifier_index.search(terms):
if not first_type:
first_type = result.type
if result.type != first_type:
# Ignore ones that aren't the same type as the best match
continue
place_vids.append(result.vid)
if place_vids:
# Add the 'all region' gvids for the higher level
all_set = set(itertools.chain.from_iterable(iallval(GVid.parse(x)) for x in place_vids))
place_vids += list(str(x) for x in all_set)
return place_vids
else:
return terms | python | def _expand_place_ids(self, terms):
""" Lookups all of the place identifiers to get gvids
Args:
terms (str or unicode): terms to lookup
Returns:
str or list: given terms if no identifiers found, otherwise list of identifiers.
"""
place_vids = []
first_type = None
for result in self.backend.identifier_index.search(terms):
if not first_type:
first_type = result.type
if result.type != first_type:
# Ignore ones that aren't the same type as the best match
continue
place_vids.append(result.vid)
if place_vids:
# Add the 'all region' gvids for the higher level
all_set = set(itertools.chain.from_iterable(iallval(GVid.parse(x)) for x in place_vids))
place_vids += list(str(x) for x in all_set)
return place_vids
else:
return terms | [
"def",
"_expand_place_ids",
"(",
"self",
",",
"terms",
")",
":",
"place_vids",
"=",
"[",
"]",
"first_type",
"=",
"None",
"for",
"result",
"in",
"self",
".",
"backend",
".",
"identifier_index",
".",
"search",
"(",
"terms",
")",
":",
"if",
"not",
"first_ty... | Lookups all of the place identifiers to get gvids
Args:
terms (str or unicode): terms to lookup
Returns:
str or list: given terms if no identifiers found, otherwise list of identifiers. | [
"Lookups",
"all",
"of",
"the",
"place",
"identifiers",
"to",
"get",
"gvids"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/base.py#L552-L582 |
CivicSpleen/ambry | ambry/library/search_backends/base.py | BaseIdentifierIndex._as_document | def _as_document(self, identifier):
""" Converts given identifier to the document indexed by FTS backend.
Args:
identifier (dict): identifier to convert. Dict contains at
least 'identifier', 'type' and 'name' keys.
Returns:
dict with structure matches to BaseIdentifierIndex._schema.
"""
return {
'identifier': u('{}').format(identifier['identifier']),
'type': u('{}').format(identifier['type']),
'name': u('{}').format(identifier['name'])
} | python | def _as_document(self, identifier):
""" Converts given identifier to the document indexed by FTS backend.
Args:
identifier (dict): identifier to convert. Dict contains at
least 'identifier', 'type' and 'name' keys.
Returns:
dict with structure matches to BaseIdentifierIndex._schema.
"""
return {
'identifier': u('{}').format(identifier['identifier']),
'type': u('{}').format(identifier['type']),
'name': u('{}').format(identifier['name'])
} | [
"def",
"_as_document",
"(",
"self",
",",
"identifier",
")",
":",
"return",
"{",
"'identifier'",
":",
"u",
"(",
"'{}'",
")",
".",
"format",
"(",
"identifier",
"[",
"'identifier'",
"]",
")",
",",
"'type'",
":",
"u",
"(",
"'{}'",
")",
".",
"format",
"("... | Converts given identifier to the document indexed by FTS backend.
Args:
identifier (dict): identifier to convert. Dict contains at
least 'identifier', 'type' and 'name' keys.
Returns:
dict with structure matches to BaseIdentifierIndex._schema. | [
"Converts",
"given",
"identifier",
"to",
"the",
"document",
"indexed",
"by",
"FTS",
"backend",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/base.py#L593-L608 |
CivicSpleen/ambry | ambry/library/search_backends/base.py | SearchTermParser._geograins | def _geograins(self):
"""Create a map geographic area terms to the geo grain GVid values """
from geoid.civick import GVid
geo_grains = {}
for sl, cls in GVid.sl_map.items():
if '_' not in cls.level:
geo_grains[self.stem(cls.level)] = str(cls.nullval().summarize())
return geo_grains | python | def _geograins(self):
"""Create a map geographic area terms to the geo grain GVid values """
from geoid.civick import GVid
geo_grains = {}
for sl, cls in GVid.sl_map.items():
if '_' not in cls.level:
geo_grains[self.stem(cls.level)] = str(cls.nullval().summarize())
return geo_grains | [
"def",
"_geograins",
"(",
"self",
")",
":",
"from",
"geoid",
".",
"civick",
"import",
"GVid",
"geo_grains",
"=",
"{",
"}",
"for",
"sl",
",",
"cls",
"in",
"GVid",
".",
"sl_map",
".",
"items",
"(",
")",
":",
"if",
"'_'",
"not",
"in",
"cls",
".",
"l... | Create a map geographic area terms to the geo grain GVid values | [
"Create",
"a",
"map",
"geographic",
"area",
"terms",
"to",
"the",
"geo",
"grain",
"GVid",
"values"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/base.py#L684-L695 |
CivicSpleen/ambry | ambry/library/search_backends/base.py | SearchTermParser.parse | def parse(self, s, term_join=None):
""" Parses search term to
Args:
s (str): string with search term.
or_join (callable): function to join 'OR' terms.
Returns:
dict: all of the terms grouped by marker. Key is a marker, value is a term.
Example:
>>> SearchTermParser().parse('table2 from 1978 to 1979 in california')
{'to': 1979, 'about': 'table2', 'from': 1978, 'in': 'california'}
"""
if not term_join:
term_join = lambda x: '(' + ' OR '.join(x) + ')'
toks = self.scan(s)
# Examples: starting with this query:
# diabetes from 2014 to 2016 source healthindicators.gov
# Assume the first term is ABOUT, if it is not marked with a marker.
if toks and toks[0] and (toks[0][0] == self.TERM or toks[0][0] == self.QUOTEDTERM):
toks = [(self.MARKER, 'about')] + toks
# The example query produces this list of tokens:
#[(3, 'about'),
# (0, 'diabetes'),
# (3, 'from'),
# (4, 2014),
# (3, 'to'),
# (4, 2016),
# (3, 'source'),
# (0, 'healthindicators.gov')]
# Group the terms by their marker.
bymarker = []
for t in toks:
if t[0] == self.MARKER:
bymarker.append((t[1], []))
else:
bymarker[-1][1].append(t)
# After grouping tokens by their markers
# [('about', [(0, 'diabetes')]),
# ('from', [(4, 2014)]),
# ('to', [(4, 2016)]),
# ('source', [(0, 'healthindicators.gov')])
# ]
# Convert some of the markers based on their contents. This just changes the marker type for keywords
# we'll do more adjustments later.
comps = []
for t in bymarker:
t = list(t)
if t[0] == 'in' and len(t[1]) == 1 and isinstance(t[1][0][1], string_types) and self.stem(
t[1][0][1]) in self.geograins.keys():
t[0] = 'by'
# If the from term isn't an integer, then it is really a source.
if t[0] == 'from' and len(t[1]) == 1 and t[1][0][0] != self.YEAR:
t[0] = 'source'
comps.append(t)
# After conversions
# [['about', [(0, 'diabetes')]],
# ['from', [(4, 2014)]],
# ['to', [(4, 2016)]],
# ['source', [(0, 'healthindicators.gov')]]]
# Join all of the terms into single marker groups
groups = {marker: [] for marker, _ in comps}
for marker, terms in comps:
groups[marker] += [term for marker, term in terms]
# At this point, the groups dict is formed, but it will have a list
# for each marker that has multiple terms.
# Only a few of the markers should have more than one term, so move
# extras to the about group
for marker, group in groups.items():
if marker == 'about':
continue
if len(group) > 1 and marker not in self.multiterms:
groups[marker], extras = [group[0]], group[1:]
if not 'about' in groups:
groups['about'] = extras
else:
groups['about'] += extras
if marker == 'by':
groups['by'] = [ self.geograins.get(self.stem(e)) for e in group]
for marker, terms in iteritems(groups):
if len(terms) > 1:
if marker in 'in':
groups[marker] = ' '.join(terms)
else:
groups[marker] = term_join(terms)
elif len(terms) == 1:
groups[marker] = terms[0]
else:
pass
# After grouping:
# {'to': 2016,
# 'about': 'diabetes',
# 'from': 2014,
# 'source': 'healthindicators.gov'}
# If there were any markers with multiple terms, they would be cast in the or_join form.
return groups | python | def parse(self, s, term_join=None):
""" Parses search term to
Args:
s (str): string with search term.
or_join (callable): function to join 'OR' terms.
Returns:
dict: all of the terms grouped by marker. Key is a marker, value is a term.
Example:
>>> SearchTermParser().parse('table2 from 1978 to 1979 in california')
{'to': 1979, 'about': 'table2', 'from': 1978, 'in': 'california'}
"""
if not term_join:
term_join = lambda x: '(' + ' OR '.join(x) + ')'
toks = self.scan(s)
# Examples: starting with this query:
# diabetes from 2014 to 2016 source healthindicators.gov
# Assume the first term is ABOUT, if it is not marked with a marker.
if toks and toks[0] and (toks[0][0] == self.TERM or toks[0][0] == self.QUOTEDTERM):
toks = [(self.MARKER, 'about')] + toks
# The example query produces this list of tokens:
#[(3, 'about'),
# (0, 'diabetes'),
# (3, 'from'),
# (4, 2014),
# (3, 'to'),
# (4, 2016),
# (3, 'source'),
# (0, 'healthindicators.gov')]
# Group the terms by their marker.
bymarker = []
for t in toks:
if t[0] == self.MARKER:
bymarker.append((t[1], []))
else:
bymarker[-1][1].append(t)
# After grouping tokens by their markers
# [('about', [(0, 'diabetes')]),
# ('from', [(4, 2014)]),
# ('to', [(4, 2016)]),
# ('source', [(0, 'healthindicators.gov')])
# ]
# Convert some of the markers based on their contents. This just changes the marker type for keywords
# we'll do more adjustments later.
comps = []
for t in bymarker:
t = list(t)
if t[0] == 'in' and len(t[1]) == 1 and isinstance(t[1][0][1], string_types) and self.stem(
t[1][0][1]) in self.geograins.keys():
t[0] = 'by'
# If the from term isn't an integer, then it is really a source.
if t[0] == 'from' and len(t[1]) == 1 and t[1][0][0] != self.YEAR:
t[0] = 'source'
comps.append(t)
# After conversions
# [['about', [(0, 'diabetes')]],
# ['from', [(4, 2014)]],
# ['to', [(4, 2016)]],
# ['source', [(0, 'healthindicators.gov')]]]
# Join all of the terms into single marker groups
groups = {marker: [] for marker, _ in comps}
for marker, terms in comps:
groups[marker] += [term for marker, term in terms]
# At this point, the groups dict is formed, but it will have a list
# for each marker that has multiple terms.
# Only a few of the markers should have more than one term, so move
# extras to the about group
for marker, group in groups.items():
if marker == 'about':
continue
if len(group) > 1 and marker not in self.multiterms:
groups[marker], extras = [group[0]], group[1:]
if not 'about' in groups:
groups['about'] = extras
else:
groups['about'] += extras
if marker == 'by':
groups['by'] = [ self.geograins.get(self.stem(e)) for e in group]
for marker, terms in iteritems(groups):
if len(terms) > 1:
if marker in 'in':
groups[marker] = ' '.join(terms)
else:
groups[marker] = term_join(terms)
elif len(terms) == 1:
groups[marker] = terms[0]
else:
pass
# After grouping:
# {'to': 2016,
# 'about': 'diabetes',
# 'from': 2014,
# 'source': 'healthindicators.gov'}
# If there were any markers with multiple terms, they would be cast in the or_join form.
return groups | [
"def",
"parse",
"(",
"self",
",",
"s",
",",
"term_join",
"=",
"None",
")",
":",
"if",
"not",
"term_join",
":",
"term_join",
"=",
"lambda",
"x",
":",
"'('",
"+",
"' OR '",
".",
"join",
"(",
"x",
")",
"+",
"')'",
"toks",
"=",
"self",
".",
"scan",
... | Parses search term to
Args:
s (str): string with search term.
or_join (callable): function to join 'OR' terms.
Returns:
dict: all of the terms grouped by marker. Key is a marker, value is a term.
Example:
>>> SearchTermParser().parse('table2 from 1978 to 1979 in california')
{'to': 1979, 'about': 'table2', 'from': 1978, 'in': 'california'} | [
"Parses",
"search",
"term",
"to"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/base.py#L705-L832 |
google/yara-procdump-python | setup.py | BuildExtCommand.run | def run(self):
"""Execute the build command."""
module = self.distribution.ext_modules[0]
building_for_windows = self.plat_name in ['win32', 'win-amd64']
if building_for_windows:
module.define_macros.append(('_CRT_SECURE_NO_WARNINGS', '1'))
module.libraries.append('advapi32')
if self.dynamic_linking:
module.libraries.append('yara')
else:
for source in yara_sources:
module.sources.append(source)
build_ext.build_ext.run(self) | python | def run(self):
"""Execute the build command."""
module = self.distribution.ext_modules[0]
building_for_windows = self.plat_name in ['win32', 'win-amd64']
if building_for_windows:
module.define_macros.append(('_CRT_SECURE_NO_WARNINGS', '1'))
module.libraries.append('advapi32')
if self.dynamic_linking:
module.libraries.append('yara')
else:
for source in yara_sources:
module.sources.append(source)
build_ext.build_ext.run(self) | [
"def",
"run",
"(",
"self",
")",
":",
"module",
"=",
"self",
".",
"distribution",
".",
"ext_modules",
"[",
"0",
"]",
"building_for_windows",
"=",
"self",
".",
"plat_name",
"in",
"[",
"'win32'",
",",
"'win-amd64'",
"]",
"if",
"building_for_windows",
":",
"mo... | Execute the build command. | [
"Execute",
"the",
"build",
"command",
"."
] | train | https://github.com/google/yara-procdump-python/blob/d32221da53fd18736bf05a926d4ad6ac7b4a0bae/setup.py#L92-L108 |
SmartTeleMax/iktomi | iktomi/cli/sqla.py | drop_everything | def drop_everything(engine):
'''Droping all tables and custom types (enums) using `engine`.
Taken from http://www.sqlalchemy.org/trac/wiki/UsageRecipes/DropEverything
This method is more robust than `metadata.drop_all(engine)`. B.c. when
you change a table or a type name, `drop_all` does not consider the old one.
Thus, DB holds some unused entities.'''
conn = engine.connect()
# the transaction only applies if the DB supports
# transactional DDL, i.e. Postgresql, MS SQL Server
trans = conn.begin()
inspector = reflection.Inspector.from_engine(engine)
metadata = MetaData()
tbs = []
all_fks = []
types = []
for table_name in inspector.get_table_names():
fks = []
for fk in inspector.get_foreign_keys(table_name):
if not fk['name']:
continue
fks.append(ForeignKeyConstraint((), (), name=fk['name']))
for col in inspector.get_columns(table_name):
if isinstance(col['type'], SchemaType):
types.append(col['type'])
t = Table(table_name, metadata, *fks)
tbs.append(t)
all_fks.extend(fks)
try:
for fkc in all_fks:
conn.execute(DropConstraint(fkc))
for table in tbs:
conn.execute(DropTable(table))
for custom_type in types:
custom_type.drop(conn)
trans.commit()
except: # pragma: no cover
trans.rollback()
raise | python | def drop_everything(engine):
'''Droping all tables and custom types (enums) using `engine`.
Taken from http://www.sqlalchemy.org/trac/wiki/UsageRecipes/DropEverything
This method is more robust than `metadata.drop_all(engine)`. B.c. when
you change a table or a type name, `drop_all` does not consider the old one.
Thus, DB holds some unused entities.'''
conn = engine.connect()
# the transaction only applies if the DB supports
# transactional DDL, i.e. Postgresql, MS SQL Server
trans = conn.begin()
inspector = reflection.Inspector.from_engine(engine)
metadata = MetaData()
tbs = []
all_fks = []
types = []
for table_name in inspector.get_table_names():
fks = []
for fk in inspector.get_foreign_keys(table_name):
if not fk['name']:
continue
fks.append(ForeignKeyConstraint((), (), name=fk['name']))
for col in inspector.get_columns(table_name):
if isinstance(col['type'], SchemaType):
types.append(col['type'])
t = Table(table_name, metadata, *fks)
tbs.append(t)
all_fks.extend(fks)
try:
for fkc in all_fks:
conn.execute(DropConstraint(fkc))
for table in tbs:
conn.execute(DropTable(table))
for custom_type in types:
custom_type.drop(conn)
trans.commit()
except: # pragma: no cover
trans.rollback()
raise | [
"def",
"drop_everything",
"(",
"engine",
")",
":",
"conn",
"=",
"engine",
".",
"connect",
"(",
")",
"# the transaction only applies if the DB supports",
"# transactional DDL, i.e. Postgresql, MS SQL Server",
"trans",
"=",
"conn",
".",
"begin",
"(",
")",
"inspector",
"="... | Droping all tables and custom types (enums) using `engine`.
Taken from http://www.sqlalchemy.org/trac/wiki/UsageRecipes/DropEverything
This method is more robust than `metadata.drop_all(engine)`. B.c. when
you change a table or a type name, `drop_all` does not consider the old one.
Thus, DB holds some unused entities. | [
"Droping",
"all",
"tables",
"and",
"custom",
"types",
"(",
"enums",
")",
"using",
"engine",
".",
"Taken",
"from",
"http",
":",
"//",
"www",
".",
"sqlalchemy",
".",
"org",
"/",
"trac",
"/",
"wiki",
"/",
"UsageRecipes",
"/",
"DropEverything"
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/cli/sqla.py#L20-L58 |
SmartTeleMax/iktomi | iktomi/cli/sqla.py | Sqla.command_create_tables | def command_create_tables(self, meta_name=None, verbose=False):
'''
Create tables according sqlalchemy data model.
Is not a complex migration tool like alembic, just creates tables that
does not exist::
./manage.py sqla:create_tables [--verbose] [meta_name]
'''
def _create_metadata_tables(metadata):
for table in metadata.sorted_tables:
if verbose:
print(self._schema(table))
else:
print(' '+table.name)
engine = self.session.get_bind(clause=table)
metadata.create_all(bind=engine, tables=[table])
if isinstance(self.metadata, MetaData):
print('Creating tables...')
_create_metadata_tables(self.metadata)
else:
for current_meta_name, metadata in self.metadata.items():
if meta_name not in (current_meta_name, None):
continue
print('Creating tables for {}...'.format(current_meta_name))
_create_metadata_tables(metadata) | python | def command_create_tables(self, meta_name=None, verbose=False):
'''
Create tables according sqlalchemy data model.
Is not a complex migration tool like alembic, just creates tables that
does not exist::
./manage.py sqla:create_tables [--verbose] [meta_name]
'''
def _create_metadata_tables(metadata):
for table in metadata.sorted_tables:
if verbose:
print(self._schema(table))
else:
print(' '+table.name)
engine = self.session.get_bind(clause=table)
metadata.create_all(bind=engine, tables=[table])
if isinstance(self.metadata, MetaData):
print('Creating tables...')
_create_metadata_tables(self.metadata)
else:
for current_meta_name, metadata in self.metadata.items():
if meta_name not in (current_meta_name, None):
continue
print('Creating tables for {}...'.format(current_meta_name))
_create_metadata_tables(metadata) | [
"def",
"command_create_tables",
"(",
"self",
",",
"meta_name",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"def",
"_create_metadata_tables",
"(",
"metadata",
")",
":",
"for",
"table",
"in",
"metadata",
".",
"sorted_tables",
":",
"if",
"verbose",
":"... | Create tables according sqlalchemy data model.
Is not a complex migration tool like alembic, just creates tables that
does not exist::
./manage.py sqla:create_tables [--verbose] [meta_name] | [
"Create",
"tables",
"according",
"sqlalchemy",
"data",
"model",
"."
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/cli/sqla.py#L86-L113 |
SmartTeleMax/iktomi | iktomi/cli/sqla.py | Sqla.command_drop_tables | def command_drop_tables(self, meta_name=None):
'''
Drops all tables without dropping a database::
./manage.py sqla:drop_tables [meta_name]
'''
answer = six.moves.input(u'All data will lost. Are you sure? [y/N] ')
if answer.strip().lower()!='y':
sys.exit('Interrupted')
def _drop_metadata_tables(metadata):
table = next(six.itervalues(metadata.tables), None)
if table is None:
print('Failed to find engine')
else:
engine = self.session.get_bind(clause=table)
drop_everything(engine)
print('Done')
if isinstance(self.metadata, MetaData):
print('Droping tables... ', end='')
_drop_metadata_tables(self.metadata)
else:
for current_meta_name, metadata in self.metadata.items():
if meta_name not in (current_meta_name, None):
continue
print('Droping tables for {}... '.format(current_meta_name),
end='')
_drop_metadata_tables(metadata) | python | def command_drop_tables(self, meta_name=None):
'''
Drops all tables without dropping a database::
./manage.py sqla:drop_tables [meta_name]
'''
answer = six.moves.input(u'All data will lost. Are you sure? [y/N] ')
if answer.strip().lower()!='y':
sys.exit('Interrupted')
def _drop_metadata_tables(metadata):
table = next(six.itervalues(metadata.tables), None)
if table is None:
print('Failed to find engine')
else:
engine = self.session.get_bind(clause=table)
drop_everything(engine)
print('Done')
if isinstance(self.metadata, MetaData):
print('Droping tables... ', end='')
_drop_metadata_tables(self.metadata)
else:
for current_meta_name, metadata in self.metadata.items():
if meta_name not in (current_meta_name, None):
continue
print('Droping tables for {}... '.format(current_meta_name),
end='')
_drop_metadata_tables(metadata) | [
"def",
"command_drop_tables",
"(",
"self",
",",
"meta_name",
"=",
"None",
")",
":",
"answer",
"=",
"six",
".",
"moves",
".",
"input",
"(",
"u'All data will lost. Are you sure? [y/N] '",
")",
"if",
"answer",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"... | Drops all tables without dropping a database::
./manage.py sqla:drop_tables [meta_name] | [
"Drops",
"all",
"tables",
"without",
"dropping",
"a",
"database",
"::"
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/cli/sqla.py#L115-L144 |
SmartTeleMax/iktomi | iktomi/cli/sqla.py | Sqla.command_schema | def command_schema(self, name=None):
'''
Prints current database schema (according sqlalchemy database model)::
./manage.py sqla:schema [name]
'''
meta_name = table_name = None
if name:
if isinstance(self.metadata, MetaData):
table_name = name
elif '.' in name:
meta_name, table_name = name.split('.', 1)
else:
meta_name = name
def _print_metadata_schema(metadata):
if table_name is None:
for table in metadata.sorted_tables:
print(self._schema(table))
else:
try:
table = metadata.tables[table_name]
except KeyError:
sys.exit('Table {} is not found'.format(name))
print(self._schema(table))
if isinstance(self.metadata, MetaData):
_print_metadata_schema(self.metadata)
else:
for current_meta_name, metadata in self.metadata.items():
if meta_name not in (current_meta_name, None):
continue
_print_metadata_schema(metadata) | python | def command_schema(self, name=None):
'''
Prints current database schema (according sqlalchemy database model)::
./manage.py sqla:schema [name]
'''
meta_name = table_name = None
if name:
if isinstance(self.metadata, MetaData):
table_name = name
elif '.' in name:
meta_name, table_name = name.split('.', 1)
else:
meta_name = name
def _print_metadata_schema(metadata):
if table_name is None:
for table in metadata.sorted_tables:
print(self._schema(table))
else:
try:
table = metadata.tables[table_name]
except KeyError:
sys.exit('Table {} is not found'.format(name))
print(self._schema(table))
if isinstance(self.metadata, MetaData):
_print_metadata_schema(self.metadata)
else:
for current_meta_name, metadata in self.metadata.items():
if meta_name not in (current_meta_name, None):
continue
_print_metadata_schema(metadata) | [
"def",
"command_schema",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"meta_name",
"=",
"table_name",
"=",
"None",
"if",
"name",
":",
"if",
"isinstance",
"(",
"self",
".",
"metadata",
",",
"MetaData",
")",
":",
"table_name",
"=",
"name",
"elif",
"'... | Prints current database schema (according sqlalchemy database model)::
./manage.py sqla:schema [name] | [
"Prints",
"current",
"database",
"schema",
"(",
"according",
"sqlalchemy",
"database",
"model",
")",
"::"
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/cli/sqla.py#L165-L197 |
SmartTeleMax/iktomi | iktomi/cli/sqla.py | Sqla.command_gen | def command_gen(self, *names):
'''
Runs generator functions.
Run `docs` generator function::
./manage.py sqla:gen docs
Run `docs` generator function with `count=10`::
./manage.py sqla:gen docs:10
'''
if not names:
sys.exit('Please provide generator names')
for name in names:
name, count = name, 0
if ':' in name:
name, count = name.split(':', 1)
count = int(count)
create = self.generators[name]
print('Generating `{0}` count={1}'.format(name, count))
create(self.session, count)
self.session.commit() | python | def command_gen(self, *names):
'''
Runs generator functions.
Run `docs` generator function::
./manage.py sqla:gen docs
Run `docs` generator function with `count=10`::
./manage.py sqla:gen docs:10
'''
if not names:
sys.exit('Please provide generator names')
for name in names:
name, count = name, 0
if ':' in name:
name, count = name.split(':', 1)
count = int(count)
create = self.generators[name]
print('Generating `{0}` count={1}'.format(name, count))
create(self.session, count)
self.session.commit() | [
"def",
"command_gen",
"(",
"self",
",",
"*",
"names",
")",
":",
"if",
"not",
"names",
":",
"sys",
".",
"exit",
"(",
"'Please provide generator names'",
")",
"for",
"name",
"in",
"names",
":",
"name",
",",
"count",
"=",
"name",
",",
"0",
"if",
"':'",
... | Runs generator functions.
Run `docs` generator function::
./manage.py sqla:gen docs
Run `docs` generator function with `count=10`::
./manage.py sqla:gen docs:10 | [
"Runs",
"generator",
"functions",
"."
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/cli/sqla.py#L199-L221 |
flaviogrossi/sockjs-cyclone | sockjs/cyclone/transports/base.py | BaseTransportMixin.get_conn_info | def get_conn_info(self):
from sockjs.cyclone.conn import ConnectionInfo
""" Return C{ConnectionInfo} object from current transport """
return ConnectionInfo(self.request.remote_ip,
self.request.cookies,
self.request.arguments,
self.request.headers,
self.request.path) | python | def get_conn_info(self):
from sockjs.cyclone.conn import ConnectionInfo
""" Return C{ConnectionInfo} object from current transport """
return ConnectionInfo(self.request.remote_ip,
self.request.cookies,
self.request.arguments,
self.request.headers,
self.request.path) | [
"def",
"get_conn_info",
"(",
"self",
")",
":",
"from",
"sockjs",
".",
"cyclone",
".",
"conn",
"import",
"ConnectionInfo",
"return",
"ConnectionInfo",
"(",
"self",
".",
"request",
".",
"remote_ip",
",",
"self",
".",
"request",
".",
"cookies",
",",
"self",
"... | Return C{ConnectionInfo} object from current transport | [
"Return",
"C",
"{",
"ConnectionInfo",
"}",
"object",
"from",
"current",
"transport"
] | train | https://github.com/flaviogrossi/sockjs-cyclone/blob/d3ca053ec1aa1e85f652347bff562c2319be37a2/sockjs/cyclone/transports/base.py#L9-L17 |
CivicSpleen/ambry | ambry/mprlib/backends/base.py | _get_table_names | def _get_table_names(statement):
""" Returns table names found in the query.
NOTE. This routine would use the sqlparse parse tree, but vnames don't parse very well.
Args:
statement (sqlparse.sql.Statement): parsed by sqlparse sql statement.
Returns:
list of str
"""
parts = statement.to_unicode().split()
tables = set()
for i, token in enumerate(parts):
if token.lower() == 'from' or token.lower().endswith('join'):
tables.add(parts[i + 1].rstrip(';'))
return list(tables) | python | def _get_table_names(statement):
""" Returns table names found in the query.
NOTE. This routine would use the sqlparse parse tree, but vnames don't parse very well.
Args:
statement (sqlparse.sql.Statement): parsed by sqlparse sql statement.
Returns:
list of str
"""
parts = statement.to_unicode().split()
tables = set()
for i, token in enumerate(parts):
if token.lower() == 'from' or token.lower().endswith('join'):
tables.add(parts[i + 1].rstrip(';'))
return list(tables) | [
"def",
"_get_table_names",
"(",
"statement",
")",
":",
"parts",
"=",
"statement",
".",
"to_unicode",
"(",
")",
".",
"split",
"(",
")",
"tables",
"=",
"set",
"(",
")",
"for",
"i",
",",
"token",
"in",
"enumerate",
"(",
"parts",
")",
":",
"if",
"token",... | Returns table names found in the query.
NOTE. This routine would use the sqlparse parse tree, but vnames don't parse very well.
Args:
statement (sqlparse.sql.Statement): parsed by sqlparse sql statement.
Returns:
list of str | [
"Returns",
"table",
"names",
"found",
"in",
"the",
"query",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/mprlib/backends/base.py#L167-L187 |
CivicSpleen/ambry | ambry/mprlib/backends/base.py | DatabaseBackend.install | def install(self, connection, partition, table_name=None, index_columns=None, materialize=False,
logger=None):
""" Installs partition's mpr to the database to allow to execute sql queries over mpr.
Args:
connection:
partition (orm.Partition):
materialize (boolean): if True, create generic table. If False create MED over mpr.
Returns:
str: name of the created table.
"""
raise NotImplementedError | python | def install(self, connection, partition, table_name=None, index_columns=None, materialize=False,
logger=None):
""" Installs partition's mpr to the database to allow to execute sql queries over mpr.
Args:
connection:
partition (orm.Partition):
materialize (boolean): if True, create generic table. If False create MED over mpr.
Returns:
str: name of the created table.
"""
raise NotImplementedError | [
"def",
"install",
"(",
"self",
",",
"connection",
",",
"partition",
",",
"table_name",
"=",
"None",
",",
"index_columns",
"=",
"None",
",",
"materialize",
"=",
"False",
",",
"logger",
"=",
"None",
")",
":",
"raise",
"NotImplementedError"
] | Installs partition's mpr to the database to allow to execute sql queries over mpr.
Args:
connection:
partition (orm.Partition):
materialize (boolean): if True, create generic table. If False create MED over mpr.
Returns:
str: name of the created table. | [
"Installs",
"partition",
"s",
"mpr",
"to",
"the",
"database",
"to",
"allow",
"to",
"execute",
"sql",
"queries",
"over",
"mpr",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/mprlib/backends/base.py#L24-L38 |
CivicSpleen/ambry | ambry/mprlib/backends/base.py | DatabaseBackend.install_table | def install_table(self, connection, table, logger = None):
""" Installs all partitons of the table and create view with union of all partitons.
Args:
connection: connection to database who stores mpr data.
table (orm.Table):
"""
# first install all partitions of the table
queries = []
query_tmpl = 'SELECT * FROM {}'
for partition in table.partitions:
partition.localize()
installed_name = self.install(connection, partition)
queries.append(query_tmpl.format(installed_name))
# now create view with union of all partitions.
query = 'CREATE VIEW {} AS {} '.format( table.vid, '\nUNION ALL\n'.join(queries))
logger.debug('Creating view for table.\n table: {}\n query: {}'.format(table.vid, query))
self._execute(connection, query, fetch=False) | python | def install_table(self, connection, table, logger = None):
""" Installs all partitons of the table and create view with union of all partitons.
Args:
connection: connection to database who stores mpr data.
table (orm.Table):
"""
# first install all partitions of the table
queries = []
query_tmpl = 'SELECT * FROM {}'
for partition in table.partitions:
partition.localize()
installed_name = self.install(connection, partition)
queries.append(query_tmpl.format(installed_name))
# now create view with union of all partitions.
query = 'CREATE VIEW {} AS {} '.format( table.vid, '\nUNION ALL\n'.join(queries))
logger.debug('Creating view for table.\n table: {}\n query: {}'.format(table.vid, query))
self._execute(connection, query, fetch=False) | [
"def",
"install_table",
"(",
"self",
",",
"connection",
",",
"table",
",",
"logger",
"=",
"None",
")",
":",
"# first install all partitions of the table",
"queries",
"=",
"[",
"]",
"query_tmpl",
"=",
"'SELECT * FROM {}'",
"for",
"partition",
"in",
"table",
".",
... | Installs all partitons of the table and create view with union of all partitons.
Args:
connection: connection to database who stores mpr data.
table (orm.Table): | [
"Installs",
"all",
"partitons",
"of",
"the",
"table",
"and",
"create",
"view",
"with",
"union",
"of",
"all",
"partitons",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/mprlib/backends/base.py#L40-L59 |
CivicSpleen/ambry | ambry/mprlib/backends/base.py | DatabaseBackend.query | def query(self, connection, query, fetch=True):
""" Creates virtual tables for all partitions found in the query and executes query.
Args:
query (str): sql query
fetch (bool): fetch result from database if True, do not fetch overwise.
"""
self.install_module(connection)
statements = sqlparse.parse(sqlparse.format(query, strip_comments=True))
# install all partitions and replace table names in the query.
#
logger.debug('Finding and installing all partitions from query. \n query: {}'.format(query))
new_query = []
if len(statements) > 1:
raise BadSQLError("Can only query a single statement")
if len(statements) == 0:
raise BadSQLError("DIdn't get any statements in '{}'".format(query))
statement = statements[0]
logger.debug( 'Searching statement for partition ref.\n statement: {}'.format(statement.to_unicode()))
#statement = self.install_statement(connection, statement.to_unicode())
logger.debug(
'Executing updated query after partition install.'
'\n query before update: {}\n query to execute (updated query): {}'
.format(statement, new_query))
return self._execute(connection, statement.to_unicode(), fetch=fetch) | python | def query(self, connection, query, fetch=True):
""" Creates virtual tables for all partitions found in the query and executes query.
Args:
query (str): sql query
fetch (bool): fetch result from database if True, do not fetch overwise.
"""
self.install_module(connection)
statements = sqlparse.parse(sqlparse.format(query, strip_comments=True))
# install all partitions and replace table names in the query.
#
logger.debug('Finding and installing all partitions from query. \n query: {}'.format(query))
new_query = []
if len(statements) > 1:
raise BadSQLError("Can only query a single statement")
if len(statements) == 0:
raise BadSQLError("DIdn't get any statements in '{}'".format(query))
statement = statements[0]
logger.debug( 'Searching statement for partition ref.\n statement: {}'.format(statement.to_unicode()))
#statement = self.install_statement(connection, statement.to_unicode())
logger.debug(
'Executing updated query after partition install.'
'\n query before update: {}\n query to execute (updated query): {}'
.format(statement, new_query))
return self._execute(connection, statement.to_unicode(), fetch=fetch) | [
"def",
"query",
"(",
"self",
",",
"connection",
",",
"query",
",",
"fetch",
"=",
"True",
")",
":",
"self",
".",
"install_module",
"(",
"connection",
")",
"statements",
"=",
"sqlparse",
".",
"parse",
"(",
"sqlparse",
".",
"format",
"(",
"query",
",",
"s... | Creates virtual tables for all partitions found in the query and executes query.
Args:
query (str): sql query
fetch (bool): fetch result from database if True, do not fetch overwise. | [
"Creates",
"virtual",
"tables",
"for",
"all",
"partitions",
"found",
"in",
"the",
"query",
"and",
"executes",
"query",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/mprlib/backends/base.py#L63-L98 |
project-ncl/pnc-cli | pnc_cli/buildconfigurations.py | get_build_configuration_id_by_name | def get_build_configuration_id_by_name(name):
"""
Returns the id of the build configuration matching name
:param name: name of build configuration
:return: id of the matching build configuration, or None if no match found
"""
response = utils.checked_api_call(pnc_api.build_configs, 'get_all', q='name==' + name).content
if not response:
return None
return response[0].id | python | def get_build_configuration_id_by_name(name):
"""
Returns the id of the build configuration matching name
:param name: name of build configuration
:return: id of the matching build configuration, or None if no match found
"""
response = utils.checked_api_call(pnc_api.build_configs, 'get_all', q='name==' + name).content
if not response:
return None
return response[0].id | [
"def",
"get_build_configuration_id_by_name",
"(",
"name",
")",
":",
"response",
"=",
"utils",
".",
"checked_api_call",
"(",
"pnc_api",
".",
"build_configs",
",",
"'get_all'",
",",
"q",
"=",
"'name=='",
"+",
"name",
")",
".",
"content",
"if",
"not",
"response",... | Returns the id of the build configuration matching name
:param name: name of build configuration
:return: id of the matching build configuration, or None if no match found | [
"Returns",
"the",
"id",
"of",
"the",
"build",
"configuration",
"matching",
"name",
":",
"param",
"name",
":",
"name",
"of",
"build",
"configuration",
":",
"return",
":",
"id",
"of",
"the",
"matching",
"build",
"configuration",
"or",
"None",
"if",
"no",
"ma... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildconfigurations.py#L21-L30 |
project-ncl/pnc-cli | pnc_cli/buildconfigurations.py | get_build_configuration_by_name | def get_build_configuration_by_name(name):
"""
Returns the build configuration matching the name
:param name: name of build configuration
:return: The matching build configuration, or None if no match found
"""
response = utils.checked_api_call(pnc_api.build_configs, 'get_all', q='name==' + name).content
if not response:
return None
return response[0] | python | def get_build_configuration_by_name(name):
"""
Returns the build configuration matching the name
:param name: name of build configuration
:return: The matching build configuration, or None if no match found
"""
response = utils.checked_api_call(pnc_api.build_configs, 'get_all', q='name==' + name).content
if not response:
return None
return response[0] | [
"def",
"get_build_configuration_by_name",
"(",
"name",
")",
":",
"response",
"=",
"utils",
".",
"checked_api_call",
"(",
"pnc_api",
".",
"build_configs",
",",
"'get_all'",
",",
"q",
"=",
"'name=='",
"+",
"name",
")",
".",
"content",
"if",
"not",
"response",
... | Returns the build configuration matching the name
:param name: name of build configuration
:return: The matching build configuration, or None if no match found | [
"Returns",
"the",
"build",
"configuration",
"matching",
"the",
"name",
":",
"param",
"name",
":",
"name",
"of",
"build",
"configuration",
":",
"return",
":",
"The",
"matching",
"build",
"configuration",
"or",
"None",
"if",
"no",
"match",
"found"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildconfigurations.py#L33-L42 |
project-ncl/pnc-cli | pnc_cli/buildconfigurations.py | config_id_exists | def config_id_exists(search_id):
"""
Test if a build configuration matching search_id exists
:param search_id: id to test for
:return: True if a build configuration with search_id exists, False otherwise
"""
response = utils.checked_api_call(pnc_api.build_configs, 'get_specific', id=search_id)
if not response:
return False
return True | python | def config_id_exists(search_id):
"""
Test if a build configuration matching search_id exists
:param search_id: id to test for
:return: True if a build configuration with search_id exists, False otherwise
"""
response = utils.checked_api_call(pnc_api.build_configs, 'get_specific', id=search_id)
if not response:
return False
return True | [
"def",
"config_id_exists",
"(",
"search_id",
")",
":",
"response",
"=",
"utils",
".",
"checked_api_call",
"(",
"pnc_api",
".",
"build_configs",
",",
"'get_specific'",
",",
"id",
"=",
"search_id",
")",
"if",
"not",
"response",
":",
"return",
"False",
"return",
... | Test if a build configuration matching search_id exists
:param search_id: id to test for
:return: True if a build configuration with search_id exists, False otherwise | [
"Test",
"if",
"a",
"build",
"configuration",
"matching",
"search_id",
"exists",
":",
"param",
"search_id",
":",
"id",
"to",
"test",
"for",
":",
"return",
":",
"True",
"if",
"a",
"build",
"configuration",
"with",
"search_id",
"exists",
"False",
"otherwise"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildconfigurations.py#L45-L54 |
project-ncl/pnc-cli | pnc_cli/buildconfigurations.py | build | def build(id=None, name=None, revision=None,
temporary_build=False, timestamp_alignment=False,
no_build_dependencies=False,
keep_pod_on_failure=False,
force_rebuild=False,
rebuild_mode=common.REBUILD_MODES_DEFAULT):
"""
Trigger a BuildConfiguration by name or ID
"""
data = build_raw(id, name, revision, temporary_build, timestamp_alignment, no_build_dependencies,
keep_pod_on_failure, force_rebuild, rebuild_mode)
if data:
return utils.format_json(data) | python | def build(id=None, name=None, revision=None,
temporary_build=False, timestamp_alignment=False,
no_build_dependencies=False,
keep_pod_on_failure=False,
force_rebuild=False,
rebuild_mode=common.REBUILD_MODES_DEFAULT):
"""
Trigger a BuildConfiguration by name or ID
"""
data = build_raw(id, name, revision, temporary_build, timestamp_alignment, no_build_dependencies,
keep_pod_on_failure, force_rebuild, rebuild_mode)
if data:
return utils.format_json(data) | [
"def",
"build",
"(",
"id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"revision",
"=",
"None",
",",
"temporary_build",
"=",
"False",
",",
"timestamp_alignment",
"=",
"False",
",",
"no_build_dependencies",
"=",
"False",
",",
"keep_pod_on_failure",
"=",
"Fals... | Trigger a BuildConfiguration by name or ID | [
"Trigger",
"a",
"BuildConfiguration",
"by",
"name",
"or",
"ID"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildconfigurations.py#L67-L79 |
project-ncl/pnc-cli | pnc_cli/buildconfigurations.py | get_build_configuration | def get_build_configuration(id=None, name=None):
"""
Retrieve a specific BuildConfiguration
"""
data = get_build_configuration_raw(id, name)
if data:
return utils.format_json(data) | python | def get_build_configuration(id=None, name=None):
"""
Retrieve a specific BuildConfiguration
"""
data = get_build_configuration_raw(id, name)
if data:
return utils.format_json(data) | [
"def",
"get_build_configuration",
"(",
"id",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"data",
"=",
"get_build_configuration_raw",
"(",
"id",
",",
"name",
")",
"if",
"data",
":",
"return",
"utils",
".",
"format_json",
"(",
"data",
")"
] | Retrieve a specific BuildConfiguration | [
"Retrieve",
"a",
"specific",
"BuildConfiguration"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildconfigurations.py#L118-L124 |
project-ncl/pnc-cli | pnc_cli/buildconfigurations.py | update_build_configuration | def update_build_configuration(id, **kwargs):
"""
Update an existing BuildConfiguration with new information
:param id: ID of BuildConfiguration to update
:param name: Name of BuildConfiguration to update
:return:
"""
data = update_build_configuration_raw(id, **kwargs)
if data:
return utils.format_json(data) | python | def update_build_configuration(id, **kwargs):
"""
Update an existing BuildConfiguration with new information
:param id: ID of BuildConfiguration to update
:param name: Name of BuildConfiguration to update
:return:
"""
data = update_build_configuration_raw(id, **kwargs)
if data:
return utils.format_json(data) | [
"def",
"update_build_configuration",
"(",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"update_build_configuration_raw",
"(",
"id",
",",
"*",
"*",
"kwargs",
")",
"if",
"data",
":",
"return",
"utils",
".",
"format_json",
"(",
"data",
")"
] | Update an existing BuildConfiguration with new information
:param id: ID of BuildConfiguration to update
:param name: Name of BuildConfiguration to update
:return: | [
"Update",
"an",
"existing",
"BuildConfiguration",
"with",
"new",
"information"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildconfigurations.py#L146-L156 |
project-ncl/pnc-cli | pnc_cli/buildconfigurations.py | delete_build_configuration | def delete_build_configuration(id=None, name=None):
"""
Delete an existing BuildConfiguration
:param id:
:param name:
:return:
"""
data = delete_build_configuration_raw(id, name)
if data:
return utils.format_json(data) | python | def delete_build_configuration(id=None, name=None):
"""
Delete an existing BuildConfiguration
:param id:
:param name:
:return:
"""
data = delete_build_configuration_raw(id, name)
if data:
return utils.format_json(data) | [
"def",
"delete_build_configuration",
"(",
"id",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"data",
"=",
"delete_build_configuration_raw",
"(",
"id",
",",
"name",
")",
"if",
"data",
":",
"return",
"utils",
".",
"format_json",
"(",
"data",
")"
] | Delete an existing BuildConfiguration
:param id:
:param name:
:return: | [
"Delete",
"an",
"existing",
"BuildConfiguration",
":",
"param",
"id",
":",
":",
"param",
"name",
":",
":",
"return",
":"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildconfigurations.py#L200-L209 |
project-ncl/pnc-cli | pnc_cli/buildconfigurations.py | list_build_configurations_for_product | def list_build_configurations_for_product(id=None, name=None, page_size=200, page_index=0, sort="", q=""):
"""
List all BuildConfigurations associated with the given Product.
"""
data = list_build_configurations_for_product_raw(id, name, page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | python | def list_build_configurations_for_product(id=None, name=None, page_size=200, page_index=0, sort="", q=""):
"""
List all BuildConfigurations associated with the given Product.
"""
data = list_build_configurations_for_product_raw(id, name, page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | [
"def",
"list_build_configurations_for_product",
"(",
"id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"page_size",
"=",
"200",
",",
"page_index",
"=",
"0",
",",
"sort",
"=",
"\"\"",
",",
"q",
"=",
"\"\"",
")",
":",
"data",
"=",
"list_build_configurations_... | List all BuildConfigurations associated with the given Product. | [
"List",
"all",
"BuildConfigurations",
"associated",
"with",
"the",
"given",
"Product",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildconfigurations.py#L278-L284 |
project-ncl/pnc-cli | pnc_cli/buildconfigurations.py | list_build_configurations_for_project | def list_build_configurations_for_project(id=None, name=None, page_size=200, page_index=0, sort="", q=""):
"""
List all BuildConfigurations associated with the given Project.
"""
data = list_build_configurations_for_project_raw(id, name, page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | python | def list_build_configurations_for_project(id=None, name=None, page_size=200, page_index=0, sort="", q=""):
"""
List all BuildConfigurations associated with the given Project.
"""
data = list_build_configurations_for_project_raw(id, name, page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | [
"def",
"list_build_configurations_for_project",
"(",
"id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"page_size",
"=",
"200",
",",
"page_index",
"=",
"0",
",",
"sort",
"=",
"\"\"",
",",
"q",
"=",
"\"\"",
")",
":",
"data",
"=",
"list_build_configurations_... | List all BuildConfigurations associated with the given Project. | [
"List",
"all",
"BuildConfigurations",
"associated",
"with",
"the",
"given",
"Project",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildconfigurations.py#L301-L307 |
project-ncl/pnc-cli | pnc_cli/buildconfigurations.py | list_build_configurations_for_product_version | def list_build_configurations_for_product_version(product_id, version_id, page_size=200, page_index=0, sort="", q=""):
"""
List all BuildConfigurations associated with the given ProductVersion
"""
data = list_build_configurations_for_project_raw(product_id, version_id, page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | python | def list_build_configurations_for_product_version(product_id, version_id, page_size=200, page_index=0, sort="", q=""):
"""
List all BuildConfigurations associated with the given ProductVersion
"""
data = list_build_configurations_for_project_raw(product_id, version_id, page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | [
"def",
"list_build_configurations_for_product_version",
"(",
"product_id",
",",
"version_id",
",",
"page_size",
"=",
"200",
",",
"page_index",
"=",
"0",
",",
"sort",
"=",
"\"\"",
",",
"q",
"=",
"\"\"",
")",
":",
"data",
"=",
"list_build_configurations_for_project_... | List all BuildConfigurations associated with the given ProductVersion | [
"List",
"all",
"BuildConfigurations",
"associated",
"with",
"the",
"given",
"ProductVersion"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildconfigurations.py#L326-L332 |
project-ncl/pnc-cli | pnc_cli/buildconfigurations.py | add_dependency | def add_dependency(id=None, name=None, dependency_id=None, dependency_name=None):
"""
Add an existing BuildConfiguration as a dependency to another BuildConfiguration.
"""
data = add_dependency_raw(id, name, dependency_id, dependency_name)
if data:
return utils.format_json_list(data) | python | def add_dependency(id=None, name=None, dependency_id=None, dependency_name=None):
"""
Add an existing BuildConfiguration as a dependency to another BuildConfiguration.
"""
data = add_dependency_raw(id, name, dependency_id, dependency_name)
if data:
return utils.format_json_list(data) | [
"def",
"add_dependency",
"(",
"id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"dependency_id",
"=",
"None",
",",
"dependency_name",
"=",
"None",
")",
":",
"data",
"=",
"add_dependency_raw",
"(",
"id",
",",
"name",
",",
"dependency_id",
",",
"dependency_n... | Add an existing BuildConfiguration as a dependency to another BuildConfiguration. | [
"Add",
"an",
"existing",
"BuildConfiguration",
"as",
"a",
"dependency",
"to",
"another",
"BuildConfiguration",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildconfigurations.py#L367-L373 |
project-ncl/pnc-cli | pnc_cli/buildconfigurations.py | remove_dependency | def remove_dependency(id=None, name=None, dependency_id=None, dependency_name=None):
"""
Remove a BuildConfiguration from the dependency list of another BuildConfiguration
"""
data = remove_dependency_raw(id, name, dependency_id, dependency_name)
if data:
return utils.format_json_list(data) | python | def remove_dependency(id=None, name=None, dependency_id=None, dependency_name=None):
"""
Remove a BuildConfiguration from the dependency list of another BuildConfiguration
"""
data = remove_dependency_raw(id, name, dependency_id, dependency_name)
if data:
return utils.format_json_list(data) | [
"def",
"remove_dependency",
"(",
"id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"dependency_id",
"=",
"None",
",",
"dependency_name",
"=",
"None",
")",
":",
"data",
"=",
"remove_dependency_raw",
"(",
"id",
",",
"name",
",",
"dependency_id",
",",
"depend... | Remove a BuildConfiguration from the dependency list of another BuildConfiguration | [
"Remove",
"a",
"BuildConfiguration",
"from",
"the",
"dependency",
"list",
"of",
"another",
"BuildConfiguration"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildconfigurations.py#L390-L396 |
project-ncl/pnc-cli | pnc_cli/buildconfigurations.py | list_product_versions_for_build_configuration | def list_product_versions_for_build_configuration(id=None, name=None, page_size=200, page_index=0, sort="", q=""):
"""
List all ProductVersions associated with a BuildConfiguration
"""
data = list_product_versions_for_build_configuration_raw(id, name, page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | python | def list_product_versions_for_build_configuration(id=None, name=None, page_size=200, page_index=0, sort="", q=""):
"""
List all ProductVersions associated with a BuildConfiguration
"""
data = list_product_versions_for_build_configuration_raw(id, name, page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | [
"def",
"list_product_versions_for_build_configuration",
"(",
"id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"page_size",
"=",
"200",
",",
"page_index",
"=",
"0",
",",
"sort",
"=",
"\"\"",
",",
"q",
"=",
"\"\"",
")",
":",
"data",
"=",
"list_product_versi... | List all ProductVersions associated with a BuildConfiguration | [
"List",
"all",
"ProductVersions",
"associated",
"with",
"a",
"BuildConfiguration"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildconfigurations.py#L412-L418 |
project-ncl/pnc-cli | pnc_cli/buildconfigurations.py | add_product_version_to_build_configuration | def add_product_version_to_build_configuration(id=None, name=None, product_version_id=None):
"""
Associate an existing ProductVersion with a BuildConfiguration
"""
data = remove_product_version_from_build_configuration_raw(id, name, product_version_id)
if data:
return utils.format_json_list(data) | python | def add_product_version_to_build_configuration(id=None, name=None, product_version_id=None):
"""
Associate an existing ProductVersion with a BuildConfiguration
"""
data = remove_product_version_from_build_configuration_raw(id, name, product_version_id)
if data:
return utils.format_json_list(data) | [
"def",
"add_product_version_to_build_configuration",
"(",
"id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"product_version_id",
"=",
"None",
")",
":",
"data",
"=",
"remove_product_version_from_build_configuration_raw",
"(",
"id",
",",
"name",
",",
"product_version_i... | Associate an existing ProductVersion with a BuildConfiguration | [
"Associate",
"an",
"existing",
"ProductVersion",
"with",
"a",
"BuildConfiguration"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildconfigurations.py#L432-L438 |
project-ncl/pnc-cli | pnc_cli/buildconfigurations.py | remove_product_version_from_build_configuration | def remove_product_version_from_build_configuration(id=None, name=None, product_version_id=None):
"""
Remove a ProductVersion from association with a BuildConfiguration
"""
data = remove_product_version_from_build_configuration_raw(id, name, product_version_id)
if data:
return utils.format_json_list(data) | python | def remove_product_version_from_build_configuration(id=None, name=None, product_version_id=None):
"""
Remove a ProductVersion from association with a BuildConfiguration
"""
data = remove_product_version_from_build_configuration_raw(id, name, product_version_id)
if data:
return utils.format_json_list(data) | [
"def",
"remove_product_version_from_build_configuration",
"(",
"id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"product_version_id",
"=",
"None",
")",
":",
"data",
"=",
"remove_product_version_from_build_configuration_raw",
"(",
"id",
",",
"name",
",",
"product_vers... | Remove a ProductVersion from association with a BuildConfiguration | [
"Remove",
"a",
"ProductVersion",
"from",
"association",
"with",
"a",
"BuildConfiguration"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildconfigurations.py#L453-L459 |
project-ncl/pnc-cli | pnc_cli/buildconfigurations.py | list_revisions_of_build_configuration | def list_revisions_of_build_configuration(id=None, name=None, page_size=200, page_index=0, sort=""):
"""
List audited revisions of a BuildConfiguration
"""
data = list_revisions_of_build_configuration_raw(id, name, page_size, page_index, sort)
if data:
return utils.format_json_list(data) | python | def list_revisions_of_build_configuration(id=None, name=None, page_size=200, page_index=0, sort=""):
"""
List audited revisions of a BuildConfiguration
"""
data = list_revisions_of_build_configuration_raw(id, name, page_size, page_index, sort)
if data:
return utils.format_json_list(data) | [
"def",
"list_revisions_of_build_configuration",
"(",
"id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"page_size",
"=",
"200",
",",
"page_index",
"=",
"0",
",",
"sort",
"=",
"\"\"",
")",
":",
"data",
"=",
"list_revisions_of_build_configuration_raw",
"(",
"id"... | List audited revisions of a BuildConfiguration | [
"List",
"audited",
"revisions",
"of",
"a",
"BuildConfiguration"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildconfigurations.py#L475-L481 |
project-ncl/pnc-cli | pnc_cli/buildconfigurations.py | get_revision_of_build_configuration | def get_revision_of_build_configuration(revision_id, id=None, name=None):
"""
Get a specific audited revision of a BuildConfiguration
"""
data = get_revision_of_build_configuration_raw(revision_id, id, name)
if data:
return utils.format_json_list(data) | python | def get_revision_of_build_configuration(revision_id, id=None, name=None):
"""
Get a specific audited revision of a BuildConfiguration
"""
data = get_revision_of_build_configuration_raw(revision_id, id, name)
if data:
return utils.format_json_list(data) | [
"def",
"get_revision_of_build_configuration",
"(",
"revision_id",
",",
"id",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"data",
"=",
"get_revision_of_build_configuration_raw",
"(",
"revision_id",
",",
"id",
",",
"name",
")",
"if",
"data",
":",
"return",
... | Get a specific audited revision of a BuildConfiguration | [
"Get",
"a",
"specific",
"audited",
"revision",
"of",
"a",
"BuildConfiguration"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildconfigurations.py#L494-L500 |
project-ncl/pnc-cli | pnc_cli/buildconfigurations.py | list_build_configurations | def list_build_configurations(page_size=200, page_index=0, sort="", q=""):
"""
List all BuildConfigurations
"""
data = list_build_configurations_raw(page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | python | def list_build_configurations(page_size=200, page_index=0, sort="", q=""):
"""
List all BuildConfigurations
"""
data = list_build_configurations_raw(page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | [
"def",
"list_build_configurations",
"(",
"page_size",
"=",
"200",
",",
"page_index",
"=",
"0",
",",
"sort",
"=",
"\"\"",
",",
"q",
"=",
"\"\"",
")",
":",
"data",
"=",
"list_build_configurations_raw",
"(",
"page_size",
",",
"page_index",
",",
"sort",
",",
"... | List all BuildConfigurations | [
"List",
"all",
"BuildConfigurations"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildconfigurations.py#L513-L519 |
mithro/python-datetime-tz | datetime_tz/pytz_abbr.py | tzabbr_register | def tzabbr_register(abbr, name, region, zone, dst):
"""Register a new timezone abbreviation in the global registry.
If another abbreviation with the same name has already been registered it new
abbreviation will only be registered in region specific dictionary.
"""
newabbr = tzabbr()
newabbr.abbr = abbr
newabbr.name = name
newabbr.region = region
newabbr.zone = zone
newabbr.dst = dst
if abbr not in all:
all[abbr] = newabbr
if not region in regions:
regions[region] = {}
assert abbr not in regions[region]
regions[region][abbr] = newabbr | python | def tzabbr_register(abbr, name, region, zone, dst):
"""Register a new timezone abbreviation in the global registry.
If another abbreviation with the same name has already been registered it new
abbreviation will only be registered in region specific dictionary.
"""
newabbr = tzabbr()
newabbr.abbr = abbr
newabbr.name = name
newabbr.region = region
newabbr.zone = zone
newabbr.dst = dst
if abbr not in all:
all[abbr] = newabbr
if not region in regions:
regions[region] = {}
assert abbr not in regions[region]
regions[region][abbr] = newabbr | [
"def",
"tzabbr_register",
"(",
"abbr",
",",
"name",
",",
"region",
",",
"zone",
",",
"dst",
")",
":",
"newabbr",
"=",
"tzabbr",
"(",
")",
"newabbr",
".",
"abbr",
"=",
"abbr",
"newabbr",
".",
"name",
"=",
"name",
"newabbr",
".",
"region",
"=",
"region... | Register a new timezone abbreviation in the global registry.
If another abbreviation with the same name has already been registered it new
abbreviation will only be registered in region specific dictionary. | [
"Register",
"a",
"new",
"timezone",
"abbreviation",
"in",
"the",
"global",
"registry",
"."
] | train | https://github.com/mithro/python-datetime-tz/blob/3c682d003f8b28e39f0c096773e471aeb68e6bbb/datetime_tz/pytz_abbr.py#L71-L91 |
project-ncl/pnc-cli | pnc_cli/licenses.py | create_license | def create_license(**kwargs):
"""
Create a new License
"""
License = create_license_object(**kwargs)
response = utils.checked_api_call(pnc_api.licenses, 'create_new', body=License)
if response:
return utils.format_json(response.content) | python | def create_license(**kwargs):
"""
Create a new License
"""
License = create_license_object(**kwargs)
response = utils.checked_api_call(pnc_api.licenses, 'create_new', body=License)
if response:
return utils.format_json(response.content) | [
"def",
"create_license",
"(",
"*",
"*",
"kwargs",
")",
":",
"License",
"=",
"create_license_object",
"(",
"*",
"*",
"kwargs",
")",
"response",
"=",
"utils",
".",
"checked_api_call",
"(",
"pnc_api",
".",
"licenses",
",",
"'create_new'",
",",
"body",
"=",
"L... | Create a new License | [
"Create",
"a",
"new",
"License"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/licenses.py#L22-L29 |
project-ncl/pnc-cli | pnc_cli/licenses.py | get_license | def get_license(id):
"""
Get a specific License by either ID or fullname
"""
response = utils.checked_api_call(
pnc_api.licenses, 'get_specific', id= id)
if response:
return utils.format_json(response.content) | python | def get_license(id):
"""
Get a specific License by either ID or fullname
"""
response = utils.checked_api_call(
pnc_api.licenses, 'get_specific', id= id)
if response:
return utils.format_json(response.content) | [
"def",
"get_license",
"(",
"id",
")",
":",
"response",
"=",
"utils",
".",
"checked_api_call",
"(",
"pnc_api",
".",
"licenses",
",",
"'get_specific'",
",",
"id",
"=",
"id",
")",
"if",
"response",
":",
"return",
"utils",
".",
"format_json",
"(",
"response",
... | Get a specific License by either ID or fullname | [
"Get",
"a",
"specific",
"License",
"by",
"either",
"ID",
"or",
"fullname"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/licenses.py#L33-L40 |
project-ncl/pnc-cli | pnc_cli/licenses.py | delete_license | def delete_license(license_id):
"""
Delete a License by ID
"""
response = utils.checked_api_call(pnc_api.licenses, 'delete', id=license_id)
if response:
return utils.format_json(response.content) | python | def delete_license(license_id):
"""
Delete a License by ID
"""
response = utils.checked_api_call(pnc_api.licenses, 'delete', id=license_id)
if response:
return utils.format_json(response.content) | [
"def",
"delete_license",
"(",
"license_id",
")",
":",
"response",
"=",
"utils",
".",
"checked_api_call",
"(",
"pnc_api",
".",
"licenses",
",",
"'delete'",
",",
"id",
"=",
"license_id",
")",
"if",
"response",
":",
"return",
"utils",
".",
"format_json",
"(",
... | Delete a License by ID | [
"Delete",
"a",
"License",
"by",
"ID"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/licenses.py#L45-L52 |
project-ncl/pnc-cli | pnc_cli/licenses.py | update_license | def update_license(license_id, **kwargs):
"""
Replace the License with given ID with a new License
"""
updated_license = pnc_api.licenses.get_specific(id=license_id).content
for key, value in iteritems(kwargs):
if value:
setattr(updated_license, key, value)
response = utils.checked_api_call(
pnc_api.licenses,
'update',
id=int(license_id),
body=updated_license)
if response:
return utils.format_json(response.content) | python | def update_license(license_id, **kwargs):
"""
Replace the License with given ID with a new License
"""
updated_license = pnc_api.licenses.get_specific(id=license_id).content
for key, value in iteritems(kwargs):
if value:
setattr(updated_license, key, value)
response = utils.checked_api_call(
pnc_api.licenses,
'update',
id=int(license_id),
body=updated_license)
if response:
return utils.format_json(response.content) | [
"def",
"update_license",
"(",
"license_id",
",",
"*",
"*",
"kwargs",
")",
":",
"updated_license",
"=",
"pnc_api",
".",
"licenses",
".",
"get_specific",
"(",
"id",
"=",
"license_id",
")",
".",
"content",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
... | Replace the License with given ID with a new License | [
"Replace",
"the",
"License",
"with",
"given",
"ID",
"with",
"a",
"new",
"License"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/licenses.py#L60-L76 |
project-ncl/pnc-cli | pnc_cli/licenses.py | list_licenses | def list_licenses(page_size=200, page_index=0, sort="", q=""):
"""
List all Licenses
"""
response = utils.checked_api_call(pnc_api.licenses, 'get_all', page_size=page_size, page_index=page_index, sort=sort, q=q)
if response:
return utils.format_json_list(response.content) | python | def list_licenses(page_size=200, page_index=0, sort="", q=""):
"""
List all Licenses
"""
response = utils.checked_api_call(pnc_api.licenses, 'get_all', page_size=page_size, page_index=page_index, sort=sort, q=q)
if response:
return utils.format_json_list(response.content) | [
"def",
"list_licenses",
"(",
"page_size",
"=",
"200",
",",
"page_index",
"=",
"0",
",",
"sort",
"=",
"\"\"",
",",
"q",
"=",
"\"\"",
")",
":",
"response",
"=",
"utils",
".",
"checked_api_call",
"(",
"pnc_api",
".",
"licenses",
",",
"'get_all'",
",",
"pa... | List all Licenses | [
"List",
"all",
"Licenses"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/licenses.py#L83-L89 |
SmartTeleMax/iktomi | iktomi/unstable/utils/image_resizers.py | Resizer.transform | def transform(self, img, transformation, params):
'''
Apply transformations to the image.
New transformations can be defined as methods::
def do__transformationname(self, img, transformation, params):
'returns new image with transformation applied'
...
def new_size__transformationname(self, size, target_size, params):
'dry run, returns a size of image if transformation is applied'
...
'''
# Transformations MUST be idempotent.
# The limitation is caused by implementation of
# image upload in iktomi.cms.
# The transformation can be applied twice:
# on image upload after crop (when TransientFile is created)
# and on object save (when PersistentFile is created).
method = getattr(self, 'do__' + transformation)
return method(img, transformation, params) | python | def transform(self, img, transformation, params):
'''
Apply transformations to the image.
New transformations can be defined as methods::
def do__transformationname(self, img, transformation, params):
'returns new image with transformation applied'
...
def new_size__transformationname(self, size, target_size, params):
'dry run, returns a size of image if transformation is applied'
...
'''
# Transformations MUST be idempotent.
# The limitation is caused by implementation of
# image upload in iktomi.cms.
# The transformation can be applied twice:
# on image upload after crop (when TransientFile is created)
# and on object save (when PersistentFile is created).
method = getattr(self, 'do__' + transformation)
return method(img, transformation, params) | [
"def",
"transform",
"(",
"self",
",",
"img",
",",
"transformation",
",",
"params",
")",
":",
"# Transformations MUST be idempotent.",
"# The limitation is caused by implementation of",
"# image upload in iktomi.cms.",
"# The transformation can be applied twice:",
"# on image upload a... | Apply transformations to the image.
New transformations can be defined as methods::
def do__transformationname(self, img, transformation, params):
'returns new image with transformation applied'
...
def new_size__transformationname(self, size, target_size, params):
'dry run, returns a size of image if transformation is applied'
... | [
"Apply",
"transformations",
"to",
"the",
"image",
"."
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/unstable/utils/image_resizers.py#L34-L55 |
SmartTeleMax/iktomi | iktomi/unstable/utils/image_resizers.py | ResizeMixed.get_resizer | def get_resizer(self, size, target_size):
'''Choose a resizer depending an image size'''
sw, sh = size
if sw >= sh * self.rate:
return self.hor_resize
else:
return self.vert_resize | python | def get_resizer(self, size, target_size):
'''Choose a resizer depending an image size'''
sw, sh = size
if sw >= sh * self.rate:
return self.hor_resize
else:
return self.vert_resize | [
"def",
"get_resizer",
"(",
"self",
",",
"size",
",",
"target_size",
")",
":",
"sw",
",",
"sh",
"=",
"size",
"if",
"sw",
">=",
"sh",
"*",
"self",
".",
"rate",
":",
"return",
"self",
".",
"hor_resize",
"else",
":",
"return",
"self",
".",
"vert_resize"
... | Choose a resizer depending an image size | [
"Choose",
"a",
"resizer",
"depending",
"an",
"image",
"size"
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/unstable/utils/image_resizers.py#L160-L166 |
cosven/feeluown-core | fuocore/player.py | Playlist.add | def add(self, song):
"""往播放列表末尾添加一首歌曲"""
if song in self._songs:
return
self._songs.append(song)
logger.debug('Add %s to player playlist', song) | python | def add(self, song):
"""往播放列表末尾添加一首歌曲"""
if song in self._songs:
return
self._songs.append(song)
logger.debug('Add %s to player playlist', song) | [
"def",
"add",
"(",
"self",
",",
"song",
")",
":",
"if",
"song",
"in",
"self",
".",
"_songs",
":",
"return",
"self",
".",
"_songs",
".",
"append",
"(",
"song",
")",
"logger",
".",
"debug",
"(",
"'Add %s to player playlist'",
",",
"song",
")"
] | 往播放列表末尾添加一首歌曲 | [
"往播放列表末尾添加一首歌曲"
] | train | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/player.py#L97-L102 |
cosven/feeluown-core | fuocore/player.py | Playlist.insert | def insert(self, song):
"""在当前歌曲后插入一首歌曲"""
if song in self._songs:
return
if self._current_song is None:
self._songs.append(song)
else:
index = self._songs.index(self._current_song)
self._songs.insert(index + 1, song) | python | def insert(self, song):
"""在当前歌曲后插入一首歌曲"""
if song in self._songs:
return
if self._current_song is None:
self._songs.append(song)
else:
index = self._songs.index(self._current_song)
self._songs.insert(index + 1, song) | [
"def",
"insert",
"(",
"self",
",",
"song",
")",
":",
"if",
"song",
"in",
"self",
".",
"_songs",
":",
"return",
"if",
"self",
".",
"_current_song",
"is",
"None",
":",
"self",
".",
"_songs",
".",
"append",
"(",
"song",
")",
"else",
":",
"index",
"=",... | 在当前歌曲后插入一首歌曲 | [
"在当前歌曲后插入一首歌曲"
] | train | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/player.py#L104-L112 |
cosven/feeluown-core | fuocore/player.py | Playlist.remove | def remove(self, song):
"""Remove song from playlist. O(n)
If song is current song, remove the song and play next. Otherwise,
just remove it.
"""
if song in self._songs:
if self._current_song is None:
self._songs.remove(song)
elif song == self._current_song:
next_song = self.next_song
# 随机模式下或者歌单只剩一首歌曲,下一首可能和当前歌曲相同
if next_song == self.current_song:
self.current_song = None
self._songs.remove(song)
self.current_song = self.next_song
else:
self.current_song = self.next_song
self._songs.remove(song)
else:
self._songs.remove(song)
logger.debug('Remove {} from player playlist'.format(song))
else:
logger.debug('Remove failed: {} not in playlist'.format(song))
if song in self._bad_songs:
self._bad_songs.remove(song) | python | def remove(self, song):
"""Remove song from playlist. O(n)
If song is current song, remove the song and play next. Otherwise,
just remove it.
"""
if song in self._songs:
if self._current_song is None:
self._songs.remove(song)
elif song == self._current_song:
next_song = self.next_song
# 随机模式下或者歌单只剩一首歌曲,下一首可能和当前歌曲相同
if next_song == self.current_song:
self.current_song = None
self._songs.remove(song)
self.current_song = self.next_song
else:
self.current_song = self.next_song
self._songs.remove(song)
else:
self._songs.remove(song)
logger.debug('Remove {} from player playlist'.format(song))
else:
logger.debug('Remove failed: {} not in playlist'.format(song))
if song in self._bad_songs:
self._bad_songs.remove(song) | [
"def",
"remove",
"(",
"self",
",",
"song",
")",
":",
"if",
"song",
"in",
"self",
".",
"_songs",
":",
"if",
"self",
".",
"_current_song",
"is",
"None",
":",
"self",
".",
"_songs",
".",
"remove",
"(",
"song",
")",
"elif",
"song",
"==",
"self",
".",
... | Remove song from playlist. O(n)
If song is current song, remove the song and play next. Otherwise,
just remove it. | [
"Remove",
"song",
"from",
"playlist",
".",
"O",
"(",
"n",
")"
] | train | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/player.py#L114-L140 |
cosven/feeluown-core | fuocore/player.py | Playlist.current_song | def current_song(self, song):
"""设置当前歌曲,将歌曲加入到播放列表,并发出 song_changed 信号
.. note::
该方法理论上只应该被 Player 对象调用。
"""
self._last_song = self.current_song
if song is None:
self._current_song = None
# add it to playlist if song not in playlist
elif song in self._songs:
self._current_song = song
else:
self.insert(song)
self._current_song = song
self.song_changed.emit(song) | python | def current_song(self, song):
"""设置当前歌曲,将歌曲加入到播放列表,并发出 song_changed 信号
.. note::
该方法理论上只应该被 Player 对象调用。
"""
self._last_song = self.current_song
if song is None:
self._current_song = None
# add it to playlist if song not in playlist
elif song in self._songs:
self._current_song = song
else:
self.insert(song)
self._current_song = song
self.song_changed.emit(song) | [
"def",
"current_song",
"(",
"self",
",",
"song",
")",
":",
"self",
".",
"_last_song",
"=",
"self",
".",
"current_song",
"if",
"song",
"is",
"None",
":",
"self",
".",
"_current_song",
"=",
"None",
"# add it to playlist if song not in playlist",
"elif",
"song",
... | 设置当前歌曲,将歌曲加入到播放列表,并发出 song_changed 信号
.. note::
该方法理论上只应该被 Player 对象调用。 | [
"设置当前歌曲,将歌曲加入到播放列表,并发出",
"song_changed",
"信号"
] | train | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/player.py#L161-L177 |
cosven/feeluown-core | fuocore/player.py | Playlist._get_good_song | def _get_good_song(self, base=0, random_=False, direction=1):
"""从播放列表中获取一首可以播放的歌曲
:param base: base index
:param random: random strategy or not
:param direction: forward if > 0 else backword
>>> pl = Playlist([1, 2, 3])
>>> pl._get_good_song()
1
>>> pl._get_good_song(base=1)
2
>>> pl._bad_songs = [2]
>>> pl._get_good_song(base=1, direction=-1)
1
>>> pl._get_good_song(base=1)
3
>>> pl._bad_songs = [1, 2, 3]
>>> pl._get_good_song()
"""
if not self._songs or len(self._songs) <= len(self._bad_songs):
logger.debug('No good song in playlist.')
return None
good_songs = []
if direction > 0:
song_list = self._songs[base:] + self._songs[0:base]
else:
song_list = self._songs[base::-1] + self._songs[:base:-1]
for song in song_list:
if song not in self._bad_songs:
good_songs.append(song)
if random_:
return random.choice(good_songs)
else:
return good_songs[0] | python | def _get_good_song(self, base=0, random_=False, direction=1):
"""从播放列表中获取一首可以播放的歌曲
:param base: base index
:param random: random strategy or not
:param direction: forward if > 0 else backword
>>> pl = Playlist([1, 2, 3])
>>> pl._get_good_song()
1
>>> pl._get_good_song(base=1)
2
>>> pl._bad_songs = [2]
>>> pl._get_good_song(base=1, direction=-1)
1
>>> pl._get_good_song(base=1)
3
>>> pl._bad_songs = [1, 2, 3]
>>> pl._get_good_song()
"""
if not self._songs or len(self._songs) <= len(self._bad_songs):
logger.debug('No good song in playlist.')
return None
good_songs = []
if direction > 0:
song_list = self._songs[base:] + self._songs[0:base]
else:
song_list = self._songs[base::-1] + self._songs[:base:-1]
for song in song_list:
if song not in self._bad_songs:
good_songs.append(song)
if random_:
return random.choice(good_songs)
else:
return good_songs[0] | [
"def",
"_get_good_song",
"(",
"self",
",",
"base",
"=",
"0",
",",
"random_",
"=",
"False",
",",
"direction",
"=",
"1",
")",
":",
"if",
"not",
"self",
".",
"_songs",
"or",
"len",
"(",
"self",
".",
"_songs",
")",
"<=",
"len",
"(",
"self",
".",
"_ba... | 从播放列表中获取一首可以播放的歌曲
:param base: base index
:param random: random strategy or not
:param direction: forward if > 0 else backword
>>> pl = Playlist([1, 2, 3])
>>> pl._get_good_song()
1
>>> pl._get_good_song(base=1)
2
>>> pl._bad_songs = [2]
>>> pl._get_good_song(base=1, direction=-1)
1
>>> pl._get_good_song(base=1)
3
>>> pl._bad_songs = [1, 2, 3]
>>> pl._get_good_song() | [
"从播放列表中获取一首可以播放的歌曲"
] | train | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/player.py#L188-L223 |
cosven/feeluown-core | fuocore/player.py | Playlist.next_song | def next_song(self):
"""next song for player, calculated based on playback_mode"""
# 如果没有正在播放的歌曲,找列表里面第一首能播放的
if self.current_song is None:
return self._get_good_song()
if self.playback_mode == PlaybackMode.random:
next_song = self._get_good_song(random_=True)
else:
current_index = self._songs.index(self.current_song)
if current_index == len(self._songs) - 1:
if self.playback_mode in (PlaybackMode.loop, PlaybackMode.one_loop):
next_song = self._get_good_song()
elif self.playback_mode == PlaybackMode.sequential:
next_song = None
else:
next_song = self._get_good_song(base=current_index+1)
return next_song | python | def next_song(self):
"""next song for player, calculated based on playback_mode"""
# 如果没有正在播放的歌曲,找列表里面第一首能播放的
if self.current_song is None:
return self._get_good_song()
if self.playback_mode == PlaybackMode.random:
next_song = self._get_good_song(random_=True)
else:
current_index = self._songs.index(self.current_song)
if current_index == len(self._songs) - 1:
if self.playback_mode in (PlaybackMode.loop, PlaybackMode.one_loop):
next_song = self._get_good_song()
elif self.playback_mode == PlaybackMode.sequential:
next_song = None
else:
next_song = self._get_good_song(base=current_index+1)
return next_song | [
"def",
"next_song",
"(",
"self",
")",
":",
"# 如果没有正在播放的歌曲,找列表里面第一首能播放的",
"if",
"self",
".",
"current_song",
"is",
"None",
":",
"return",
"self",
".",
"_get_good_song",
"(",
")",
"if",
"self",
".",
"playback_mode",
"==",
"PlaybackMode",
".",
"random",
":",
"n... | next song for player, calculated based on playback_mode | [
"next",
"song",
"for",
"player",
"calculated",
"based",
"on",
"playback_mode"
] | train | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/player.py#L226-L243 |
cosven/feeluown-core | fuocore/player.py | Playlist.previous_song | def previous_song(self):
"""previous song for player to play
NOTE: not the last played song
"""
if self.current_song is None:
return self._get_good_song(base=-1, direction=-1)
if self.playback_mode == PlaybackMode.random:
previous_song = self._get_good_song(direction=-1)
else:
current_index = self._songs.index(self.current_song)
previous_song = self._get_good_song(base=current_index - 1, direction=-1)
return previous_song | python | def previous_song(self):
"""previous song for player to play
NOTE: not the last played song
"""
if self.current_song is None:
return self._get_good_song(base=-1, direction=-1)
if self.playback_mode == PlaybackMode.random:
previous_song = self._get_good_song(direction=-1)
else:
current_index = self._songs.index(self.current_song)
previous_song = self._get_good_song(base=current_index - 1, direction=-1)
return previous_song | [
"def",
"previous_song",
"(",
"self",
")",
":",
"if",
"self",
".",
"current_song",
"is",
"None",
":",
"return",
"self",
".",
"_get_good_song",
"(",
"base",
"=",
"-",
"1",
",",
"direction",
"=",
"-",
"1",
")",
"if",
"self",
".",
"playback_mode",
"==",
... | previous song for player to play
NOTE: not the last played song | [
"previous",
"song",
"for",
"player",
"to",
"play"
] | train | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/player.py#L246-L259 |
cosven/feeluown-core | fuocore/player.py | AbstractPlayer.state | def state(self, value):
"""set player state, emit state changed signal
outer object should not set state directly,
use ``pause`` / ``resume`` / ``stop`` / ``play`` method instead.
"""
self._state = value
self.state_changed.emit(value) | python | def state(self, value):
"""set player state, emit state changed signal
outer object should not set state directly,
use ``pause`` / ``resume`` / ``stop`` / ``play`` method instead.
"""
self._state = value
self.state_changed.emit(value) | [
"def",
"state",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_state",
"=",
"value",
"self",
".",
"state_changed",
".",
"emit",
"(",
"value",
")"
] | set player state, emit state changed signal
outer object should not set state directly,
use ``pause`` / ``resume`` / ``stop`` / ``play`` method instead. | [
"set",
"player",
"state",
"emit",
"state",
"changed",
"signal"
] | train | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/player.py#L296-L303 |
cosven/feeluown-core | fuocore/player.py | MpvPlayer.play_song | def play_song(self, song):
"""播放指定歌曲
如果目标歌曲与当前歌曲不相同,则修改播放列表当前歌曲,
播放列表会发出 song_changed 信号,player 监听到信号后调用 play 方法,
到那时才会真正的播放新的歌曲。如果和当前播放歌曲相同,则忽略。
.. note::
调用方不应该直接调用 playlist.current_song = song 来切换歌曲
"""
if song is not None and song == self.current_song:
logger.warning('The song is already under playing.')
else:
self._playlist.current_song = song | python | def play_song(self, song):
"""播放指定歌曲
如果目标歌曲与当前歌曲不相同,则修改播放列表当前歌曲,
播放列表会发出 song_changed 信号,player 监听到信号后调用 play 方法,
到那时才会真正的播放新的歌曲。如果和当前播放歌曲相同,则忽略。
.. note::
调用方不应该直接调用 playlist.current_song = song 来切换歌曲
"""
if song is not None and song == self.current_song:
logger.warning('The song is already under playing.')
else:
self._playlist.current_song = song | [
"def",
"play_song",
"(",
"self",
",",
"song",
")",
":",
"if",
"song",
"is",
"not",
"None",
"and",
"song",
"==",
"self",
".",
"current_song",
":",
"logger",
".",
"warning",
"(",
"'The song is already under playing.'",
")",
"else",
":",
"self",
".",
"_playli... | 播放指定歌曲
如果目标歌曲与当前歌曲不相同,则修改播放列表当前歌曲,
播放列表会发出 song_changed 信号,player 监听到信号后调用 play 方法,
到那时才会真正的播放新的歌曲。如果和当前播放歌曲相同,则忽略。
.. note::
调用方不应该直接调用 playlist.current_song = song 来切换歌曲 | [
"播放指定歌曲"
] | train | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/player.py#L443-L457 |
cosven/feeluown-core | fuocore/player.py | MpvPlayer._on_song_changed | def _on_song_changed(self, song):
"""播放列表 current_song 发生变化后的回调
判断变化后的歌曲是否有效的,有效则播放,否则将它标记为无效歌曲。
如果变化后的歌曲是 None,则停止播放。
"""
logger.debug('Player received song changed signal')
if song is not None:
logger.info('Try to play song: %s' % song)
if song.url:
self.play(song.url)
else:
self._playlist.mark_as_bad(song)
self.play_next()
else:
self.stop()
logger.info('No good song in player playlist anymore.') | python | def _on_song_changed(self, song):
"""播放列表 current_song 发生变化后的回调
判断变化后的歌曲是否有效的,有效则播放,否则将它标记为无效歌曲。
如果变化后的歌曲是 None,则停止播放。
"""
logger.debug('Player received song changed signal')
if song is not None:
logger.info('Try to play song: %s' % song)
if song.url:
self.play(song.url)
else:
self._playlist.mark_as_bad(song)
self.play_next()
else:
self.stop()
logger.info('No good song in player playlist anymore.') | [
"def",
"_on_song_changed",
"(",
"self",
",",
"song",
")",
":",
"logger",
".",
"debug",
"(",
"'Player received song changed signal'",
")",
"if",
"song",
"is",
"not",
"None",
":",
"logger",
".",
"info",
"(",
"'Try to play song: %s'",
"%",
"song",
")",
"if",
"s... | 播放列表 current_song 发生变化后的回调
判断变化后的歌曲是否有效的,有效则播放,否则将它标记为无效歌曲。
如果变化后的歌曲是 None,则停止播放。 | [
"播放列表",
"current_song",
"发生变化后的回调"
] | train | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/player.py#L519-L535 |
project-ncl/pnc-cli | pnc_cli/tools/maven_utils.py | _read_managed_gavs | def _read_managed_gavs(artifact, repo_url=None, mgmt_type=MGMT_TYPE.DEPENDENCIES, mvn_repo_local=None):
"""
Reads all artifacts managed in dependencyManagement section of effective pom of the given artifact. It places the
repo_url in settings.xml and then runs help:effective-pom with these settings. There should be the POM with its
parent and dependencies available in the repository and there should also be all plugins available needed to execute
help:effective-pom goal.
:param artifact: MavenArtifact instance representing the POM
:param repo_url: repository URL to use
:param mgmt_type: type of management to read, values available are defined in MGMT_TYPE class
:param mvn_repo_local: path to local Maven repository to be used when getting effective POM
:returns: dictionary, where key is the management type and value is the list of artifacts managed by
dependencyManagement/pluginManagement or None, if a problem occurs
"""
# download the pom
pom_path = download_pom(repo_url, artifact)
if pom_path:
pom_dir = os.path.split(pom_path)[0]
# get effective pom
eff_pom = get_effective_pom(pom_dir, repo_url, mvn_repo_local)
shutil.rmtree(pom_dir, True)
if not eff_pom:
return None
# read dependencyManagement/pluginManagement section
managed_arts = read_management(eff_pom, mgmt_type)
else:
managed_arts = None
return managed_arts | python | def _read_managed_gavs(artifact, repo_url=None, mgmt_type=MGMT_TYPE.DEPENDENCIES, mvn_repo_local=None):
"""
Reads all artifacts managed in dependencyManagement section of effective pom of the given artifact. It places the
repo_url in settings.xml and then runs help:effective-pom with these settings. There should be the POM with its
parent and dependencies available in the repository and there should also be all plugins available needed to execute
help:effective-pom goal.
:param artifact: MavenArtifact instance representing the POM
:param repo_url: repository URL to use
:param mgmt_type: type of management to read, values available are defined in MGMT_TYPE class
:param mvn_repo_local: path to local Maven repository to be used when getting effective POM
:returns: dictionary, where key is the management type and value is the list of artifacts managed by
dependencyManagement/pluginManagement or None, if a problem occurs
"""
# download the pom
pom_path = download_pom(repo_url, artifact)
if pom_path:
pom_dir = os.path.split(pom_path)[0]
# get effective pom
eff_pom = get_effective_pom(pom_dir, repo_url, mvn_repo_local)
shutil.rmtree(pom_dir, True)
if not eff_pom:
return None
# read dependencyManagement/pluginManagement section
managed_arts = read_management(eff_pom, mgmt_type)
else:
managed_arts = None
return managed_arts | [
"def",
"_read_managed_gavs",
"(",
"artifact",
",",
"repo_url",
"=",
"None",
",",
"mgmt_type",
"=",
"MGMT_TYPE",
".",
"DEPENDENCIES",
",",
"mvn_repo_local",
"=",
"None",
")",
":",
"# download the pom",
"pom_path",
"=",
"download_pom",
"(",
"repo_url",
",",
"artif... | Reads all artifacts managed in dependencyManagement section of effective pom of the given artifact. It places the
repo_url in settings.xml and then runs help:effective-pom with these settings. There should be the POM with its
parent and dependencies available in the repository and there should also be all plugins available needed to execute
help:effective-pom goal.
:param artifact: MavenArtifact instance representing the POM
:param repo_url: repository URL to use
:param mgmt_type: type of management to read, values available are defined in MGMT_TYPE class
:param mvn_repo_local: path to local Maven repository to be used when getting effective POM
:returns: dictionary, where key is the management type and value is the list of artifacts managed by
dependencyManagement/pluginManagement or None, if a problem occurs | [
"Reads",
"all",
"artifacts",
"managed",
"in",
"dependencyManagement",
"section",
"of",
"effective",
"pom",
"of",
"the",
"given",
"artifact",
".",
"It",
"places",
"the",
"repo_url",
"in",
"settings",
".",
"xml",
"and",
"then",
"runs",
"help",
":",
"effective",
... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/tools/maven_utils.py#L53-L84 |
project-ncl/pnc-cli | pnc_cli/tools/maven_utils.py | get_effective_pom | def get_effective_pom(pom_dir, repo_url, mvn_repo_local, profiles=None, additional_params=None):
"""
Gets the effective pom from the downloaded pom. There has to be complete source tree (at least the pom tree) in case
that the root pom contains some modules.
:param pom_dir: directory where the pom is prepared (including potential patches)
:param repo_url: repository URL, where all dependencies needed to resolve the effective POM are available
:param mvn_repo_local: path to local repository to use if a non-default location is required
:returns: the effective pom as a string or None if a problem occurs
"""
global effective_pom_cache
pom_file = None
try:
pom_file = open(os.path.join(pom_dir, "pom.xml"))
pom = pom_file.read()
finally:
if pom_file:
pom_file.close()
artifact = MavenArtifact(pom=pom)
gav = artifact.get_gav()
eff_pom = None
if repo_url in effective_pom_cache.keys():
if gav in effective_pom_cache[repo_url].keys():
if profiles in effective_pom_cache[repo_url][gav].keys():
if additional_params in effective_pom_cache[repo_url][gav][profiles].keys():
eff_pom = effective_pom_cache[repo_url][gav][profiles][additional_params]
if not eff_pom:
try:
eff_pom = _read_effective_pom(pom_dir, repo_url, mvn_repo_local, profiles, additional_params)
finally:
if eff_pom:
effective_pom_cache.setdefault(repo_url, {}).setdefault(gav, {}).setdefault(profiles, {})[additional_params] = eff_pom
return eff_pom | python | def get_effective_pom(pom_dir, repo_url, mvn_repo_local, profiles=None, additional_params=None):
"""
Gets the effective pom from the downloaded pom. There has to be complete source tree (at least the pom tree) in case
that the root pom contains some modules.
:param pom_dir: directory where the pom is prepared (including potential patches)
:param repo_url: repository URL, where all dependencies needed to resolve the effective POM are available
:param mvn_repo_local: path to local repository to use if a non-default location is required
:returns: the effective pom as a string or None if a problem occurs
"""
global effective_pom_cache
pom_file = None
try:
pom_file = open(os.path.join(pom_dir, "pom.xml"))
pom = pom_file.read()
finally:
if pom_file:
pom_file.close()
artifact = MavenArtifact(pom=pom)
gav = artifact.get_gav()
eff_pom = None
if repo_url in effective_pom_cache.keys():
if gav in effective_pom_cache[repo_url].keys():
if profiles in effective_pom_cache[repo_url][gav].keys():
if additional_params in effective_pom_cache[repo_url][gav][profiles].keys():
eff_pom = effective_pom_cache[repo_url][gav][profiles][additional_params]
if not eff_pom:
try:
eff_pom = _read_effective_pom(pom_dir, repo_url, mvn_repo_local, profiles, additional_params)
finally:
if eff_pom:
effective_pom_cache.setdefault(repo_url, {}).setdefault(gav, {}).setdefault(profiles, {})[additional_params] = eff_pom
return eff_pom | [
"def",
"get_effective_pom",
"(",
"pom_dir",
",",
"repo_url",
",",
"mvn_repo_local",
",",
"profiles",
"=",
"None",
",",
"additional_params",
"=",
"None",
")",
":",
"global",
"effective_pom_cache",
"pom_file",
"=",
"None",
"try",
":",
"pom_file",
"=",
"open",
"(... | Gets the effective pom from the downloaded pom. There has to be complete source tree (at least the pom tree) in case
that the root pom contains some modules.
:param pom_dir: directory where the pom is prepared (including potential patches)
:param repo_url: repository URL, where all dependencies needed to resolve the effective POM are available
:param mvn_repo_local: path to local repository to use if a non-default location is required
:returns: the effective pom as a string or None if a problem occurs | [
"Gets",
"the",
"effective",
"pom",
"from",
"the",
"downloaded",
"pom",
".",
"There",
"has",
"to",
"be",
"complete",
"source",
"tree",
"(",
"at",
"least",
"the",
"pom",
"tree",
")",
"in",
"case",
"that",
"the",
"root",
"pom",
"contains",
"some",
"modules"... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/tools/maven_utils.py#L87-L123 |
project-ncl/pnc-cli | pnc_cli/tools/maven_utils.py | alter_poms | def alter_poms(pom_dir, additional_params, repo_url=None, mvn_repo_local=None):
"""
Runs mvn clean command with provided additional parameters to perform pom updates by pom-manipulation-ext.
"""
work_dir = os.getcwd()
os.chdir(pom_dir)
try:
if repo_url:
settings_filename = create_mirror_settings(repo_url)
else:
settings_filename = None
args = ["mvn", "clean"]
if mvn_repo_local:
args.extend(["-s", settings_filename])
if mvn_repo_local:
args.append("-Dmaven.repo.local=%s" % mvn_repo_local)
param_list = additional_params.split(" ")
args.extend(param_list)
logging.debug("Running command: %s", " ".join(args))
command = Popen(args, stdout=PIPE, stderr=STDOUT)
stdout = command.communicate()[0]
if command.returncode:
logging.error("POM manipulation failed. Output:\n%s" % stdout)
else:
logging.debug("POM manipulation succeeded. Output:\n%s" % stdout)
finally:
os.chdir(work_dir) | python | def alter_poms(pom_dir, additional_params, repo_url=None, mvn_repo_local=None):
"""
Runs mvn clean command with provided additional parameters to perform pom updates by pom-manipulation-ext.
"""
work_dir = os.getcwd()
os.chdir(pom_dir)
try:
if repo_url:
settings_filename = create_mirror_settings(repo_url)
else:
settings_filename = None
args = ["mvn", "clean"]
if mvn_repo_local:
args.extend(["-s", settings_filename])
if mvn_repo_local:
args.append("-Dmaven.repo.local=%s" % mvn_repo_local)
param_list = additional_params.split(" ")
args.extend(param_list)
logging.debug("Running command: %s", " ".join(args))
command = Popen(args, stdout=PIPE, stderr=STDOUT)
stdout = command.communicate()[0]
if command.returncode:
logging.error("POM manipulation failed. Output:\n%s" % stdout)
else:
logging.debug("POM manipulation succeeded. Output:\n%s" % stdout)
finally:
os.chdir(work_dir) | [
"def",
"alter_poms",
"(",
"pom_dir",
",",
"additional_params",
",",
"repo_url",
"=",
"None",
",",
"mvn_repo_local",
"=",
"None",
")",
":",
"work_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"os",
".",
"chdir",
"(",
"pom_dir",
")",
"try",
":",
"if",
"repo_... | Runs mvn clean command with provided additional parameters to perform pom updates by pom-manipulation-ext. | [
"Runs",
"mvn",
"clean",
"command",
"with",
"provided",
"additional",
"parameters",
"to",
"perform",
"pom",
"updates",
"by",
"pom",
"-",
"manipulation",
"-",
"ext",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/tools/maven_utils.py#L165-L194 |
project-ncl/pnc-cli | pnc_cli/tools/maven_utils.py | pom_contains_modules | def pom_contains_modules():
"""
Reads pom.xml in current working directory and checks, if there is non-empty modules tag.
"""
pom_file = None
try:
pom_file = open("pom.xml")
pom = pom_file.read()
finally:
if pom_file:
pom_file.close()
artifact = MavenArtifact(pom=pom)
if artifact.modules:
return True
else:
return False | python | def pom_contains_modules():
"""
Reads pom.xml in current working directory and checks, if there is non-empty modules tag.
"""
pom_file = None
try:
pom_file = open("pom.xml")
pom = pom_file.read()
finally:
if pom_file:
pom_file.close()
artifact = MavenArtifact(pom=pom)
if artifact.modules:
return True
else:
return False | [
"def",
"pom_contains_modules",
"(",
")",
":",
"pom_file",
"=",
"None",
"try",
":",
"pom_file",
"=",
"open",
"(",
"\"pom.xml\"",
")",
"pom",
"=",
"pom_file",
".",
"read",
"(",
")",
"finally",
":",
"if",
"pom_file",
":",
"pom_file",
".",
"close",
"(",
")... | Reads pom.xml in current working directory and checks, if there is non-empty modules tag. | [
"Reads",
"pom",
".",
"xml",
"in",
"current",
"working",
"directory",
"and",
"checks",
"if",
"there",
"is",
"non",
"-",
"empty",
"modules",
"tag",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/tools/maven_utils.py#L196-L212 |
project-ncl/pnc-cli | pnc_cli/tools/maven_utils.py | get_repo_url | def get_repo_url(mead_tag, nexus_base_url, prefix="hudson-", suffix=""):
"""
Creates repository Nexus group URL composed of:
<nexus_base_url>/content/groups/<prefix><mead_tag><suffix>
:param mead_tag: name of the MEAD tag used to create the proxy URL in settings.xml
:param nexus_base_url: the base URL of a Nexus instance
:param prefix: Nexus group name prefix, default is "hudson-"
:param suffix: Nexus group name suffix, e.g. "-jboss-central" or "-reverse"
:returns:
"""
result = urlparse.urljoin(nexus_base_url, "content/groups/")
result = urlparse.urljoin(result, "%s%s%s/" % (prefix, mead_tag, suffix))
return result | python | def get_repo_url(mead_tag, nexus_base_url, prefix="hudson-", suffix=""):
"""
Creates repository Nexus group URL composed of:
<nexus_base_url>/content/groups/<prefix><mead_tag><suffix>
:param mead_tag: name of the MEAD tag used to create the proxy URL in settings.xml
:param nexus_base_url: the base URL of a Nexus instance
:param prefix: Nexus group name prefix, default is "hudson-"
:param suffix: Nexus group name suffix, e.g. "-jboss-central" or "-reverse"
:returns:
"""
result = urlparse.urljoin(nexus_base_url, "content/groups/")
result = urlparse.urljoin(result, "%s%s%s/" % (prefix, mead_tag, suffix))
return result | [
"def",
"get_repo_url",
"(",
"mead_tag",
",",
"nexus_base_url",
",",
"prefix",
"=",
"\"hudson-\"",
",",
"suffix",
"=",
"\"\"",
")",
":",
"result",
"=",
"urlparse",
".",
"urljoin",
"(",
"nexus_base_url",
",",
"\"content/groups/\"",
")",
"result",
"=",
"urlparse"... | Creates repository Nexus group URL composed of:
<nexus_base_url>/content/groups/<prefix><mead_tag><suffix>
:param mead_tag: name of the MEAD tag used to create the proxy URL in settings.xml
:param nexus_base_url: the base URL of a Nexus instance
:param prefix: Nexus group name prefix, default is "hudson-"
:param suffix: Nexus group name suffix, e.g. "-jboss-central" or "-reverse"
:returns: | [
"Creates",
"repository",
"Nexus",
"group",
"URL",
"composed",
"of",
":",
"<nexus_base_url",
">",
"/",
"content",
"/",
"groups",
"/",
"<prefix",
">",
"<mead_tag",
">",
"<suffix",
">"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/tools/maven_utils.py#L215-L228 |
project-ncl/pnc-cli | pnc_cli/tools/maven_utils.py | download_pom | def download_pom(repo_url=None, artifact=None, pom_url=None, target_dir=None):
"""
Downloads a pom file with give GAV (as array) or from given pom_url and saves it as pom.xml into target_dir.
:param repo_url: repository URL from which the pom should be downloaded, mandatory only if no pom_url provided
:param artifact: MavenArtifact instance, mandatory only if no pom_url provided
:param pom_url: URL of the pom to download, not mandatory
:target_dir: target directory path, where the pom should be saved, not mandatory
:returns: path to the saved pom, useful if no target_dir provided
"""
if not pom_url:
pom_url = urlparse.urljoin(repo_url, "%s/" % string.replace(artifact.groupId, ".", "/"))
pom_url = urlparse.urljoin(pom_url, "%s/" % artifact.artifactId)
pom_url = urlparse.urljoin(pom_url, "%s/" % artifact.version)
pom_url = urlparse.urljoin(pom_url, "%s-%s.pom" % (artifact.artifactId, artifact.version))
handler = None
try:
handler = urlopen(pom_url)
except HTTPError as err:
logging.error("Failed to download POM %s. %s", pom_url, err)
return None
if not target_dir:
num = 1
while not target_dir or os.path.exists(target_dir):
target_dir = "/tmp/maven-temp-path-%s" % num
num += 1
pom_path = os.path.join(target_dir, "pom.xml")
if handler.getcode() == 200:
pom = handler.read()
handler.close()
if not os.path.exists(target_dir):
os.makedirs(target_dir)
pom_file = None
try:
pom_file = open(pom_path, "w")
pom_file.write(pom)
finally:
if pom_file:
pom_file.close()
return pom_path | python | def download_pom(repo_url=None, artifact=None, pom_url=None, target_dir=None):
"""
Downloads a pom file with give GAV (as array) or from given pom_url and saves it as pom.xml into target_dir.
:param repo_url: repository URL from which the pom should be downloaded, mandatory only if no pom_url provided
:param artifact: MavenArtifact instance, mandatory only if no pom_url provided
:param pom_url: URL of the pom to download, not mandatory
:target_dir: target directory path, where the pom should be saved, not mandatory
:returns: path to the saved pom, useful if no target_dir provided
"""
if not pom_url:
pom_url = urlparse.urljoin(repo_url, "%s/" % string.replace(artifact.groupId, ".", "/"))
pom_url = urlparse.urljoin(pom_url, "%s/" % artifact.artifactId)
pom_url = urlparse.urljoin(pom_url, "%s/" % artifact.version)
pom_url = urlparse.urljoin(pom_url, "%s-%s.pom" % (artifact.artifactId, artifact.version))
handler = None
try:
handler = urlopen(pom_url)
except HTTPError as err:
logging.error("Failed to download POM %s. %s", pom_url, err)
return None
if not target_dir:
num = 1
while not target_dir or os.path.exists(target_dir):
target_dir = "/tmp/maven-temp-path-%s" % num
num += 1
pom_path = os.path.join(target_dir, "pom.xml")
if handler.getcode() == 200:
pom = handler.read()
handler.close()
if not os.path.exists(target_dir):
os.makedirs(target_dir)
pom_file = None
try:
pom_file = open(pom_path, "w")
pom_file.write(pom)
finally:
if pom_file:
pom_file.close()
return pom_path | [
"def",
"download_pom",
"(",
"repo_url",
"=",
"None",
",",
"artifact",
"=",
"None",
",",
"pom_url",
"=",
"None",
",",
"target_dir",
"=",
"None",
")",
":",
"if",
"not",
"pom_url",
":",
"pom_url",
"=",
"urlparse",
".",
"urljoin",
"(",
"repo_url",
",",
"\"... | Downloads a pom file with give GAV (as array) or from given pom_url and saves it as pom.xml into target_dir.
:param repo_url: repository URL from which the pom should be downloaded, mandatory only if no pom_url provided
:param artifact: MavenArtifact instance, mandatory only if no pom_url provided
:param pom_url: URL of the pom to download, not mandatory
:target_dir: target directory path, where the pom should be saved, not mandatory
:returns: path to the saved pom, useful if no target_dir provided | [
"Downloads",
"a",
"pom",
"file",
"with",
"give",
"GAV",
"(",
"as",
"array",
")",
"or",
"from",
"given",
"pom_url",
"and",
"saves",
"it",
"as",
"pom",
".",
"xml",
"into",
"target_dir",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/tools/maven_utils.py#L231-L275 |
project-ncl/pnc-cli | pnc_cli/tools/maven_utils.py | create_mirror_settings | def create_mirror_settings(repo_url):
"""
Creates settings.xml in current working directory, which when used makes Maven use given repo URL as a mirror of all
repositories to look at.
:param repo_url: the repository URL to use
:returns: filepath to the created file
"""
cwd = os.getcwd()
settings_path = os.path.join(cwd, "settings.xml")
settings_file = None
try:
settings_file = open(settings_path, "w")
settings_file.write('<?xml version="1.0" encoding="UTF-8"?>\n')
settings_file.write('<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"\n')
settings_file.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\n')
settings_file.write(' xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">\n')
settings_file.write('<mirrors>\n')
settings_file.write(' <mirror>\n')
settings_file.write(' <id>repo-mirror</id>\n')
settings_file.write(' <url>%s</url>\n' % repo_url)
settings_file.write(' <mirrorOf>*</mirrorOf>\n')
settings_file.write(' </mirror>\n')
settings_file.write(' </mirrors>\n')
settings_file.write('</settings>\n')
finally:
if settings_file:
settings_file.close()
return settings_path | python | def create_mirror_settings(repo_url):
"""
Creates settings.xml in current working directory, which when used makes Maven use given repo URL as a mirror of all
repositories to look at.
:param repo_url: the repository URL to use
:returns: filepath to the created file
"""
cwd = os.getcwd()
settings_path = os.path.join(cwd, "settings.xml")
settings_file = None
try:
settings_file = open(settings_path, "w")
settings_file.write('<?xml version="1.0" encoding="UTF-8"?>\n')
settings_file.write('<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"\n')
settings_file.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\n')
settings_file.write(' xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">\n')
settings_file.write('<mirrors>\n')
settings_file.write(' <mirror>\n')
settings_file.write(' <id>repo-mirror</id>\n')
settings_file.write(' <url>%s</url>\n' % repo_url)
settings_file.write(' <mirrorOf>*</mirrorOf>\n')
settings_file.write(' </mirror>\n')
settings_file.write(' </mirrors>\n')
settings_file.write('</settings>\n')
finally:
if settings_file:
settings_file.close()
return settings_path | [
"def",
"create_mirror_settings",
"(",
"repo_url",
")",
":",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"settings_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cwd",
",",
"\"settings.xml\"",
")",
"settings_file",
"=",
"None",
"try",
":",
"settings_file"... | Creates settings.xml in current working directory, which when used makes Maven use given repo URL as a mirror of all
repositories to look at.
:param repo_url: the repository URL to use
:returns: filepath to the created file | [
"Creates",
"settings",
".",
"xml",
"in",
"current",
"working",
"directory",
"which",
"when",
"used",
"makes",
"Maven",
"use",
"given",
"repo",
"URL",
"as",
"a",
"mirror",
"of",
"all",
"repositories",
"to",
"look",
"at",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/tools/maven_utils.py#L363-L393 |
cosven/feeluown-core | fuocore/netease/api.py | API.search | def search(self, s, stype=1, offset=0, total='true', limit=60):
"""get songs list from search keywords"""
action = uri + '/search/get'
data = {
's': s,
'type': stype,
'offset': offset,
'total': total,
'limit': 60
}
resp = self.request('POST', action, data)
if resp['code'] == 200:
return resp['result']['songs']
return [] | python | def search(self, s, stype=1, offset=0, total='true', limit=60):
"""get songs list from search keywords"""
action = uri + '/search/get'
data = {
's': s,
'type': stype,
'offset': offset,
'total': total,
'limit': 60
}
resp = self.request('POST', action, data)
if resp['code'] == 200:
return resp['result']['songs']
return [] | [
"def",
"search",
"(",
"self",
",",
"s",
",",
"stype",
"=",
"1",
",",
"offset",
"=",
"0",
",",
"total",
"=",
"'true'",
",",
"limit",
"=",
"60",
")",
":",
"action",
"=",
"uri",
"+",
"'/search/get'",
"data",
"=",
"{",
"'s'",
":",
"s",
",",
"'type'... | get songs list from search keywords | [
"get",
"songs",
"list",
"from",
"search",
"keywords"
] | train | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/netease/api.py#L116-L129 |
cosven/feeluown-core | fuocore/netease/api.py | API.artist_infos | def artist_infos(self, artist_id):
"""
:param artist_id: artist_id
:return: {
code: int,
artist: {artist},
more: boolean,
hotSongs: [songs]
}
"""
action = uri + '/artist/' + str(artist_id)
data = self.request('GET', action)
return data | python | def artist_infos(self, artist_id):
"""
:param artist_id: artist_id
:return: {
code: int,
artist: {artist},
more: boolean,
hotSongs: [songs]
}
"""
action = uri + '/artist/' + str(artist_id)
data = self.request('GET', action)
return data | [
"def",
"artist_infos",
"(",
"self",
",",
"artist_id",
")",
":",
"action",
"=",
"uri",
"+",
"'/artist/'",
"+",
"str",
"(",
"artist_id",
")",
"data",
"=",
"self",
".",
"request",
"(",
"'GET'",
",",
"action",
")",
"return",
"data"
] | :param artist_id: artist_id
:return: {
code: int,
artist: {artist},
more: boolean,
hotSongs: [songs]
} | [
":",
"param",
"artist_id",
":",
"artist_id",
":",
"return",
":",
"{",
"code",
":",
"int",
"artist",
":",
"{",
"artist",
"}",
"more",
":",
"boolean",
"hotSongs",
":",
"[",
"songs",
"]",
"}"
] | train | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/netease/api.py#L165-L177 |
cosven/feeluown-core | fuocore/netease/api.py | API.album_infos | def album_infos(self, album_id):
"""
:param album_id:
:return: {
code: int,
album: { album }
}
"""
action = uri + '/album/' + str(album_id)
data = self.request('GET', action)
if data['code'] == 200:
return data['album'] | python | def album_infos(self, album_id):
"""
:param album_id:
:return: {
code: int,
album: { album }
}
"""
action = uri + '/album/' + str(album_id)
data = self.request('GET', action)
if data['code'] == 200:
return data['album'] | [
"def",
"album_infos",
"(",
"self",
",",
"album_id",
")",
":",
"action",
"=",
"uri",
"+",
"'/album/'",
"+",
"str",
"(",
"album_id",
")",
"data",
"=",
"self",
".",
"request",
"(",
"'GET'",
",",
"action",
")",
"if",
"data",
"[",
"'code'",
"]",
"==",
"... | :param album_id:
:return: {
code: int,
album: { album }
} | [
":",
"param",
"album_id",
":",
":",
"return",
":",
"{",
"code",
":",
"int",
"album",
":",
"{",
"album",
"}",
"}"
] | train | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/netease/api.py#L180-L191 |
cosven/feeluown-core | fuocore/netease/api.py | API.op_music_to_playlist | def op_music_to_playlist(self, mid, pid, op):
"""
:param op: add or del
"""
url_add = uri + '/playlist/manipulate/tracks'
trackIds = '["' + str(mid) + '"]'
data_add = {
'tracks': str(mid), # music id
'pid': str(pid), # playlist id
'trackIds': trackIds, # music id str
'op': op # opation
}
data = self.request('POST', url_add, data_add)
code = data.get('code')
# 从歌单中成功的移除歌曲时,code 是 200
# 当从歌单中移除一首不存在的歌曲时,code 也是 200
# 当向歌单添加歌曲时,如果歌曲已经在列表当中,
# 返回 code 为 502
if code == 200:
return 1
elif code == 502:
return -1
else:
return 0 | python | def op_music_to_playlist(self, mid, pid, op):
"""
:param op: add or del
"""
url_add = uri + '/playlist/manipulate/tracks'
trackIds = '["' + str(mid) + '"]'
data_add = {
'tracks': str(mid), # music id
'pid': str(pid), # playlist id
'trackIds': trackIds, # music id str
'op': op # opation
}
data = self.request('POST', url_add, data_add)
code = data.get('code')
# 从歌单中成功的移除歌曲时,code 是 200
# 当从歌单中移除一首不存在的歌曲时,code 也是 200
# 当向歌单添加歌曲时,如果歌曲已经在列表当中,
# 返回 code 为 502
if code == 200:
return 1
elif code == 502:
return -1
else:
return 0 | [
"def",
"op_music_to_playlist",
"(",
"self",
",",
"mid",
",",
"pid",
",",
"op",
")",
":",
"url_add",
"=",
"uri",
"+",
"'/playlist/manipulate/tracks'",
"trackIds",
"=",
"'[\"'",
"+",
"str",
"(",
"mid",
")",
"+",
"'\"]'",
"data_add",
"=",
"{",
"'tracks'",
"... | :param op: add or del | [
":",
"param",
"op",
":",
"add",
"or",
"del"
] | train | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/netease/api.py#L261-L285 |
cosven/feeluown-core | fuocore/netease/api.py | API.get_mv_detail | def get_mv_detail(self, mvid):
"""Get mv detail
:param mvid: mv id
:return:
"""
url = uri + '/mv/detail?id=' + str(mvid)
return self.request('GET', url) | python | def get_mv_detail(self, mvid):
"""Get mv detail
:param mvid: mv id
:return:
"""
url = uri + '/mv/detail?id=' + str(mvid)
return self.request('GET', url) | [
"def",
"get_mv_detail",
"(",
"self",
",",
"mvid",
")",
":",
"url",
"=",
"uri",
"+",
"'/mv/detail?id='",
"+",
"str",
"(",
"mvid",
")",
"return",
"self",
".",
"request",
"(",
"'GET'",
",",
"url",
")"
] | Get mv detail
:param mvid: mv id
:return: | [
"Get",
"mv",
"detail",
":",
"param",
"mvid",
":",
"mv",
"id",
":",
"return",
":"
] | train | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/netease/api.py#L300-L306 |
cosven/feeluown-core | fuocore/netease/api.py | API.get_lyric_by_songid | def get_lyric_by_songid(self, mid):
"""Get song lyric
:param mid: music id
:return: {
lrc: {
version: int,
lyric: str
},
tlyric: {
version: int,
lyric: str
}
sgc: bool,
qfy: bool,
sfy: bool,
transUser: {},
code: int,
}
"""
# tv 表示翻译。-1:表示要翻译,1:不要
url = uri + '/song/lyric?' + 'id=' + str(mid) + '&lv=1&kv=1&tv=-1'
return self.request('GET', url) | python | def get_lyric_by_songid(self, mid):
"""Get song lyric
:param mid: music id
:return: {
lrc: {
version: int,
lyric: str
},
tlyric: {
version: int,
lyric: str
}
sgc: bool,
qfy: bool,
sfy: bool,
transUser: {},
code: int,
}
"""
# tv 表示翻译。-1:表示要翻译,1:不要
url = uri + '/song/lyric?' + 'id=' + str(mid) + '&lv=1&kv=1&tv=-1'
return self.request('GET', url) | [
"def",
"get_lyric_by_songid",
"(",
"self",
",",
"mid",
")",
":",
"# tv 表示翻译。-1:表示要翻译,1:不要",
"url",
"=",
"uri",
"+",
"'/song/lyric?'",
"+",
"'id='",
"+",
"str",
"(",
"mid",
")",
"+",
"'&lv=1&kv=1&tv=-1'",
"return",
"self",
".",
"request",
"(",
"'GET'",
",",
... | Get song lyric
:param mid: music id
:return: {
lrc: {
version: int,
lyric: str
},
tlyric: {
version: int,
lyric: str
}
sgc: bool,
qfy: bool,
sfy: bool,
transUser: {},
code: int,
} | [
"Get",
"song",
"lyric",
":",
"param",
"mid",
":",
"music",
"id",
":",
"return",
":",
"{",
"lrc",
":",
"{",
"version",
":",
"int",
"lyric",
":",
"str",
"}",
"tlyric",
":",
"{",
"version",
":",
"int",
"lyric",
":",
"str",
"}",
"sgc",
":",
"bool",
... | train | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/netease/api.py#L308-L329 |
CivicSpleen/ambry | ambry/library/search_backends/whoosh_backend.py | _init_index | def _init_index(root_dir, schema, index_name):
""" Creates new index or opens existing.
Args:
root_dir (str): root dir where to find or create index.
schema (whoosh.fields.Schema): schema of the index to create or open.
index_name (str): name of the index.
Returns:
tuple ((whoosh.index.FileIndex, str)): first element is index, second is index directory.
"""
index_dir = os.path.join(root_dir, index_name)
try:
if not os.path.exists(index_dir):
os.makedirs(index_dir)
return create_in(index_dir, schema), index_dir
else:
return open_dir(index_dir), index_dir
except Exception as e:
logger.error("Init error: failed to open search index at: '{}': {} ".format(index_dir, e))
raise | python | def _init_index(root_dir, schema, index_name):
""" Creates new index or opens existing.
Args:
root_dir (str): root dir where to find or create index.
schema (whoosh.fields.Schema): schema of the index to create or open.
index_name (str): name of the index.
Returns:
tuple ((whoosh.index.FileIndex, str)): first element is index, second is index directory.
"""
index_dir = os.path.join(root_dir, index_name)
try:
if not os.path.exists(index_dir):
os.makedirs(index_dir)
return create_in(index_dir, schema), index_dir
else:
return open_dir(index_dir), index_dir
except Exception as e:
logger.error("Init error: failed to open search index at: '{}': {} ".format(index_dir, e))
raise | [
"def",
"_init_index",
"(",
"root_dir",
",",
"schema",
",",
"index_name",
")",
":",
"index_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root_dir",
",",
"index_name",
")",
"try",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"index_dir",
... | Creates new index or opens existing.
Args:
root_dir (str): root dir where to find or create index.
schema (whoosh.fields.Schema): schema of the index to create or open.
index_name (str): name of the index.
Returns:
tuple ((whoosh.index.FileIndex, str)): first element is index, second is index directory. | [
"Creates",
"new",
"index",
"or",
"opens",
"existing",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/whoosh_backend.py#L410-L431 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.