id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
232,400 | mozilla/mozilla-django-oidc | mozilla_django_oidc/middleware.py | SessionRefresh.is_refreshable_url | def is_refreshable_url(self, request):
"""Takes a request and returns whether it triggers a refresh examination
:arg HttpRequest request:
:returns: boolean
"""
# Do not attempt to refresh the session if the OIDC backend is not used
backend_session = request.session.get(BACKEND_SESSION_KEY)
is_oidc_enabled = True
if backend_session:
auth_backend = import_string(backend_session)
is_oidc_enabled = issubclass(auth_backend, OIDCAuthenticationBackend)
return (
request.method == 'GET' and
is_authenticated(request.user) and
is_oidc_enabled and
request.path not in self.exempt_urls
) | python | def is_refreshable_url(self, request):
# Do not attempt to refresh the session if the OIDC backend is not used
backend_session = request.session.get(BACKEND_SESSION_KEY)
is_oidc_enabled = True
if backend_session:
auth_backend = import_string(backend_session)
is_oidc_enabled = issubclass(auth_backend, OIDCAuthenticationBackend)
return (
request.method == 'GET' and
is_authenticated(request.user) and
is_oidc_enabled and
request.path not in self.exempt_urls
) | [
"def",
"is_refreshable_url",
"(",
"self",
",",
"request",
")",
":",
"# Do not attempt to refresh the session if the OIDC backend is not used",
"backend_session",
"=",
"request",
".",
"session",
".",
"get",
"(",
"BACKEND_SESSION_KEY",
")",
"is_oidc_enabled",
"=",
"True",
"... | Takes a request and returns whether it triggers a refresh examination
:arg HttpRequest request:
:returns: boolean | [
"Takes",
"a",
"request",
"and",
"returns",
"whether",
"it",
"triggers",
"a",
"refresh",
"examination"
] | e780130deacccbafc85a92f48d1407e042f5f955 | https://github.com/mozilla/mozilla-django-oidc/blob/e780130deacccbafc85a92f48d1407e042f5f955/mozilla_django_oidc/middleware.py#L67-L87 |
232,401 | Jahaja/psdash | psdash/log.py | ReverseFileSearcher._read | def _read(self):
"""
Reads and returns a buffer reversely from current file-pointer position.
:rtype : str
"""
filepos = self._fp.tell()
if filepos < 1:
return ""
destpos = max(filepos - self._chunk_size, 0)
self._fp.seek(destpos)
buf = self._fp.read(filepos - destpos)
self._fp.seek(destpos)
return buf | python | def _read(self):
filepos = self._fp.tell()
if filepos < 1:
return ""
destpos = max(filepos - self._chunk_size, 0)
self._fp.seek(destpos)
buf = self._fp.read(filepos - destpos)
self._fp.seek(destpos)
return buf | [
"def",
"_read",
"(",
"self",
")",
":",
"filepos",
"=",
"self",
".",
"_fp",
".",
"tell",
"(",
")",
"if",
"filepos",
"<",
"1",
":",
"return",
"\"\"",
"destpos",
"=",
"max",
"(",
"filepos",
"-",
"self",
".",
"_chunk_size",
",",
"0",
")",
"self",
"."... | Reads and returns a buffer reversely from current file-pointer position.
:rtype : str | [
"Reads",
"and",
"returns",
"a",
"buffer",
"reversely",
"from",
"current",
"file",
"-",
"pointer",
"position",
"."
] | 4f1784742666045a3c33bd471dbe489b4f5c7699 | https://github.com/Jahaja/psdash/blob/4f1784742666045a3c33bd471dbe489b4f5c7699/psdash/log.py#L42-L55 |
232,402 | Jahaja/psdash | psdash/log.py | ReverseFileSearcher.find | def find(self):
"""
Returns the position of the first occurence of needle.
If the needle was not found, -1 is returned.
:rtype : int
"""
lastbuf = ""
while 0 < self._fp.tell():
buf = self._read()
bufpos = (buf + lastbuf).rfind(self._needle)
if bufpos > -1:
filepos = self._fp.tell() + bufpos
self._fp.seek(filepos)
return filepos
# for it to work when the needle is split between chunks.
lastbuf = buf[:len(self._needle)]
return -1 | python | def find(self):
lastbuf = ""
while 0 < self._fp.tell():
buf = self._read()
bufpos = (buf + lastbuf).rfind(self._needle)
if bufpos > -1:
filepos = self._fp.tell() + bufpos
self._fp.seek(filepos)
return filepos
# for it to work when the needle is split between chunks.
lastbuf = buf[:len(self._needle)]
return -1 | [
"def",
"find",
"(",
"self",
")",
":",
"lastbuf",
"=",
"\"\"",
"while",
"0",
"<",
"self",
".",
"_fp",
".",
"tell",
"(",
")",
":",
"buf",
"=",
"self",
".",
"_read",
"(",
")",
"bufpos",
"=",
"(",
"buf",
"+",
"lastbuf",
")",
".",
"rfind",
"(",
"s... | Returns the position of the first occurence of needle.
If the needle was not found, -1 is returned.
:rtype : int | [
"Returns",
"the",
"position",
"of",
"the",
"first",
"occurence",
"of",
"needle",
".",
"If",
"the",
"needle",
"was",
"not",
"found",
"-",
"1",
"is",
"returned",
"."
] | 4f1784742666045a3c33bd471dbe489b4f5c7699 | https://github.com/Jahaja/psdash/blob/4f1784742666045a3c33bd471dbe489b4f5c7699/psdash/log.py#L57-L76 |
232,403 | Jahaja/psdash | psdash/log.py | LogReader.search | def search(self, text):
"""
Find text in log file from current position
returns a tuple containing:
absolute position,
position in result buffer,
result buffer (the actual file contents)
"""
key = hash(text)
searcher = self._searchers.get(key)
if not searcher:
searcher = ReverseFileSearcher(self.filename, text)
self._searchers[key] = searcher
position = searcher.find()
if position < 0:
# reset the searcher to start from the tail again.
searcher.reset()
return -1, -1, ''
# try to get some content from before and after the result's position
read_before = self.buffer_size / 2
offset = max(position - read_before, 0)
bufferpos = position if offset == 0 else read_before
self.fp.seek(offset)
return position, bufferpos, self.read() | python | def search(self, text):
key = hash(text)
searcher = self._searchers.get(key)
if not searcher:
searcher = ReverseFileSearcher(self.filename, text)
self._searchers[key] = searcher
position = searcher.find()
if position < 0:
# reset the searcher to start from the tail again.
searcher.reset()
return -1, -1, ''
# try to get some content from before and after the result's position
read_before = self.buffer_size / 2
offset = max(position - read_before, 0)
bufferpos = position if offset == 0 else read_before
self.fp.seek(offset)
return position, bufferpos, self.read() | [
"def",
"search",
"(",
"self",
",",
"text",
")",
":",
"key",
"=",
"hash",
"(",
"text",
")",
"searcher",
"=",
"self",
".",
"_searchers",
".",
"get",
"(",
"key",
")",
"if",
"not",
"searcher",
":",
"searcher",
"=",
"ReverseFileSearcher",
"(",
"self",
"."... | Find text in log file from current position
returns a tuple containing:
absolute position,
position in result buffer,
result buffer (the actual file contents) | [
"Find",
"text",
"in",
"log",
"file",
"from",
"current",
"position"
] | 4f1784742666045a3c33bd471dbe489b4f5c7699 | https://github.com/Jahaja/psdash/blob/4f1784742666045a3c33bd471dbe489b4f5c7699/psdash/log.py#L114-L140 |
232,404 | Jahaja/psdash | psdash/net.py | get_interface_addresses | def get_interface_addresses():
"""
Get addresses of available network interfaces.
See netifaces on pypi for details.
Returns a list of dicts
"""
addresses = []
ifaces = netifaces.interfaces()
for iface in ifaces:
addrs = netifaces.ifaddresses(iface)
families = addrs.keys()
# put IPv4 to the end so it lists as the main iface address
if netifaces.AF_INET in families:
families.remove(netifaces.AF_INET)
families.append(netifaces.AF_INET)
for family in families:
for addr in addrs[family]:
address = {
'name': iface,
'family': family,
'ip': addr['addr'],
}
addresses.append(address)
return addresses | python | def get_interface_addresses():
addresses = []
ifaces = netifaces.interfaces()
for iface in ifaces:
addrs = netifaces.ifaddresses(iface)
families = addrs.keys()
# put IPv4 to the end so it lists as the main iface address
if netifaces.AF_INET in families:
families.remove(netifaces.AF_INET)
families.append(netifaces.AF_INET)
for family in families:
for addr in addrs[family]:
address = {
'name': iface,
'family': family,
'ip': addr['addr'],
}
addresses.append(address)
return addresses | [
"def",
"get_interface_addresses",
"(",
")",
":",
"addresses",
"=",
"[",
"]",
"ifaces",
"=",
"netifaces",
".",
"interfaces",
"(",
")",
"for",
"iface",
"in",
"ifaces",
":",
"addrs",
"=",
"netifaces",
".",
"ifaddresses",
"(",
"iface",
")",
"families",
"=",
... | Get addresses of available network interfaces.
See netifaces on pypi for details.
Returns a list of dicts | [
"Get",
"addresses",
"of",
"available",
"network",
"interfaces",
".",
"See",
"netifaces",
"on",
"pypi",
"for",
"details",
"."
] | 4f1784742666045a3c33bd471dbe489b4f5c7699 | https://github.com/Jahaja/psdash/blob/4f1784742666045a3c33bd471dbe489b4f5c7699/psdash/net.py#L61-L89 |
232,405 | Jahaja/psdash | psdash/net.py | NetIOCounters._get_net_io_counters | def _get_net_io_counters(self):
"""
Fetch io counters from psutil and transform it to
dicts with the additional attributes defaulted
"""
counters = psutil.net_io_counters(pernic=self.pernic)
res = {}
for name, io in counters.iteritems():
res[name] = io._asdict()
res[name].update({'tx_per_sec': 0, 'rx_per_sec': 0})
return res | python | def _get_net_io_counters(self):
counters = psutil.net_io_counters(pernic=self.pernic)
res = {}
for name, io in counters.iteritems():
res[name] = io._asdict()
res[name].update({'tx_per_sec': 0, 'rx_per_sec': 0})
return res | [
"def",
"_get_net_io_counters",
"(",
"self",
")",
":",
"counters",
"=",
"psutil",
".",
"net_io_counters",
"(",
"pernic",
"=",
"self",
".",
"pernic",
")",
"res",
"=",
"{",
"}",
"for",
"name",
",",
"io",
"in",
"counters",
".",
"iteritems",
"(",
")",
":",
... | Fetch io counters from psutil and transform it to
dicts with the additional attributes defaulted | [
"Fetch",
"io",
"counters",
"from",
"psutil",
"and",
"transform",
"it",
"to",
"dicts",
"with",
"the",
"additional",
"attributes",
"defaulted"
] | 4f1784742666045a3c33bd471dbe489b4f5c7699 | https://github.com/Jahaja/psdash/blob/4f1784742666045a3c33bd471dbe489b4f5c7699/psdash/net.py#L14-L26 |
232,406 | aio-libs/yarl | yarl/__init__.py | URL.build | def build(
cls,
*,
scheme="",
user="",
password=None,
host="",
port=None,
path="",
query=None,
query_string="",
fragment="",
encoded=False
):
"""Creates and returns a new URL"""
if not host and scheme:
raise ValueError('Can\'t build URL with "scheme" but without "host".')
if port and not host:
raise ValueError('Can\'t build URL with "port" but without "host".')
if query and query_string:
raise ValueError('Only one of "query" or "query_string" should be passed')
if path is None or query_string is None or fragment is None:
raise TypeError('NoneType is illegal for "path", "query_string" and '
'"fragment" args, use string values instead.')
if not user and not password and not host and not port:
netloc = ""
else:
netloc = cls._make_netloc(user, password, host, port, encode=not encoded)
if not encoded:
path = cls._PATH_QUOTER(path)
if netloc:
path = cls._normalize_path(path)
cls._validate_authority_uri_abs_path(host=host, path=path)
query_string = cls._QUERY_QUOTER(query_string)
fragment = cls._FRAGMENT_QUOTER(fragment)
url = cls(
SplitResult(scheme, netloc, path, query_string, fragment), encoded=True
)
if query:
return url.with_query(query)
else:
return url | python | def build(
cls,
*,
scheme="",
user="",
password=None,
host="",
port=None,
path="",
query=None,
query_string="",
fragment="",
encoded=False
):
if not host and scheme:
raise ValueError('Can\'t build URL with "scheme" but without "host".')
if port and not host:
raise ValueError('Can\'t build URL with "port" but without "host".')
if query and query_string:
raise ValueError('Only one of "query" or "query_string" should be passed')
if path is None or query_string is None or fragment is None:
raise TypeError('NoneType is illegal for "path", "query_string" and '
'"fragment" args, use string values instead.')
if not user and not password and not host and not port:
netloc = ""
else:
netloc = cls._make_netloc(user, password, host, port, encode=not encoded)
if not encoded:
path = cls._PATH_QUOTER(path)
if netloc:
path = cls._normalize_path(path)
cls._validate_authority_uri_abs_path(host=host, path=path)
query_string = cls._QUERY_QUOTER(query_string)
fragment = cls._FRAGMENT_QUOTER(fragment)
url = cls(
SplitResult(scheme, netloc, path, query_string, fragment), encoded=True
)
if query:
return url.with_query(query)
else:
return url | [
"def",
"build",
"(",
"cls",
",",
"*",
",",
"scheme",
"=",
"\"\"",
",",
"user",
"=",
"\"\"",
",",
"password",
"=",
"None",
",",
"host",
"=",
"\"\"",
",",
"port",
"=",
"None",
",",
"path",
"=",
"\"\"",
",",
"query",
"=",
"None",
",",
"query_string"... | Creates and returns a new URL | [
"Creates",
"and",
"returns",
"a",
"new",
"URL"
] | e47da02c00ad764e030ca7647a9565548c97d362 | https://github.com/aio-libs/yarl/blob/e47da02c00ad764e030ca7647a9565548c97d362/yarl/__init__.py#L185-L231 |
232,407 | aio-libs/yarl | yarl/__init__.py | URL.is_default_port | def is_default_port(self):
"""A check for default port.
Return True if port is default for specified scheme,
e.g. 'http://python.org' or 'http://python.org:80', False
otherwise.
"""
if self.port is None:
return False
default = DEFAULT_PORTS.get(self.scheme)
if default is None:
return False
return self.port == default | python | def is_default_port(self):
if self.port is None:
return False
default = DEFAULT_PORTS.get(self.scheme)
if default is None:
return False
return self.port == default | [
"def",
"is_default_port",
"(",
"self",
")",
":",
"if",
"self",
".",
"port",
"is",
"None",
":",
"return",
"False",
"default",
"=",
"DEFAULT_PORTS",
".",
"get",
"(",
"self",
".",
"scheme",
")",
"if",
"default",
"is",
"None",
":",
"return",
"False",
"retu... | A check for default port.
Return True if port is default for specified scheme,
e.g. 'http://python.org' or 'http://python.org:80', False
otherwise. | [
"A",
"check",
"for",
"default",
"port",
"."
] | e47da02c00ad764e030ca7647a9565548c97d362 | https://github.com/aio-libs/yarl/blob/e47da02c00ad764e030ca7647a9565548c97d362/yarl/__init__.py#L332-L345 |
232,408 | aio-libs/yarl | yarl/__init__.py | URL.origin | def origin(self):
"""Return an URL with scheme, host and port parts only.
user, password, path, query and fragment are removed.
"""
# TODO: add a keyword-only option for keeping user/pass maybe?
if not self.is_absolute():
raise ValueError("URL should be absolute")
if not self._val.scheme:
raise ValueError("URL should have scheme")
v = self._val
netloc = self._make_netloc(None, None, v.hostname, v.port, encode=False)
val = v._replace(netloc=netloc, path="", query="", fragment="")
return URL(val, encoded=True) | python | def origin(self):
# TODO: add a keyword-only option for keeping user/pass maybe?
if not self.is_absolute():
raise ValueError("URL should be absolute")
if not self._val.scheme:
raise ValueError("URL should have scheme")
v = self._val
netloc = self._make_netloc(None, None, v.hostname, v.port, encode=False)
val = v._replace(netloc=netloc, path="", query="", fragment="")
return URL(val, encoded=True) | [
"def",
"origin",
"(",
"self",
")",
":",
"# TODO: add a keyword-only option for keeping user/pass maybe?",
"if",
"not",
"self",
".",
"is_absolute",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"URL should be absolute\"",
")",
"if",
"not",
"self",
".",
"_val",
".",
... | Return an URL with scheme, host and port parts only.
user, password, path, query and fragment are removed. | [
"Return",
"an",
"URL",
"with",
"scheme",
"host",
"and",
"port",
"parts",
"only",
"."
] | e47da02c00ad764e030ca7647a9565548c97d362 | https://github.com/aio-libs/yarl/blob/e47da02c00ad764e030ca7647a9565548c97d362/yarl/__init__.py#L347-L361 |
232,409 | aio-libs/yarl | yarl/__init__.py | URL.relative | def relative(self):
"""Return a relative part of the URL.
scheme, user, password, host and port are removed.
"""
if not self.is_absolute():
raise ValueError("URL should be absolute")
val = self._val._replace(scheme="", netloc="")
return URL(val, encoded=True) | python | def relative(self):
if not self.is_absolute():
raise ValueError("URL should be absolute")
val = self._val._replace(scheme="", netloc="")
return URL(val, encoded=True) | [
"def",
"relative",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_absolute",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"URL should be absolute\"",
")",
"val",
"=",
"self",
".",
"_val",
".",
"_replace",
"(",
"scheme",
"=",
"\"\"",
",",
"netloc",
... | Return a relative part of the URL.
scheme, user, password, host and port are removed. | [
"Return",
"a",
"relative",
"part",
"of",
"the",
"URL",
"."
] | e47da02c00ad764e030ca7647a9565548c97d362 | https://github.com/aio-libs/yarl/blob/e47da02c00ad764e030ca7647a9565548c97d362/yarl/__init__.py#L363-L372 |
232,410 | aio-libs/yarl | yarl/__init__.py | URL.host | def host(self):
"""Decoded host part of URL.
None for relative URLs.
"""
raw = self.raw_host
if raw is None:
return None
if "%" in raw:
# Hack for scoped IPv6 addresses like
# fe80::2%Проверка
# presence of '%' sign means only IPv6 address, so idna is useless.
return raw
try:
return idna.decode(raw.encode("ascii"))
except UnicodeError: # e.g. '::1'
return raw.encode("ascii").decode("idna") | python | def host(self):
raw = self.raw_host
if raw is None:
return None
if "%" in raw:
# Hack for scoped IPv6 addresses like
# fe80::2%Проверка
# presence of '%' sign means only IPv6 address, so idna is useless.
return raw
try:
return idna.decode(raw.encode("ascii"))
except UnicodeError: # e.g. '::1'
return raw.encode("ascii").decode("idna") | [
"def",
"host",
"(",
"self",
")",
":",
"raw",
"=",
"self",
".",
"raw_host",
"if",
"raw",
"is",
"None",
":",
"return",
"None",
"if",
"\"%\"",
"in",
"raw",
":",
"# Hack for scoped IPv6 addresses like",
"# fe80::2%Проверка",
"# presence of '%' sign means only IPv6 addre... | Decoded host part of URL.
None for relative URLs. | [
"Decoded",
"host",
"part",
"of",
"URL",
"."
] | e47da02c00ad764e030ca7647a9565548c97d362 | https://github.com/aio-libs/yarl/blob/e47da02c00ad764e030ca7647a9565548c97d362/yarl/__init__.py#L435-L453 |
232,411 | aio-libs/yarl | yarl/__init__.py | URL.port | def port(self):
"""Port part of URL, with scheme-based fallback.
None for relative URLs or URLs without explicit port and
scheme without default port substitution.
"""
return self._val.port or DEFAULT_PORTS.get(self._val.scheme) | python | def port(self):
return self._val.port or DEFAULT_PORTS.get(self._val.scheme) | [
"def",
"port",
"(",
"self",
")",
":",
"return",
"self",
".",
"_val",
".",
"port",
"or",
"DEFAULT_PORTS",
".",
"get",
"(",
"self",
".",
"_val",
".",
"scheme",
")"
] | Port part of URL, with scheme-based fallback.
None for relative URLs or URLs without explicit port and
scheme without default port substitution. | [
"Port",
"part",
"of",
"URL",
"with",
"scheme",
"-",
"based",
"fallback",
"."
] | e47da02c00ad764e030ca7647a9565548c97d362 | https://github.com/aio-libs/yarl/blob/e47da02c00ad764e030ca7647a9565548c97d362/yarl/__init__.py#L456-L463 |
232,412 | aio-libs/yarl | yarl/__init__.py | URL.raw_path | def raw_path(self):
"""Encoded path of URL.
/ for absolute URLs without path part.
"""
ret = self._val.path
if not ret and self.is_absolute():
ret = "/"
return ret | python | def raw_path(self):
ret = self._val.path
if not ret and self.is_absolute():
ret = "/"
return ret | [
"def",
"raw_path",
"(",
"self",
")",
":",
"ret",
"=",
"self",
".",
"_val",
".",
"path",
"if",
"not",
"ret",
"and",
"self",
".",
"is_absolute",
"(",
")",
":",
"ret",
"=",
"\"/\"",
"return",
"ret"
] | Encoded path of URL.
/ for absolute URLs without path part. | [
"Encoded",
"path",
"of",
"URL",
"."
] | e47da02c00ad764e030ca7647a9565548c97d362 | https://github.com/aio-libs/yarl/blob/e47da02c00ad764e030ca7647a9565548c97d362/yarl/__init__.py#L475-L484 |
232,413 | aio-libs/yarl | yarl/__init__.py | URL.query | def query(self):
"""A MultiDictProxy representing parsed query parameters in decoded
representation.
Empty value if URL has no query part.
"""
ret = MultiDict(parse_qsl(self.raw_query_string, keep_blank_values=True))
return MultiDictProxy(ret) | python | def query(self):
ret = MultiDict(parse_qsl(self.raw_query_string, keep_blank_values=True))
return MultiDictProxy(ret) | [
"def",
"query",
"(",
"self",
")",
":",
"ret",
"=",
"MultiDict",
"(",
"parse_qsl",
"(",
"self",
".",
"raw_query_string",
",",
"keep_blank_values",
"=",
"True",
")",
")",
"return",
"MultiDictProxy",
"(",
"ret",
")"
] | A MultiDictProxy representing parsed query parameters in decoded
representation.
Empty value if URL has no query part. | [
"A",
"MultiDictProxy",
"representing",
"parsed",
"query",
"parameters",
"in",
"decoded",
"representation",
"."
] | e47da02c00ad764e030ca7647a9565548c97d362 | https://github.com/aio-libs/yarl/blob/e47da02c00ad764e030ca7647a9565548c97d362/yarl/__init__.py#L496-L504 |
232,414 | aio-libs/yarl | yarl/__init__.py | URL.path_qs | def path_qs(self):
"""Decoded path of URL with query."""
if not self.query_string:
return self.path
return "{}?{}".format(self.path, self.query_string) | python | def path_qs(self):
if not self.query_string:
return self.path
return "{}?{}".format(self.path, self.query_string) | [
"def",
"path_qs",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"query_string",
":",
"return",
"self",
".",
"path",
"return",
"\"{}?{}\"",
".",
"format",
"(",
"self",
".",
"path",
",",
"self",
".",
"query_string",
")"
] | Decoded path of URL with query. | [
"Decoded",
"path",
"of",
"URL",
"with",
"query",
"."
] | e47da02c00ad764e030ca7647a9565548c97d362 | https://github.com/aio-libs/yarl/blob/e47da02c00ad764e030ca7647a9565548c97d362/yarl/__init__.py#L525-L529 |
232,415 | aio-libs/yarl | yarl/__init__.py | URL.raw_path_qs | def raw_path_qs(self):
"""Encoded path of URL with query."""
if not self.raw_query_string:
return self.raw_path
return "{}?{}".format(self.raw_path, self.raw_query_string) | python | def raw_path_qs(self):
if not self.raw_query_string:
return self.raw_path
return "{}?{}".format(self.raw_path, self.raw_query_string) | [
"def",
"raw_path_qs",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"raw_query_string",
":",
"return",
"self",
".",
"raw_path",
"return",
"\"{}?{}\"",
".",
"format",
"(",
"self",
".",
"raw_path",
",",
"self",
".",
"raw_query_string",
")"
] | Encoded path of URL with query. | [
"Encoded",
"path",
"of",
"URL",
"with",
"query",
"."
] | e47da02c00ad764e030ca7647a9565548c97d362 | https://github.com/aio-libs/yarl/blob/e47da02c00ad764e030ca7647a9565548c97d362/yarl/__init__.py#L532-L536 |
232,416 | aio-libs/yarl | yarl/__init__.py | URL.parent | def parent(self):
"""A new URL with last part of path removed and cleaned up query and
fragment.
"""
path = self.raw_path
if not path or path == "/":
if self.raw_fragment or self.raw_query_string:
return URL(self._val._replace(query="", fragment=""), encoded=True)
return self
parts = path.split("/")
val = self._val._replace(path="/".join(parts[:-1]), query="", fragment="")
return URL(val, encoded=True) | python | def parent(self):
path = self.raw_path
if not path or path == "/":
if self.raw_fragment or self.raw_query_string:
return URL(self._val._replace(query="", fragment=""), encoded=True)
return self
parts = path.split("/")
val = self._val._replace(path="/".join(parts[:-1]), query="", fragment="")
return URL(val, encoded=True) | [
"def",
"parent",
"(",
"self",
")",
":",
"path",
"=",
"self",
".",
"raw_path",
"if",
"not",
"path",
"or",
"path",
"==",
"\"/\"",
":",
"if",
"self",
".",
"raw_fragment",
"or",
"self",
".",
"raw_query_string",
":",
"return",
"URL",
"(",
"self",
".",
"_v... | A new URL with last part of path removed and cleaned up query and
fragment. | [
"A",
"new",
"URL",
"with",
"last",
"part",
"of",
"path",
"removed",
"and",
"cleaned",
"up",
"query",
"and",
"fragment",
"."
] | e47da02c00ad764e030ca7647a9565548c97d362 | https://github.com/aio-libs/yarl/blob/e47da02c00ad764e030ca7647a9565548c97d362/yarl/__init__.py#L586-L598 |
232,417 | aio-libs/yarl | yarl/__init__.py | URL.raw_name | def raw_name(self):
"""The last part of raw_parts."""
parts = self.raw_parts
if self.is_absolute():
parts = parts[1:]
if not parts:
return ""
else:
return parts[-1]
else:
return parts[-1] | python | def raw_name(self):
parts = self.raw_parts
if self.is_absolute():
parts = parts[1:]
if not parts:
return ""
else:
return parts[-1]
else:
return parts[-1] | [
"def",
"raw_name",
"(",
"self",
")",
":",
"parts",
"=",
"self",
".",
"raw_parts",
"if",
"self",
".",
"is_absolute",
"(",
")",
":",
"parts",
"=",
"parts",
"[",
"1",
":",
"]",
"if",
"not",
"parts",
":",
"return",
"\"\"",
"else",
":",
"return",
"parts... | The last part of raw_parts. | [
"The",
"last",
"part",
"of",
"raw_parts",
"."
] | e47da02c00ad764e030ca7647a9565548c97d362 | https://github.com/aio-libs/yarl/blob/e47da02c00ad764e030ca7647a9565548c97d362/yarl/__init__.py#L601-L611 |
232,418 | aio-libs/yarl | yarl/__init__.py | URL._validate_authority_uri_abs_path | def _validate_authority_uri_abs_path(host, path):
"""Ensure that path in URL with authority starts with a leading slash.
Raise ValueError if not.
"""
if len(host) > 0 and len(path) > 0 and not path.startswith("/"):
raise ValueError(
"Path in a URL with authority " "should start with a slash ('/') if set"
) | python | def _validate_authority_uri_abs_path(host, path):
if len(host) > 0 and len(path) > 0 and not path.startswith("/"):
raise ValueError(
"Path in a URL with authority " "should start with a slash ('/') if set"
) | [
"def",
"_validate_authority_uri_abs_path",
"(",
"host",
",",
"path",
")",
":",
"if",
"len",
"(",
"host",
")",
">",
"0",
"and",
"len",
"(",
"path",
")",
">",
"0",
"and",
"not",
"path",
".",
"startswith",
"(",
"\"/\"",
")",
":",
"raise",
"ValueError",
... | Ensure that path in URL with authority starts with a leading slash.
Raise ValueError if not. | [
"Ensure",
"that",
"path",
"in",
"URL",
"with",
"authority",
"starts",
"with",
"a",
"leading",
"slash",
"."
] | e47da02c00ad764e030ca7647a9565548c97d362 | https://github.com/aio-libs/yarl/blob/e47da02c00ad764e030ca7647a9565548c97d362/yarl/__init__.py#L619-L627 |
232,419 | aio-libs/yarl | yarl/__init__.py | URL.with_scheme | def with_scheme(self, scheme):
"""Return a new URL with scheme replaced."""
# N.B. doesn't cleanup query/fragment
if not isinstance(scheme, str):
raise TypeError("Invalid scheme type")
if not self.is_absolute():
raise ValueError("scheme replacement is not allowed " "for relative URLs")
return URL(self._val._replace(scheme=scheme.lower()), encoded=True) | python | def with_scheme(self, scheme):
# N.B. doesn't cleanup query/fragment
if not isinstance(scheme, str):
raise TypeError("Invalid scheme type")
if not self.is_absolute():
raise ValueError("scheme replacement is not allowed " "for relative URLs")
return URL(self._val._replace(scheme=scheme.lower()), encoded=True) | [
"def",
"with_scheme",
"(",
"self",
",",
"scheme",
")",
":",
"# N.B. doesn't cleanup query/fragment",
"if",
"not",
"isinstance",
"(",
"scheme",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"Invalid scheme type\"",
")",
"if",
"not",
"self",
".",
"is_absolute... | Return a new URL with scheme replaced. | [
"Return",
"a",
"new",
"URL",
"with",
"scheme",
"replaced",
"."
] | e47da02c00ad764e030ca7647a9565548c97d362 | https://github.com/aio-libs/yarl/blob/e47da02c00ad764e030ca7647a9565548c97d362/yarl/__init__.py#L699-L706 |
232,420 | aio-libs/yarl | yarl/__init__.py | URL.with_user | def with_user(self, user):
"""Return a new URL with user replaced.
Autoencode user if needed.
Clear user/password if user is None.
"""
# N.B. doesn't cleanup query/fragment
val = self._val
if user is None:
password = None
elif isinstance(user, str):
user = self._QUOTER(user)
password = val.password
else:
raise TypeError("Invalid user type")
if not self.is_absolute():
raise ValueError("user replacement is not allowed " "for relative URLs")
return URL(
self._val._replace(
netloc=self._make_netloc(
user, password, val.hostname, val.port, encode=False
)
),
encoded=True,
) | python | def with_user(self, user):
# N.B. doesn't cleanup query/fragment
val = self._val
if user is None:
password = None
elif isinstance(user, str):
user = self._QUOTER(user)
password = val.password
else:
raise TypeError("Invalid user type")
if not self.is_absolute():
raise ValueError("user replacement is not allowed " "for relative URLs")
return URL(
self._val._replace(
netloc=self._make_netloc(
user, password, val.hostname, val.port, encode=False
)
),
encoded=True,
) | [
"def",
"with_user",
"(",
"self",
",",
"user",
")",
":",
"# N.B. doesn't cleanup query/fragment",
"val",
"=",
"self",
".",
"_val",
"if",
"user",
"is",
"None",
":",
"password",
"=",
"None",
"elif",
"isinstance",
"(",
"user",
",",
"str",
")",
":",
"user",
"... | Return a new URL with user replaced.
Autoencode user if needed.
Clear user/password if user is None. | [
"Return",
"a",
"new",
"URL",
"with",
"user",
"replaced",
"."
] | e47da02c00ad764e030ca7647a9565548c97d362 | https://github.com/aio-libs/yarl/blob/e47da02c00ad764e030ca7647a9565548c97d362/yarl/__init__.py#L708-L734 |
232,421 | aio-libs/yarl | yarl/__init__.py | URL.with_host | def with_host(self, host):
"""Return a new URL with host replaced.
Autoencode host if needed.
Changing host for relative URLs is not allowed, use .join()
instead.
"""
# N.B. doesn't cleanup query/fragment
if not isinstance(host, str):
raise TypeError("Invalid host type")
if not self.is_absolute():
raise ValueError("host replacement is not allowed " "for relative URLs")
if not host:
raise ValueError("host removing is not allowed")
host = self._encode_host(host)
val = self._val
return URL(
self._val._replace(
netloc=self._make_netloc(
val.username, val.password, host, val.port, encode=False
)
),
encoded=True,
) | python | def with_host(self, host):
# N.B. doesn't cleanup query/fragment
if not isinstance(host, str):
raise TypeError("Invalid host type")
if not self.is_absolute():
raise ValueError("host replacement is not allowed " "for relative URLs")
if not host:
raise ValueError("host removing is not allowed")
host = self._encode_host(host)
val = self._val
return URL(
self._val._replace(
netloc=self._make_netloc(
val.username, val.password, host, val.port, encode=False
)
),
encoded=True,
) | [
"def",
"with_host",
"(",
"self",
",",
"host",
")",
":",
"# N.B. doesn't cleanup query/fragment",
"if",
"not",
"isinstance",
"(",
"host",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"Invalid host type\"",
")",
"if",
"not",
"self",
".",
"is_absolute",
"("... | Return a new URL with host replaced.
Autoencode host if needed.
Changing host for relative URLs is not allowed, use .join()
instead. | [
"Return",
"a",
"new",
"URL",
"with",
"host",
"replaced",
"."
] | e47da02c00ad764e030ca7647a9565548c97d362 | https://github.com/aio-libs/yarl/blob/e47da02c00ad764e030ca7647a9565548c97d362/yarl/__init__.py#L763-L788 |
232,422 | aio-libs/yarl | yarl/__init__.py | URL.with_port | def with_port(self, port):
"""Return a new URL with port replaced.
Clear port to default if None is passed.
"""
# N.B. doesn't cleanup query/fragment
if port is not None and not isinstance(port, int):
raise TypeError("port should be int or None, got {}".format(type(port)))
if not self.is_absolute():
raise ValueError("port replacement is not allowed " "for relative URLs")
val = self._val
return URL(
self._val._replace(
netloc=self._make_netloc(
val.username, val.password, val.hostname, port, encode=False
)
),
encoded=True,
) | python | def with_port(self, port):
# N.B. doesn't cleanup query/fragment
if port is not None and not isinstance(port, int):
raise TypeError("port should be int or None, got {}".format(type(port)))
if not self.is_absolute():
raise ValueError("port replacement is not allowed " "for relative URLs")
val = self._val
return URL(
self._val._replace(
netloc=self._make_netloc(
val.username, val.password, val.hostname, port, encode=False
)
),
encoded=True,
) | [
"def",
"with_port",
"(",
"self",
",",
"port",
")",
":",
"# N.B. doesn't cleanup query/fragment",
"if",
"port",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"port",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"port should be int or None, got {}\"",
... | Return a new URL with port replaced.
Clear port to default if None is passed. | [
"Return",
"a",
"new",
"URL",
"with",
"port",
"replaced",
"."
] | e47da02c00ad764e030ca7647a9565548c97d362 | https://github.com/aio-libs/yarl/blob/e47da02c00ad764e030ca7647a9565548c97d362/yarl/__init__.py#L790-L809 |
232,423 | aio-libs/yarl | yarl/__init__.py | URL.with_path | def with_path(self, path, *, encoded=False):
"""Return a new URL with path replaced."""
if not encoded:
path = self._PATH_QUOTER(path)
if self.is_absolute():
path = self._normalize_path(path)
if len(path) > 0 and path[0] != "/":
path = "/" + path
return URL(self._val._replace(path=path, query="", fragment=""), encoded=True) | python | def with_path(self, path, *, encoded=False):
if not encoded:
path = self._PATH_QUOTER(path)
if self.is_absolute():
path = self._normalize_path(path)
if len(path) > 0 and path[0] != "/":
path = "/" + path
return URL(self._val._replace(path=path, query="", fragment=""), encoded=True) | [
"def",
"with_path",
"(",
"self",
",",
"path",
",",
"*",
",",
"encoded",
"=",
"False",
")",
":",
"if",
"not",
"encoded",
":",
"path",
"=",
"self",
".",
"_PATH_QUOTER",
"(",
"path",
")",
"if",
"self",
".",
"is_absolute",
"(",
")",
":",
"path",
"=",
... | Return a new URL with path replaced. | [
"Return",
"a",
"new",
"URL",
"with",
"path",
"replaced",
"."
] | e47da02c00ad764e030ca7647a9565548c97d362 | https://github.com/aio-libs/yarl/blob/e47da02c00ad764e030ca7647a9565548c97d362/yarl/__init__.py#L811-L819 |
232,424 | aio-libs/yarl | yarl/__init__.py | URL.with_query | def with_query(self, *args, **kwargs):
"""Return a new URL with query part replaced.
Accepts any Mapping (e.g. dict, multidict.MultiDict instances)
or str, autoencode the argument if needed.
A sequence of (key, value) pairs is supported as well.
It also can take an arbitrary number of keyword arguments.
Clear query if None is passed.
"""
# N.B. doesn't cleanup query/fragment
new_query = self._get_str_query(*args, **kwargs)
return URL(
self._val._replace(path=self._val.path, query=new_query), encoded=True
) | python | def with_query(self, *args, **kwargs):
# N.B. doesn't cleanup query/fragment
new_query = self._get_str_query(*args, **kwargs)
return URL(
self._val._replace(path=self._val.path, query=new_query), encoded=True
) | [
"def",
"with_query",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# N.B. doesn't cleanup query/fragment",
"new_query",
"=",
"self",
".",
"_get_str_query",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"URL",
"(",
"self",
... | Return a new URL with query part replaced.
Accepts any Mapping (e.g. dict, multidict.MultiDict instances)
or str, autoencode the argument if needed.
A sequence of (key, value) pairs is supported as well.
It also can take an arbitrary number of keyword arguments.
Clear query if None is passed. | [
"Return",
"a",
"new",
"URL",
"with",
"query",
"part",
"replaced",
"."
] | e47da02c00ad764e030ca7647a9565548c97d362 | https://github.com/aio-libs/yarl/blob/e47da02c00ad764e030ca7647a9565548c97d362/yarl/__init__.py#L873-L891 |
232,425 | aio-libs/yarl | yarl/__init__.py | URL.update_query | def update_query(self, *args, **kwargs):
"""Return a new URL with query part updated."""
s = self._get_str_query(*args, **kwargs)
new_query = MultiDict(parse_qsl(s, keep_blank_values=True))
query = MultiDict(self.query)
query.update(new_query)
return URL(self._val._replace(query=self._get_str_query(query)), encoded=True) | python | def update_query(self, *args, **kwargs):
s = self._get_str_query(*args, **kwargs)
new_query = MultiDict(parse_qsl(s, keep_blank_values=True))
query = MultiDict(self.query)
query.update(new_query)
return URL(self._val._replace(query=self._get_str_query(query)), encoded=True) | [
"def",
"update_query",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"s",
"=",
"self",
".",
"_get_str_query",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"new_query",
"=",
"MultiDict",
"(",
"parse_qsl",
"(",
"s",
",",
"keep_... | Return a new URL with query part updated. | [
"Return",
"a",
"new",
"URL",
"with",
"query",
"part",
"updated",
"."
] | e47da02c00ad764e030ca7647a9565548c97d362 | https://github.com/aio-libs/yarl/blob/e47da02c00ad764e030ca7647a9565548c97d362/yarl/__init__.py#L893-L900 |
232,426 | aio-libs/yarl | yarl/__init__.py | URL.with_fragment | def with_fragment(self, fragment):
"""Return a new URL with fragment replaced.
Autoencode fragment if needed.
Clear fragment to default if None is passed.
"""
# N.B. doesn't cleanup query/fragment
if fragment is None:
fragment = ""
elif not isinstance(fragment, str):
raise TypeError("Invalid fragment type")
return URL(
self._val._replace(fragment=self._FRAGMENT_QUOTER(fragment)), encoded=True
) | python | def with_fragment(self, fragment):
# N.B. doesn't cleanup query/fragment
if fragment is None:
fragment = ""
elif not isinstance(fragment, str):
raise TypeError("Invalid fragment type")
return URL(
self._val._replace(fragment=self._FRAGMENT_QUOTER(fragment)), encoded=True
) | [
"def",
"with_fragment",
"(",
"self",
",",
"fragment",
")",
":",
"# N.B. doesn't cleanup query/fragment",
"if",
"fragment",
"is",
"None",
":",
"fragment",
"=",
"\"\"",
"elif",
"not",
"isinstance",
"(",
"fragment",
",",
"str",
")",
":",
"raise",
"TypeError",
"("... | Return a new URL with fragment replaced.
Autoencode fragment if needed.
Clear fragment to default if None is passed. | [
"Return",
"a",
"new",
"URL",
"with",
"fragment",
"replaced",
"."
] | e47da02c00ad764e030ca7647a9565548c97d362 | https://github.com/aio-libs/yarl/blob/e47da02c00ad764e030ca7647a9565548c97d362/yarl/__init__.py#L902-L917 |
232,427 | aio-libs/yarl | yarl/__init__.py | URL.human_repr | def human_repr(self):
"""Return decoded human readable string for URL representation."""
return urlunsplit(
SplitResult(
self.scheme,
self._make_netloc(
self.user, self.password, self.host, self._val.port, encode=False
),
self.path,
self.query_string,
self.fragment,
)
) | python | def human_repr(self):
return urlunsplit(
SplitResult(
self.scheme,
self._make_netloc(
self.user, self.password, self.host, self._val.port, encode=False
),
self.path,
self.query_string,
self.fragment,
)
) | [
"def",
"human_repr",
"(",
"self",
")",
":",
"return",
"urlunsplit",
"(",
"SplitResult",
"(",
"self",
".",
"scheme",
",",
"self",
".",
"_make_netloc",
"(",
"self",
".",
"user",
",",
"self",
".",
"password",
",",
"self",
".",
"host",
",",
"self",
".",
... | Return decoded human readable string for URL representation. | [
"Return",
"decoded",
"human",
"readable",
"string",
"for",
"URL",
"representation",
"."
] | e47da02c00ad764e030ca7647a9565548c97d362 | https://github.com/aio-libs/yarl/blob/e47da02c00ad764e030ca7647a9565548c97d362/yarl/__init__.py#L968-L981 |
232,428 | ulfalizer/Kconfiglib | examples/list_undefined.py | all_arch_srcarch_kconfigs | def all_arch_srcarch_kconfigs():
"""
Generates Kconfig instances for all the architectures in the kernel
"""
os.environ["srctree"] = "."
os.environ["HOSTCC"] = "gcc"
os.environ["HOSTCXX"] = "g++"
os.environ["CC"] = "gcc"
os.environ["LD"] = "ld"
for arch, srcarch in all_arch_srcarch_pairs():
print(" Processing " + arch)
os.environ["ARCH"] = arch
os.environ["SRCARCH"] = srcarch
# um (User Mode Linux) uses a different base Kconfig file
yield Kconfig("Kconfig" if arch != "um" else "arch/x86/um/Kconfig",
warn=False) | python | def all_arch_srcarch_kconfigs():
os.environ["srctree"] = "."
os.environ["HOSTCC"] = "gcc"
os.environ["HOSTCXX"] = "g++"
os.environ["CC"] = "gcc"
os.environ["LD"] = "ld"
for arch, srcarch in all_arch_srcarch_pairs():
print(" Processing " + arch)
os.environ["ARCH"] = arch
os.environ["SRCARCH"] = srcarch
# um (User Mode Linux) uses a different base Kconfig file
yield Kconfig("Kconfig" if arch != "um" else "arch/x86/um/Kconfig",
warn=False) | [
"def",
"all_arch_srcarch_kconfigs",
"(",
")",
":",
"os",
".",
"environ",
"[",
"\"srctree\"",
"]",
"=",
"\".\"",
"os",
".",
"environ",
"[",
"\"HOSTCC\"",
"]",
"=",
"\"gcc\"",
"os",
".",
"environ",
"[",
"\"HOSTCXX\"",
"]",
"=",
"\"g++\"",
"os",
".",
"envir... | Generates Kconfig instances for all the architectures in the kernel | [
"Generates",
"Kconfig",
"instances",
"for",
"all",
"the",
"architectures",
"in",
"the",
"kernel"
] | 9fe13c03de16c341cd7ed40167216207b821ea50 | https://github.com/ulfalizer/Kconfiglib/blob/9fe13c03de16c341cd7ed40167216207b821ea50/examples/list_undefined.py#L76-L95 |
232,429 | ulfalizer/Kconfiglib | menuconfig.py | menuconfig | def menuconfig(kconf):
"""
Launches the configuration interface, returning after the user exits.
kconf:
Kconfig instance to be configured
"""
global _kconf
global _conf_filename
global _conf_changed
global _minconf_filename
global _show_all
_kconf = kconf
# Load existing configuration and set _conf_changed True if it is outdated
_conf_changed = _load_config()
# Filename to save configuration to
_conf_filename = standard_config_filename()
# Filename to save minimal configuration to
_minconf_filename = "defconfig"
# Any visible items in the top menu?
_show_all = False
if not _shown_nodes(kconf.top_node):
# Nothing visible. Start in show-all mode and try again.
_show_all = True
if not _shown_nodes(kconf.top_node):
# Give up. The implementation relies on always having a selected
# node.
print("Empty configuration -- nothing to configure.\n"
"Check that environment variables are set properly.")
return
# Disable warnings. They get mangled in curses mode, and we deal with
# errors ourselves.
kconf.disable_warnings()
# Make curses use the locale settings specified in the environment
locale.setlocale(locale.LC_ALL, "")
# Try to fix Unicode issues on systems with bad defaults
if _CONVERT_C_LC_CTYPE_TO_UTF8:
_convert_c_lc_ctype_to_utf8()
# Get rid of the delay between pressing ESC and jumping to the parent menu,
# unless the user has set ESCDELAY (see ncurses(3)). This makes the UI much
# smoother to work with.
#
# Note: This is strictly pretty iffy, since escape codes for e.g. cursor
# keys start with ESC, but I've never seen it cause problems in practice
# (probably because it's unlikely that the escape code for a key would get
# split up across read()s, at least with a terminal emulator). Please
# report if you run into issues. Some suitable small default value could be
# used here instead in that case. Maybe it's silly to not put in the
# smallest imperceptible delay here already, though I don't like guessing.
#
# (From a quick glance at the ncurses source code, ESCDELAY might only be
# relevant for mouse events there, so maybe escapes are assumed to arrive
# in one piece already...)
os.environ.setdefault("ESCDELAY", "0")
# Enter curses mode. _menuconfig() returns a string to print on exit, after
# curses has been de-initialized.
print(curses.wrapper(_menuconfig)) | python | def menuconfig(kconf):
global _kconf
global _conf_filename
global _conf_changed
global _minconf_filename
global _show_all
_kconf = kconf
# Load existing configuration and set _conf_changed True if it is outdated
_conf_changed = _load_config()
# Filename to save configuration to
_conf_filename = standard_config_filename()
# Filename to save minimal configuration to
_minconf_filename = "defconfig"
# Any visible items in the top menu?
_show_all = False
if not _shown_nodes(kconf.top_node):
# Nothing visible. Start in show-all mode and try again.
_show_all = True
if not _shown_nodes(kconf.top_node):
# Give up. The implementation relies on always having a selected
# node.
print("Empty configuration -- nothing to configure.\n"
"Check that environment variables are set properly.")
return
# Disable warnings. They get mangled in curses mode, and we deal with
# errors ourselves.
kconf.disable_warnings()
# Make curses use the locale settings specified in the environment
locale.setlocale(locale.LC_ALL, "")
# Try to fix Unicode issues on systems with bad defaults
if _CONVERT_C_LC_CTYPE_TO_UTF8:
_convert_c_lc_ctype_to_utf8()
# Get rid of the delay between pressing ESC and jumping to the parent menu,
# unless the user has set ESCDELAY (see ncurses(3)). This makes the UI much
# smoother to work with.
#
# Note: This is strictly pretty iffy, since escape codes for e.g. cursor
# keys start with ESC, but I've never seen it cause problems in practice
# (probably because it's unlikely that the escape code for a key would get
# split up across read()s, at least with a terminal emulator). Please
# report if you run into issues. Some suitable small default value could be
# used here instead in that case. Maybe it's silly to not put in the
# smallest imperceptible delay here already, though I don't like guessing.
#
# (From a quick glance at the ncurses source code, ESCDELAY might only be
# relevant for mouse events there, so maybe escapes are assumed to arrive
# in one piece already...)
os.environ.setdefault("ESCDELAY", "0")
# Enter curses mode. _menuconfig() returns a string to print on exit, after
# curses has been de-initialized.
print(curses.wrapper(_menuconfig)) | [
"def",
"menuconfig",
"(",
"kconf",
")",
":",
"global",
"_kconf",
"global",
"_conf_filename",
"global",
"_conf_changed",
"global",
"_minconf_filename",
"global",
"_show_all",
"_kconf",
"=",
"kconf",
"# Load existing configuration and set _conf_changed True if it is outdated",
... | Launches the configuration interface, returning after the user exits.
kconf:
Kconfig instance to be configured | [
"Launches",
"the",
"configuration",
"interface",
"returning",
"after",
"the",
"user",
"exits",
"."
] | 9fe13c03de16c341cd7ed40167216207b821ea50 | https://github.com/ulfalizer/Kconfiglib/blob/9fe13c03de16c341cd7ed40167216207b821ea50/menuconfig.py#L636-L702 |
232,430 | ulfalizer/Kconfiglib | examples/print_config_tree.py | print_menuconfig_nodes | def print_menuconfig_nodes(node, indent):
"""
Prints a tree with all the menu entries rooted at 'node'. Child menu
entries are indented.
"""
while node:
string = node_str(node)
if string:
indent_print(string, indent)
if node.list:
print_menuconfig_nodes(node.list, indent + 8)
node = node.next | python | def print_menuconfig_nodes(node, indent):
while node:
string = node_str(node)
if string:
indent_print(string, indent)
if node.list:
print_menuconfig_nodes(node.list, indent + 8)
node = node.next | [
"def",
"print_menuconfig_nodes",
"(",
"node",
",",
"indent",
")",
":",
"while",
"node",
":",
"string",
"=",
"node_str",
"(",
"node",
")",
"if",
"string",
":",
"indent_print",
"(",
"string",
",",
"indent",
")",
"if",
"node",
".",
"list",
":",
"print_menuc... | Prints a tree with all the menu entries rooted at 'node'. Child menu
entries are indented. | [
"Prints",
"a",
"tree",
"with",
"all",
"the",
"menu",
"entries",
"rooted",
"at",
"node",
".",
"Child",
"menu",
"entries",
"are",
"indented",
"."
] | 9fe13c03de16c341cd7ed40167216207b821ea50 | https://github.com/ulfalizer/Kconfiglib/blob/9fe13c03de16c341cd7ed40167216207b821ea50/examples/print_config_tree.py#L157-L170 |
232,431 | ulfalizer/Kconfiglib | examples/print_config_tree.py | print_menuconfig | def print_menuconfig(kconf):
"""
Prints all menu entries for the configuration.
"""
# Print the expanded mainmenu text at the top. This is the same as
# kconf.top_node.prompt[0], but with variable references expanded.
print("\n======== {} ========\n".format(kconf.mainmenu_text))
print_menuconfig_nodes(kconf.top_node.list, 0)
print("") | python | def print_menuconfig(kconf):
# Print the expanded mainmenu text at the top. This is the same as
# kconf.top_node.prompt[0], but with variable references expanded.
print("\n======== {} ========\n".format(kconf.mainmenu_text))
print_menuconfig_nodes(kconf.top_node.list, 0)
print("") | [
"def",
"print_menuconfig",
"(",
"kconf",
")",
":",
"# Print the expanded mainmenu text at the top. This is the same as",
"# kconf.top_node.prompt[0], but with variable references expanded.",
"print",
"(",
"\"\\n======== {} ========\\n\"",
".",
"format",
"(",
"kconf",
".",
"mainmenu_t... | Prints all menu entries for the configuration. | [
"Prints",
"all",
"menu",
"entries",
"for",
"the",
"configuration",
"."
] | 9fe13c03de16c341cd7ed40167216207b821ea50 | https://github.com/ulfalizer/Kconfiglib/blob/9fe13c03de16c341cd7ed40167216207b821ea50/examples/print_config_tree.py#L173-L182 |
232,432 | ulfalizer/Kconfiglib | kconfiglib.py | expr_str | def expr_str(expr, sc_expr_str_fn=standard_sc_expr_str):
"""
Returns the string representation of the expression 'expr', as in a Kconfig
file.
Passing subexpressions of expressions to this function works as expected.
sc_expr_str_fn (default: standard_sc_expr_str):
This function is called for every symbol/choice (hence "sc") appearing in
the expression, with the symbol/choice as the argument. It is expected to
return a string to be used for the symbol/choice.
This can be used e.g. to turn symbols/choices into links when generating
documentation, or for printing the value of each symbol/choice after it.
Note that quoted values are represented as constants symbols
(Symbol.is_constant == True).
"""
if expr.__class__ is not tuple:
return sc_expr_str_fn(expr)
if expr[0] is AND:
return "{} && {}".format(_parenthesize(expr[1], OR, sc_expr_str_fn),
_parenthesize(expr[2], OR, sc_expr_str_fn))
if expr[0] is OR:
# This turns A && B || C && D into "(A && B) || (C && D)", which is
# redundant, but more readable
return "{} || {}".format(_parenthesize(expr[1], AND, sc_expr_str_fn),
_parenthesize(expr[2], AND, sc_expr_str_fn))
if expr[0] is NOT:
if expr[1].__class__ is tuple:
return "!({})".format(expr_str(expr[1], sc_expr_str_fn))
return "!" + sc_expr_str_fn(expr[1]) # Symbol
# Relation
#
# Relation operands are always symbols (quoted strings are constant
# symbols)
return "{} {} {}".format(sc_expr_str_fn(expr[1]), _REL_TO_STR[expr[0]],
sc_expr_str_fn(expr[2])) | python | def expr_str(expr, sc_expr_str_fn=standard_sc_expr_str):
if expr.__class__ is not tuple:
return sc_expr_str_fn(expr)
if expr[0] is AND:
return "{} && {}".format(_parenthesize(expr[1], OR, sc_expr_str_fn),
_parenthesize(expr[2], OR, sc_expr_str_fn))
if expr[0] is OR:
# This turns A && B || C && D into "(A && B) || (C && D)", which is
# redundant, but more readable
return "{} || {}".format(_parenthesize(expr[1], AND, sc_expr_str_fn),
_parenthesize(expr[2], AND, sc_expr_str_fn))
if expr[0] is NOT:
if expr[1].__class__ is tuple:
return "!({})".format(expr_str(expr[1], sc_expr_str_fn))
return "!" + sc_expr_str_fn(expr[1]) # Symbol
# Relation
#
# Relation operands are always symbols (quoted strings are constant
# symbols)
return "{} {} {}".format(sc_expr_str_fn(expr[1]), _REL_TO_STR[expr[0]],
sc_expr_str_fn(expr[2])) | [
"def",
"expr_str",
"(",
"expr",
",",
"sc_expr_str_fn",
"=",
"standard_sc_expr_str",
")",
":",
"if",
"expr",
".",
"__class__",
"is",
"not",
"tuple",
":",
"return",
"sc_expr_str_fn",
"(",
"expr",
")",
"if",
"expr",
"[",
"0",
"]",
"is",
"AND",
":",
"return"... | Returns the string representation of the expression 'expr', as in a Kconfig
file.
Passing subexpressions of expressions to this function works as expected.
sc_expr_str_fn (default: standard_sc_expr_str):
This function is called for every symbol/choice (hence "sc") appearing in
the expression, with the symbol/choice as the argument. It is expected to
return a string to be used for the symbol/choice.
This can be used e.g. to turn symbols/choices into links when generating
documentation, or for printing the value of each symbol/choice after it.
Note that quoted values are represented as constants symbols
(Symbol.is_constant == True). | [
"Returns",
"the",
"string",
"representation",
"of",
"the",
"expression",
"expr",
"as",
"in",
"a",
"Kconfig",
"file",
"."
] | 9fe13c03de16c341cd7ed40167216207b821ea50 | https://github.com/ulfalizer/Kconfiglib/blob/9fe13c03de16c341cd7ed40167216207b821ea50/kconfiglib.py#L5553-L5594 |
232,433 | ulfalizer/Kconfiglib | kconfiglib.py | standard_kconfig | def standard_kconfig():
"""
Helper for tools. Loads the top-level Kconfig specified as the first
command-line argument, or "Kconfig" if there are no command-line arguments.
Returns the Kconfig instance.
Exits with sys.exit() (which raises a SystemExit exception) and prints a
usage note to stderr if more than one command-line argument is passed.
"""
if len(sys.argv) > 2:
sys.exit("usage: {} [Kconfig]".format(sys.argv[0]))
# Only show backtraces for unexpected exceptions
try:
return Kconfig("Kconfig" if len(sys.argv) < 2 else sys.argv[1])
except (IOError, KconfigError) as e:
# Some long exception messages have extra newlines for better
# formatting when reported as an unhandled exception. Strip them here.
sys.exit(str(e).strip()) | python | def standard_kconfig():
if len(sys.argv) > 2:
sys.exit("usage: {} [Kconfig]".format(sys.argv[0]))
# Only show backtraces for unexpected exceptions
try:
return Kconfig("Kconfig" if len(sys.argv) < 2 else sys.argv[1])
except (IOError, KconfigError) as e:
# Some long exception messages have extra newlines for better
# formatting when reported as an unhandled exception. Strip them here.
sys.exit(str(e).strip()) | [
"def",
"standard_kconfig",
"(",
")",
":",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
">",
"2",
":",
"sys",
".",
"exit",
"(",
"\"usage: {} [Kconfig]\"",
".",
"format",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
")",
"# Only show backtraces for unexpecte... | Helper for tools. Loads the top-level Kconfig specified as the first
command-line argument, or "Kconfig" if there are no command-line arguments.
Returns the Kconfig instance.
Exits with sys.exit() (which raises a SystemExit exception) and prints a
usage note to stderr if more than one command-line argument is passed. | [
"Helper",
"for",
"tools",
".",
"Loads",
"the",
"top",
"-",
"level",
"Kconfig",
"specified",
"as",
"the",
"first",
"command",
"-",
"line",
"argument",
"or",
"Kconfig",
"if",
"there",
"are",
"no",
"command",
"-",
"line",
"arguments",
".",
"Returns",
"the",
... | 9fe13c03de16c341cd7ed40167216207b821ea50 | https://github.com/ulfalizer/Kconfiglib/blob/9fe13c03de16c341cd7ed40167216207b821ea50/kconfiglib.py#L5689-L5707 |
232,434 | ulfalizer/Kconfiglib | kconfiglib.py | Kconfig.write_config | def write_config(self, filename=None,
header="# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n",
save_old=True, verbose=True):
r"""
Writes out symbol values in the .config format. The format matches the
C implementation, including ordering.
Symbols appear in the same order in generated .config files as they do
in the Kconfig files. For symbols defined in multiple locations, a
single assignment is written out corresponding to the first location
where the symbol is defined.
See the 'Intro to symbol values' section in the module docstring to
understand which symbols get written out.
filename (default: None):
Filename to save configuration to (a string).
If None (the default), the filename in the the environment variable
KCONFIG_CONFIG is used if set, and ".config" otherwise. See
standard_config_filename().
header (default: "# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n"):
Text that will be inserted verbatim at the beginning of the file. You
would usually want each line to start with '#' to make it a comment,
and include a final terminating newline.
save_old (default: True):
If True and <filename> already exists, a copy of it will be saved to
.<filename>.old in the same directory before the new configuration is
written. The leading dot is added only if the filename doesn't
already start with a dot.
Errors are silently ignored if .<filename>.old cannot be written
(e.g. due to being a directory).
verbose (default: True):
If True and filename is None (automatically infer configuration
file), a message will be printed to stdout telling which file got
written. This is meant to reduce boilerplate in tools.
"""
if filename is None:
filename = standard_config_filename()
else:
verbose = False
if save_old:
_save_old(filename)
with self._open(filename, "w") as f:
f.write(header)
for node in self.node_iter(unique_syms=True):
item = node.item
if item.__class__ is Symbol:
f.write(item.config_string)
elif expr_value(node.dep) and \
((item is MENU and expr_value(node.visibility)) or
item is COMMENT):
f.write("\n#\n# {}\n#\n".format(node.prompt[0]))
if verbose:
print("Configuration written to '{}'".format(filename)) | python | def write_config(self, filename=None,
header="# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n",
save_old=True, verbose=True):
r"""
Writes out symbol values in the .config format. The format matches the
C implementation, including ordering.
Symbols appear in the same order in generated .config files as they do
in the Kconfig files. For symbols defined in multiple locations, a
single assignment is written out corresponding to the first location
where the symbol is defined.
See the 'Intro to symbol values' section in the module docstring to
understand which symbols get written out.
filename (default: None):
Filename to save configuration to (a string).
If None (the default), the filename in the the environment variable
KCONFIG_CONFIG is used if set, and ".config" otherwise. See
standard_config_filename().
header (default: "# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n"):
Text that will be inserted verbatim at the beginning of the file. You
would usually want each line to start with '#' to make it a comment,
and include a final terminating newline.
save_old (default: True):
If True and <filename> already exists, a copy of it will be saved to
.<filename>.old in the same directory before the new configuration is
written. The leading dot is added only if the filename doesn't
already start with a dot.
Errors are silently ignored if .<filename>.old cannot be written
(e.g. due to being a directory).
verbose (default: True):
If True and filename is None (automatically infer configuration
file), a message will be printed to stdout telling which file got
written. This is meant to reduce boilerplate in tools.
"""
if filename is None:
filename = standard_config_filename()
else:
verbose = False
if save_old:
_save_old(filename)
with self._open(filename, "w") as f:
f.write(header)
for node in self.node_iter(unique_syms=True):
item = node.item
if item.__class__ is Symbol:
f.write(item.config_string)
elif expr_value(node.dep) and \
((item is MENU and expr_value(node.visibility)) or
item is COMMENT):
f.write("\n#\n# {}\n#\n".format(node.prompt[0]))
if verbose:
print("Configuration written to '{}'".format(filename)) | [
"def",
"write_config",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"header",
"=",
"\"# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\\n\"",
",",
"save_old",
"=",
"True",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"filename",
"is",
"None",
... | r"""
Writes out symbol values in the .config format. The format matches the
C implementation, including ordering.
Symbols appear in the same order in generated .config files as they do
in the Kconfig files. For symbols defined in multiple locations, a
single assignment is written out corresponding to the first location
where the symbol is defined.
See the 'Intro to symbol values' section in the module docstring to
understand which symbols get written out.
filename (default: None):
Filename to save configuration to (a string).
If None (the default), the filename in the the environment variable
KCONFIG_CONFIG is used if set, and ".config" otherwise. See
standard_config_filename().
header (default: "# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n"):
Text that will be inserted verbatim at the beginning of the file. You
would usually want each line to start with '#' to make it a comment,
and include a final terminating newline.
save_old (default: True):
If True and <filename> already exists, a copy of it will be saved to
.<filename>.old in the same directory before the new configuration is
written. The leading dot is added only if the filename doesn't
already start with a dot.
Errors are silently ignored if .<filename>.old cannot be written
(e.g. due to being a directory).
verbose (default: True):
If True and filename is None (automatically infer configuration
file), a message will be printed to stdout telling which file got
written. This is meant to reduce boilerplate in tools. | [
"r",
"Writes",
"out",
"symbol",
"values",
"in",
"the",
".",
"config",
"format",
".",
"The",
"format",
"matches",
"the",
"C",
"implementation",
"including",
"ordering",
"."
] | 9fe13c03de16c341cd7ed40167216207b821ea50 | https://github.com/ulfalizer/Kconfiglib/blob/9fe13c03de16c341cd7ed40167216207b821ea50/kconfiglib.py#L1332-L1397 |
232,435 | ulfalizer/Kconfiglib | kconfiglib.py | Kconfig.write_min_config | def write_min_config(self, filename,
header="# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n"):
"""
Writes out a "minimal" configuration file, omitting symbols whose value
matches their default value. The format matches the one produced by
'make savedefconfig'.
The resulting configuration file is incomplete, but a complete
configuration can be derived from it by loading it. Minimal
configuration files can serve as a more manageable configuration format
compared to a "full" .config file, especially when configurations files
are merged or edited by hand.
filename:
Self-explanatory.
header (default: "# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n"):
Text that will be inserted verbatim at the beginning of the file. You
would usually want each line to start with '#' to make it a comment,
and include a final terminating newline.
"""
with self._open(filename, "w") as f:
f.write(header)
for sym in self.unique_defined_syms:
# Skip symbols that cannot be changed. Only check
# non-choice symbols, as selects don't affect choice
# symbols.
if not sym.choice and \
sym.visibility <= expr_value(sym.rev_dep):
continue
# Skip symbols whose value matches their default
if sym.str_value == sym._str_default():
continue
# Skip symbols that would be selected by default in a
# choice, unless the choice is optional or the symbol type
# isn't bool (it might be possible to set the choice mode
# to n or the symbol to m in those cases).
if sym.choice and \
not sym.choice.is_optional and \
sym.choice._get_selection_from_defaults() is sym and \
sym.orig_type is BOOL and \
sym.tri_value == 2:
continue
f.write(sym.config_string) | python | def write_min_config(self, filename,
header="# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n"):
with self._open(filename, "w") as f:
f.write(header)
for sym in self.unique_defined_syms:
# Skip symbols that cannot be changed. Only check
# non-choice symbols, as selects don't affect choice
# symbols.
if not sym.choice and \
sym.visibility <= expr_value(sym.rev_dep):
continue
# Skip symbols whose value matches their default
if sym.str_value == sym._str_default():
continue
# Skip symbols that would be selected by default in a
# choice, unless the choice is optional or the symbol type
# isn't bool (it might be possible to set the choice mode
# to n or the symbol to m in those cases).
if sym.choice and \
not sym.choice.is_optional and \
sym.choice._get_selection_from_defaults() is sym and \
sym.orig_type is BOOL and \
sym.tri_value == 2:
continue
f.write(sym.config_string) | [
"def",
"write_min_config",
"(",
"self",
",",
"filename",
",",
"header",
"=",
"\"# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\\n\"",
")",
":",
"with",
"self",
".",
"_open",
"(",
"filename",
",",
"\"w\"",
")",
"as",
"f",
":",
"f",
".",
"write"... | Writes out a "minimal" configuration file, omitting symbols whose value
matches their default value. The format matches the one produced by
'make savedefconfig'.
The resulting configuration file is incomplete, but a complete
configuration can be derived from it by loading it. Minimal
configuration files can serve as a more manageable configuration format
compared to a "full" .config file, especially when configurations files
are merged or edited by hand.
filename:
Self-explanatory.
header (default: "# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n"):
Text that will be inserted verbatim at the beginning of the file. You
would usually want each line to start with '#' to make it a comment,
and include a final terminating newline. | [
"Writes",
"out",
"a",
"minimal",
"configuration",
"file",
"omitting",
"symbols",
"whose",
"value",
"matches",
"their",
"default",
"value",
".",
"The",
"format",
"matches",
"the",
"one",
"produced",
"by",
"make",
"savedefconfig",
"."
] | 9fe13c03de16c341cd7ed40167216207b821ea50 | https://github.com/ulfalizer/Kconfiglib/blob/9fe13c03de16c341cd7ed40167216207b821ea50/kconfiglib.py#L1399-L1446 |
232,436 | ulfalizer/Kconfiglib | kconfiglib.py | Kconfig.eval_string | def eval_string(self, s):
"""
Returns the tristate value of the expression 's', represented as 0, 1,
and 2 for n, m, and y, respectively. Raises KconfigError if syntax
errors are detected in 's'. Warns if undefined symbols are referenced.
As an example, if FOO and BAR are tristate symbols at least one of
which has the value y, then config.eval_string("y && (FOO || BAR)")
returns 2 (y).
To get the string value of non-bool/tristate symbols, use
Symbol.str_value. eval_string() always returns a tristate value, and
all non-bool/tristate symbols have the tristate value 0 (n).
The expression parsing is consistent with how parsing works for
conditional ('if ...') expressions in the configuration, and matches
the C implementation. m is rewritten to 'm && MODULES', so
eval_string("m") will return 0 (n) unless modules are enabled.
"""
# The parser is optimized to be fast when parsing Kconfig files (where
# an expression can never appear at the beginning of a line). We have
# to monkey-patch things a bit here to reuse it.
self._filename = None
# Don't include the "if " from below to avoid giving confusing error
# messages
self._line = s
self._tokens = self._tokenize("if " + s)
self._tokens_i = 1 # Skip the 'if' token
return expr_value(self._expect_expr_and_eol()) | python | def eval_string(self, s):
# The parser is optimized to be fast when parsing Kconfig files (where
# an expression can never appear at the beginning of a line). We have
# to monkey-patch things a bit here to reuse it.
self._filename = None
# Don't include the "if " from below to avoid giving confusing error
# messages
self._line = s
self._tokens = self._tokenize("if " + s)
self._tokens_i = 1 # Skip the 'if' token
return expr_value(self._expect_expr_and_eol()) | [
"def",
"eval_string",
"(",
"self",
",",
"s",
")",
":",
"# The parser is optimized to be fast when parsing Kconfig files (where",
"# an expression can never appear at the beginning of a line). We have",
"# to monkey-patch things a bit here to reuse it.",
"self",
".",
"_filename",
"=",
"... | Returns the tristate value of the expression 's', represented as 0, 1,
and 2 for n, m, and y, respectively. Raises KconfigError if syntax
errors are detected in 's'. Warns if undefined symbols are referenced.
As an example, if FOO and BAR are tristate symbols at least one of
which has the value y, then config.eval_string("y && (FOO || BAR)")
returns 2 (y).
To get the string value of non-bool/tristate symbols, use
Symbol.str_value. eval_string() always returns a tristate value, and
all non-bool/tristate symbols have the tristate value 0 (n).
The expression parsing is consistent with how parsing works for
conditional ('if ...') expressions in the configuration, and matches
the C implementation. m is rewritten to 'm && MODULES', so
eval_string("m") will return 0 (n) unless modules are enabled. | [
"Returns",
"the",
"tristate",
"value",
"of",
"the",
"expression",
"s",
"represented",
"as",
"0",
"1",
"and",
"2",
"for",
"n",
"m",
"and",
"y",
"respectively",
".",
"Raises",
"KconfigError",
"if",
"syntax",
"errors",
"are",
"detected",
"in",
"s",
".",
"Wa... | 9fe13c03de16c341cd7ed40167216207b821ea50 | https://github.com/ulfalizer/Kconfiglib/blob/9fe13c03de16c341cd7ed40167216207b821ea50/kconfiglib.py#L1655-L1686 |
232,437 | ulfalizer/Kconfiglib | kconfiglib.py | Symbol.set_value | def set_value(self, value):
"""
Sets the user value of the symbol.
Equal in effect to assigning the value to the symbol within a .config
file. For bool and tristate symbols, use the 'assignable' attribute to
check which values can currently be assigned. Setting values outside
'assignable' will cause Symbol.user_value to differ from
Symbol.str/tri_value (be truncated down or up).
Setting a choice symbol to 2 (y) sets Choice.user_selection to the
choice symbol in addition to setting Symbol.user_value.
Choice.user_selection is considered when the choice is in y mode (the
"normal" mode).
Other symbols that depend (possibly indirectly) on this symbol are
automatically recalculated to reflect the assigned value.
value:
The user value to give to the symbol. For bool and tristate symbols,
n/m/y can be specified either as 0/1/2 (the usual format for tristate
values in Kconfiglib) or as one of the strings "n"/"m"/"y". For other
symbol types, pass a string.
Values that are invalid for the type (such as "foo" or 1 (m) for a
BOOL or "0x123" for an INT) are ignored and won't be stored in
Symbol.user_value. Kconfiglib will print a warning by default for
invalid assignments, and set_value() will return False.
Returns True if the value is valid for the type of the symbol, and
False otherwise. This only looks at the form of the value. For BOOL and
TRISTATE symbols, check the Symbol.assignable attribute to see what
values are currently in range and would actually be reflected in the
value of the symbol. For other symbol types, check whether the
visibility is non-n.
"""
# If the new user value matches the old, nothing changes, and we can
# save some work.
#
# This optimization is skipped for choice symbols: Setting a choice
# symbol's user value to y might change the state of the choice, so it
# wouldn't be safe (symbol user values always match the values set in a
# .config file or via set_value(), and are never implicitly updated).
if value == self.user_value and not self.choice:
self._was_set = True
return True
# Check if the value is valid for our type
if not (self.orig_type is BOOL and value in (2, 0, "y", "n") or
self.orig_type is TRISTATE and value in (2, 1, 0, "y", "m", "n") or
(value.__class__ is str and
(self.orig_type is STRING or
self.orig_type is INT and _is_base_n(value, 10) or
self.orig_type is HEX and _is_base_n(value, 16)
and int(value, 16) >= 0))):
# Display tristate values as n, m, y in the warning
self.kconfig._warn(
"the value {} is invalid for {}, which has type {} -- "
"assignment ignored"
.format(TRI_TO_STR[value] if value in (0, 1, 2) else
"'{}'".format(value),
_name_and_loc(self), TYPE_TO_STR[self.orig_type]))
return False
if self.orig_type in _BOOL_TRISTATE and value in ("y", "m", "n"):
value = STR_TO_TRI[value]
self.user_value = value
self._was_set = True
if self.choice and value == 2:
# Setting a choice symbol to y makes it the user selection of the
# choice. Like for symbol user values, the user selection is not
# guaranteed to match the actual selection of the choice, as
# dependencies come into play.
self.choice.user_selection = self
self.choice._was_set = True
self.choice._rec_invalidate()
else:
self._rec_invalidate_if_has_prompt()
return True | python | def set_value(self, value):
# If the new user value matches the old, nothing changes, and we can
# save some work.
#
# This optimization is skipped for choice symbols: Setting a choice
# symbol's user value to y might change the state of the choice, so it
# wouldn't be safe (symbol user values always match the values set in a
# .config file or via set_value(), and are never implicitly updated).
if value == self.user_value and not self.choice:
self._was_set = True
return True
# Check if the value is valid for our type
if not (self.orig_type is BOOL and value in (2, 0, "y", "n") or
self.orig_type is TRISTATE and value in (2, 1, 0, "y", "m", "n") or
(value.__class__ is str and
(self.orig_type is STRING or
self.orig_type is INT and _is_base_n(value, 10) or
self.orig_type is HEX and _is_base_n(value, 16)
and int(value, 16) >= 0))):
# Display tristate values as n, m, y in the warning
self.kconfig._warn(
"the value {} is invalid for {}, which has type {} -- "
"assignment ignored"
.format(TRI_TO_STR[value] if value in (0, 1, 2) else
"'{}'".format(value),
_name_and_loc(self), TYPE_TO_STR[self.orig_type]))
return False
if self.orig_type in _BOOL_TRISTATE and value in ("y", "m", "n"):
value = STR_TO_TRI[value]
self.user_value = value
self._was_set = True
if self.choice and value == 2:
# Setting a choice symbol to y makes it the user selection of the
# choice. Like for symbol user values, the user selection is not
# guaranteed to match the actual selection of the choice, as
# dependencies come into play.
self.choice.user_selection = self
self.choice._was_set = True
self.choice._rec_invalidate()
else:
self._rec_invalidate_if_has_prompt()
return True | [
"def",
"set_value",
"(",
"self",
",",
"value",
")",
":",
"# If the new user value matches the old, nothing changes, and we can",
"# save some work.",
"#",
"# This optimization is skipped for choice symbols: Setting a choice",
"# symbol's user value to y might change the state of the choice, ... | Sets the user value of the symbol.
Equal in effect to assigning the value to the symbol within a .config
file. For bool and tristate symbols, use the 'assignable' attribute to
check which values can currently be assigned. Setting values outside
'assignable' will cause Symbol.user_value to differ from
Symbol.str/tri_value (be truncated down or up).
Setting a choice symbol to 2 (y) sets Choice.user_selection to the
choice symbol in addition to setting Symbol.user_value.
Choice.user_selection is considered when the choice is in y mode (the
"normal" mode).
Other symbols that depend (possibly indirectly) on this symbol are
automatically recalculated to reflect the assigned value.
value:
The user value to give to the symbol. For bool and tristate symbols,
n/m/y can be specified either as 0/1/2 (the usual format for tristate
values in Kconfiglib) or as one of the strings "n"/"m"/"y". For other
symbol types, pass a string.
Values that are invalid for the type (such as "foo" or 1 (m) for a
BOOL or "0x123" for an INT) are ignored and won't be stored in
Symbol.user_value. Kconfiglib will print a warning by default for
invalid assignments, and set_value() will return False.
Returns True if the value is valid for the type of the symbol, and
False otherwise. This only looks at the form of the value. For BOOL and
TRISTATE symbols, check the Symbol.assignable attribute to see what
values are currently in range and would actually be reflected in the
value of the symbol. For other symbol types, check whether the
visibility is non-n. | [
"Sets",
"the",
"user",
"value",
"of",
"the",
"symbol",
"."
] | 9fe13c03de16c341cd7ed40167216207b821ea50 | https://github.com/ulfalizer/Kconfiglib/blob/9fe13c03de16c341cd7ed40167216207b821ea50/kconfiglib.py#L4194-L4277 |
232,438 | 0k/shyaml | shyaml.py | tokenize | def tokenize(s):
r"""Returns an iterable through all subparts of string splitted by '.'
So:
>>> list(tokenize('foo.bar.wiz'))
['foo', 'bar', 'wiz']
Contrary to traditional ``.split()`` method, this function has to
deal with any type of data in the string. So it actually
interprets the string. Characters with meaning are '.' and '\'.
Both of these can be included in a token by quoting them with '\'.
So dot of slashes can be contained in token:
>>> print('\n'.join(tokenize(r'foo.dot<\.>.slash<\\>')))
foo
dot<.>
slash<\>
Notice that empty keys are also supported:
>>> list(tokenize(r'foo..bar'))
['foo', '', 'bar']
Given an empty string:
>>> list(tokenize(r''))
['']
And a None value:
>>> list(tokenize(None))
[]
"""
if s is None:
return
tokens = (re.sub(r'\\(\\|\.)', r'\1', m.group(0))
for m in re.finditer(r'((\\.|[^.\\])*)', s))
## an empty string superfluous token is added after all non-empty token
for token in tokens:
if len(token) != 0:
next(tokens)
yield token | python | def tokenize(s):
r"""Returns an iterable through all subparts of string splitted by '.'
So:
>>> list(tokenize('foo.bar.wiz'))
['foo', 'bar', 'wiz']
Contrary to traditional ``.split()`` method, this function has to
deal with any type of data in the string. So it actually
interprets the string. Characters with meaning are '.' and '\'.
Both of these can be included in a token by quoting them with '\'.
So dot of slashes can be contained in token:
>>> print('\n'.join(tokenize(r'foo.dot<\.>.slash<\\>')))
foo
dot<.>
slash<\>
Notice that empty keys are also supported:
>>> list(tokenize(r'foo..bar'))
['foo', '', 'bar']
Given an empty string:
>>> list(tokenize(r''))
['']
And a None value:
>>> list(tokenize(None))
[]
"""
if s is None:
return
tokens = (re.sub(r'\\(\\|\.)', r'\1', m.group(0))
for m in re.finditer(r'((\\.|[^.\\])*)', s))
## an empty string superfluous token is added after all non-empty token
for token in tokens:
if len(token) != 0:
next(tokens)
yield token | [
"def",
"tokenize",
"(",
"s",
")",
":",
"if",
"s",
"is",
"None",
":",
"return",
"tokens",
"=",
"(",
"re",
".",
"sub",
"(",
"r'\\\\(\\\\|\\.)'",
",",
"r'\\1'",
",",
"m",
".",
"group",
"(",
"0",
")",
")",
"for",
"m",
"in",
"re",
".",
"finditer",
"... | r"""Returns an iterable through all subparts of string splitted by '.'
So:
>>> list(tokenize('foo.bar.wiz'))
['foo', 'bar', 'wiz']
Contrary to traditional ``.split()`` method, this function has to
deal with any type of data in the string. So it actually
interprets the string. Characters with meaning are '.' and '\'.
Both of these can be included in a token by quoting them with '\'.
So dot of slashes can be contained in token:
>>> print('\n'.join(tokenize(r'foo.dot<\.>.slash<\\>')))
foo
dot<.>
slash<\>
Notice that empty keys are also supported:
>>> list(tokenize(r'foo..bar'))
['foo', '', 'bar']
Given an empty string:
>>> list(tokenize(r''))
['']
And a None value:
>>> list(tokenize(None))
[] | [
"r",
"Returns",
"an",
"iterable",
"through",
"all",
"subparts",
"of",
"string",
"splitted",
"by",
"."
] | 8dcf9bb39f995564271600a4dae1fc114077c2e0 | https://github.com/0k/shyaml/blob/8dcf9bb39f995564271600a4dae1fc114077c2e0/shyaml.py#L227-L271 |
232,439 | 0k/shyaml | shyaml.py | aget | def aget(dct, key):
r"""Allow to get values deep in a dict with iterable keys
Accessing leaf values is quite straightforward:
>>> dct = {'a': {'x': 1, 'b': {'c': 2}}}
>>> aget(dct, ('a', 'x'))
1
>>> aget(dct, ('a', 'b', 'c'))
2
If key is empty, it returns unchanged the ``dct`` value.
>>> aget({'x': 1}, ())
{'x': 1}
"""
key = iter(key)
try:
head = next(key)
except StopIteration:
return dct
if isinstance(dct, list):
try:
idx = int(head)
except ValueError:
raise IndexNotIntegerError(
"non-integer index %r provided on a list."
% head)
try:
value = dct[idx]
except IndexError:
raise IndexOutOfRange(
"index %d is out of range (%d elements in list)."
% (idx, len(dct)))
else:
try:
value = dct[head]
except KeyError:
## Replace with a more informative KeyError
raise MissingKeyError(
"missing key %r in dict."
% (head, ))
except Exception:
raise NonDictLikeTypeError(
"can't query subvalue %r of a leaf%s."
% (head,
(" (leaf value is %r)" % dct)
if len(repr(dct)) < 15 else ""))
return aget(value, key) | python | def aget(dct, key):
r"""Allow to get values deep in a dict with iterable keys
Accessing leaf values is quite straightforward:
>>> dct = {'a': {'x': 1, 'b': {'c': 2}}}
>>> aget(dct, ('a', 'x'))
1
>>> aget(dct, ('a', 'b', 'c'))
2
If key is empty, it returns unchanged the ``dct`` value.
>>> aget({'x': 1}, ())
{'x': 1}
"""
key = iter(key)
try:
head = next(key)
except StopIteration:
return dct
if isinstance(dct, list):
try:
idx = int(head)
except ValueError:
raise IndexNotIntegerError(
"non-integer index %r provided on a list."
% head)
try:
value = dct[idx]
except IndexError:
raise IndexOutOfRange(
"index %d is out of range (%d elements in list)."
% (idx, len(dct)))
else:
try:
value = dct[head]
except KeyError:
## Replace with a more informative KeyError
raise MissingKeyError(
"missing key %r in dict."
% (head, ))
except Exception:
raise NonDictLikeTypeError(
"can't query subvalue %r of a leaf%s."
% (head,
(" (leaf value is %r)" % dct)
if len(repr(dct)) < 15 else ""))
return aget(value, key) | [
"def",
"aget",
"(",
"dct",
",",
"key",
")",
":",
"key",
"=",
"iter",
"(",
"key",
")",
"try",
":",
"head",
"=",
"next",
"(",
"key",
")",
"except",
"StopIteration",
":",
"return",
"dct",
"if",
"isinstance",
"(",
"dct",
",",
"list",
")",
":",
"try",... | r"""Allow to get values deep in a dict with iterable keys
Accessing leaf values is quite straightforward:
>>> dct = {'a': {'x': 1, 'b': {'c': 2}}}
>>> aget(dct, ('a', 'x'))
1
>>> aget(dct, ('a', 'b', 'c'))
2
If key is empty, it returns unchanged the ``dct`` value.
>>> aget({'x': 1}, ())
{'x': 1} | [
"r",
"Allow",
"to",
"get",
"values",
"deep",
"in",
"a",
"dict",
"with",
"iterable",
"keys"
] | 8dcf9bb39f995564271600a4dae1fc114077c2e0 | https://github.com/0k/shyaml/blob/8dcf9bb39f995564271600a4dae1fc114077c2e0/shyaml.py#L375-L425 |
232,440 | 0k/shyaml | shyaml.py | die | def die(msg, errlvl=1, prefix="Error: "):
"""Convenience function to write short message to stderr and quit."""
stderr("%s%s\n" % (prefix, msg))
sys.exit(errlvl) | python | def die(msg, errlvl=1, prefix="Error: "):
stderr("%s%s\n" % (prefix, msg))
sys.exit(errlvl) | [
"def",
"die",
"(",
"msg",
",",
"errlvl",
"=",
"1",
",",
"prefix",
"=",
"\"Error: \"",
")",
":",
"stderr",
"(",
"\"%s%s\\n\"",
"%",
"(",
"prefix",
",",
"msg",
")",
")",
"sys",
".",
"exit",
"(",
"errlvl",
")"
] | Convenience function to write short message to stderr and quit. | [
"Convenience",
"function",
"to",
"write",
"short",
"message",
"to",
"stderr",
"and",
"quit",
"."
] | 8dcf9bb39f995564271600a4dae1fc114077c2e0 | https://github.com/0k/shyaml/blob/8dcf9bb39f995564271600a4dae1fc114077c2e0/shyaml.py#L438-L441 |
232,441 | 0k/shyaml | shyaml.py | type_name | def type_name(value):
"""Returns pseudo-YAML type name of given value."""
return type(value).__name__ if isinstance(value, EncapsulatedNode) else \
"struct" if isinstance(value, dict) else \
"sequence" if isinstance(value, (tuple, list)) else \
type(value).__name__ | python | def type_name(value):
return type(value).__name__ if isinstance(value, EncapsulatedNode) else \
"struct" if isinstance(value, dict) else \
"sequence" if isinstance(value, (tuple, list)) else \
type(value).__name__ | [
"def",
"type_name",
"(",
"value",
")",
":",
"return",
"type",
"(",
"value",
")",
".",
"__name__",
"if",
"isinstance",
"(",
"value",
",",
"EncapsulatedNode",
")",
"else",
"\"struct\"",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
"else",
"\"sequence\... | Returns pseudo-YAML type name of given value. | [
"Returns",
"pseudo",
"-",
"YAML",
"type",
"name",
"of",
"given",
"value",
"."
] | 8dcf9bb39f995564271600a4dae1fc114077c2e0 | https://github.com/0k/shyaml/blob/8dcf9bb39f995564271600a4dae1fc114077c2e0/shyaml.py#L472-L477 |
232,442 | 0k/shyaml | shyaml.py | do | def do(stream, action, key, default=None, dump=yaml_dump,
loader=ShyamlSafeLoader):
"""Return string representations of target value in stream YAML
The key is used for traversal of the YAML structure to target
the value that will be dumped.
:param stream: file like input yaml content
:param action: string identifying one of the possible supported actions
:param key: string dotted expression to traverse yaml input
:param default: optional default value in case of missing end value when
traversing input yaml. (default is ``None``)
:param dump: callable that will be given python objet to dump in yaml
(default is ``yaml_dump``)
:param loader: PyYAML's *Loader subclass to parse YAML
(default is ShyamlSafeLoader)
:return: generator of string representation of target value per
YAML docs in the given stream.
:raises ActionTypeError: when there's a type mismatch between the
action selected and the type of the targetted value.
(ie: action 'key-values' on non-struct)
:raises InvalidAction: when selected action is not a recognised valid
action identifier.
:raises InvalidPath: upon inexistent content when traversing YAML
input following the key specification.
"""
at_least_one_content = False
for content in yaml.load_all(stream, Loader=loader):
at_least_one_content = True
value = traverse(content, key, default=default)
yield act(action, value, dump=dump)
## In case of empty stream, we consider that it is equivalent
## to one document having the ``null`` value.
if at_least_one_content is False:
value = traverse(None, key, default=default)
yield act(action, value, dump=dump) | python | def do(stream, action, key, default=None, dump=yaml_dump,
loader=ShyamlSafeLoader):
at_least_one_content = False
for content in yaml.load_all(stream, Loader=loader):
at_least_one_content = True
value = traverse(content, key, default=default)
yield act(action, value, dump=dump)
## In case of empty stream, we consider that it is equivalent
## to one document having the ``null`` value.
if at_least_one_content is False:
value = traverse(None, key, default=default)
yield act(action, value, dump=dump) | [
"def",
"do",
"(",
"stream",
",",
"action",
",",
"key",
",",
"default",
"=",
"None",
",",
"dump",
"=",
"yaml_dump",
",",
"loader",
"=",
"ShyamlSafeLoader",
")",
":",
"at_least_one_content",
"=",
"False",
"for",
"content",
"in",
"yaml",
".",
"load_all",
"(... | Return string representations of target value in stream YAML
The key is used for traversal of the YAML structure to target
the value that will be dumped.
:param stream: file like input yaml content
:param action: string identifying one of the possible supported actions
:param key: string dotted expression to traverse yaml input
:param default: optional default value in case of missing end value when
traversing input yaml. (default is ``None``)
:param dump: callable that will be given python objet to dump in yaml
(default is ``yaml_dump``)
:param loader: PyYAML's *Loader subclass to parse YAML
(default is ShyamlSafeLoader)
:return: generator of string representation of target value per
YAML docs in the given stream.
:raises ActionTypeError: when there's a type mismatch between the
action selected and the type of the targetted value.
(ie: action 'key-values' on non-struct)
:raises InvalidAction: when selected action is not a recognised valid
action identifier.
:raises InvalidPath: upon inexistent content when traversing YAML
input following the key specification. | [
"Return",
"string",
"representations",
"of",
"target",
"value",
"in",
"stream",
"YAML"
] | 8dcf9bb39f995564271600a4dae1fc114077c2e0 | https://github.com/0k/shyaml/blob/8dcf9bb39f995564271600a4dae1fc114077c2e0/shyaml.py#L626-L664 |
232,443 | charlierguo/gmail | gmail/utf.py | encode | def encode(s):
"""Encode a folder name using IMAP modified UTF-7 encoding.
Despite the function's name, the output is still a unicode string.
"""
if not isinstance(s, text_type):
return s
r = []
_in = []
def extend_result_if_chars_buffered():
if _in:
r.extend(['&', modified_utf7(''.join(_in)), '-'])
del _in[:]
for c in s:
if ord(c) in PRINTABLE:
extend_result_if_chars_buffered()
r.append(c)
elif c == '&':
extend_result_if_chars_buffered()
r.append('&-')
else:
_in.append(c)
extend_result_if_chars_buffered()
return ''.join(r) | python | def encode(s):
if not isinstance(s, text_type):
return s
r = []
_in = []
def extend_result_if_chars_buffered():
if _in:
r.extend(['&', modified_utf7(''.join(_in)), '-'])
del _in[:]
for c in s:
if ord(c) in PRINTABLE:
extend_result_if_chars_buffered()
r.append(c)
elif c == '&':
extend_result_if_chars_buffered()
r.append('&-')
else:
_in.append(c)
extend_result_if_chars_buffered()
return ''.join(r) | [
"def",
"encode",
"(",
"s",
")",
":",
"if",
"not",
"isinstance",
"(",
"s",
",",
"text_type",
")",
":",
"return",
"s",
"r",
"=",
"[",
"]",
"_in",
"=",
"[",
"]",
"def",
"extend_result_if_chars_buffered",
"(",
")",
":",
"if",
"_in",
":",
"r",
".",
"e... | Encode a folder name using IMAP modified UTF-7 encoding.
Despite the function's name, the output is still a unicode string. | [
"Encode",
"a",
"folder",
"name",
"using",
"IMAP",
"modified",
"UTF",
"-",
"7",
"encoding",
"."
] | 4626823d3fbf159d242a50b33251576aeddbd9ad | https://github.com/charlierguo/gmail/blob/4626823d3fbf159d242a50b33251576aeddbd9ad/gmail/utf.py#L30-L58 |
232,444 | charlierguo/gmail | gmail/utf.py | decode | def decode(s):
"""Decode a folder name from IMAP modified UTF-7 encoding to unicode.
Despite the function's name, the input may still be a unicode
string. If the input is bytes, it's first decoded to unicode.
"""
if isinstance(s, binary_type):
s = s.decode('latin-1')
if not isinstance(s, text_type):
return s
r = []
_in = []
for c in s:
if c == '&' and not _in:
_in.append('&')
elif c == '-' and _in:
if len(_in) == 1:
r.append('&')
else:
r.append(modified_deutf7(''.join(_in[1:])))
_in = []
elif _in:
_in.append(c)
else:
r.append(c)
if _in:
r.append(modified_deutf7(''.join(_in[1:])))
return ''.join(r) | python | def decode(s):
if isinstance(s, binary_type):
s = s.decode('latin-1')
if not isinstance(s, text_type):
return s
r = []
_in = []
for c in s:
if c == '&' and not _in:
_in.append('&')
elif c == '-' and _in:
if len(_in) == 1:
r.append('&')
else:
r.append(modified_deutf7(''.join(_in[1:])))
_in = []
elif _in:
_in.append(c)
else:
r.append(c)
if _in:
r.append(modified_deutf7(''.join(_in[1:])))
return ''.join(r) | [
"def",
"decode",
"(",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"binary_type",
")",
":",
"s",
"=",
"s",
".",
"decode",
"(",
"'latin-1'",
")",
"if",
"not",
"isinstance",
"(",
"s",
",",
"text_type",
")",
":",
"return",
"s",
"r",
"=",
"[",
... | Decode a folder name from IMAP modified UTF-7 encoding to unicode.
Despite the function's name, the input may still be a unicode
string. If the input is bytes, it's first decoded to unicode. | [
"Decode",
"a",
"folder",
"name",
"from",
"IMAP",
"modified",
"UTF",
"-",
"7",
"encoding",
"to",
"unicode",
"."
] | 4626823d3fbf159d242a50b33251576aeddbd9ad | https://github.com/charlierguo/gmail/blob/4626823d3fbf159d242a50b33251576aeddbd9ad/gmail/utf.py#L60-L89 |
232,445 | rhiever/datacleaner | datacleaner/datacleaner.py | autoclean | def autoclean(input_dataframe, drop_nans=False, copy=False, encoder=None,
encoder_kwargs=None, ignore_update_check=False):
"""Performs a series of automated data cleaning transformations on the provided data set
Parameters
----------
input_dataframe: pandas.DataFrame
Data set to clean
drop_nans: bool
Drop all rows that have a NaN in any column (default: False)
copy: bool
Make a copy of the data set (default: False)
encoder: category_encoders transformer
The a valid category_encoders transformer which is passed an inferred cols list. Default (None: LabelEncoder)
encoder_kwargs: category_encoders
The a valid sklearn transformer to encode categorical features. Default (None)
ignore_update_check: bool
Do not check for the latest version of datacleaner
Returns
----------
output_dataframe: pandas.DataFrame
Cleaned data set
"""
global update_checked
if ignore_update_check:
update_checked = True
if not update_checked:
update_check('datacleaner', __version__)
update_checked = True
if copy:
input_dataframe = input_dataframe.copy()
if drop_nans:
input_dataframe.dropna(inplace=True)
if encoder_kwargs is None:
encoder_kwargs = {}
for column in input_dataframe.columns.values:
# Replace NaNs with the median or mode of the column depending on the column type
try:
input_dataframe[column].fillna(input_dataframe[column].median(), inplace=True)
except TypeError:
most_frequent = input_dataframe[column].mode()
# If the mode can't be computed, use the nearest valid value
# See https://github.com/rhiever/datacleaner/issues/8
if len(most_frequent) > 0:
input_dataframe[column].fillna(input_dataframe[column].mode()[0], inplace=True)
else:
input_dataframe[column].fillna(method='bfill', inplace=True)
input_dataframe[column].fillna(method='ffill', inplace=True)
# Encode all strings with numerical equivalents
if str(input_dataframe[column].values.dtype) == 'object':
if encoder is not None:
column_encoder = encoder(**encoder_kwargs).fit(input_dataframe[column].values)
else:
column_encoder = LabelEncoder().fit(input_dataframe[column].values)
input_dataframe[column] = column_encoder.transform(input_dataframe[column].values)
return input_dataframe | python | def autoclean(input_dataframe, drop_nans=False, copy=False, encoder=None,
encoder_kwargs=None, ignore_update_check=False):
global update_checked
if ignore_update_check:
update_checked = True
if not update_checked:
update_check('datacleaner', __version__)
update_checked = True
if copy:
input_dataframe = input_dataframe.copy()
if drop_nans:
input_dataframe.dropna(inplace=True)
if encoder_kwargs is None:
encoder_kwargs = {}
for column in input_dataframe.columns.values:
# Replace NaNs with the median or mode of the column depending on the column type
try:
input_dataframe[column].fillna(input_dataframe[column].median(), inplace=True)
except TypeError:
most_frequent = input_dataframe[column].mode()
# If the mode can't be computed, use the nearest valid value
# See https://github.com/rhiever/datacleaner/issues/8
if len(most_frequent) > 0:
input_dataframe[column].fillna(input_dataframe[column].mode()[0], inplace=True)
else:
input_dataframe[column].fillna(method='bfill', inplace=True)
input_dataframe[column].fillna(method='ffill', inplace=True)
# Encode all strings with numerical equivalents
if str(input_dataframe[column].values.dtype) == 'object':
if encoder is not None:
column_encoder = encoder(**encoder_kwargs).fit(input_dataframe[column].values)
else:
column_encoder = LabelEncoder().fit(input_dataframe[column].values)
input_dataframe[column] = column_encoder.transform(input_dataframe[column].values)
return input_dataframe | [
"def",
"autoclean",
"(",
"input_dataframe",
",",
"drop_nans",
"=",
"False",
",",
"copy",
"=",
"False",
",",
"encoder",
"=",
"None",
",",
"encoder_kwargs",
"=",
"None",
",",
"ignore_update_check",
"=",
"False",
")",
":",
"global",
"update_checked",
"if",
"ign... | Performs a series of automated data cleaning transformations on the provided data set
Parameters
----------
input_dataframe: pandas.DataFrame
Data set to clean
drop_nans: bool
Drop all rows that have a NaN in any column (default: False)
copy: bool
Make a copy of the data set (default: False)
encoder: category_encoders transformer
The a valid category_encoders transformer which is passed an inferred cols list. Default (None: LabelEncoder)
encoder_kwargs: category_encoders
The a valid sklearn transformer to encode categorical features. Default (None)
ignore_update_check: bool
Do not check for the latest version of datacleaner
Returns
----------
output_dataframe: pandas.DataFrame
Cleaned data set | [
"Performs",
"a",
"series",
"of",
"automated",
"data",
"cleaning",
"transformations",
"on",
"the",
"provided",
"data",
"set"
] | f6f92d763ab385013b72776acf990857d4949e66 | https://github.com/rhiever/datacleaner/blob/f6f92d763ab385013b72776acf990857d4949e66/datacleaner/datacleaner.py#L32-L98 |
232,446 | rhiever/datacleaner | datacleaner/datacleaner.py | autoclean_cv | def autoclean_cv(training_dataframe, testing_dataframe, drop_nans=False, copy=False,
encoder=None, encoder_kwargs=None, ignore_update_check=False):
"""Performs a series of automated data cleaning transformations on the provided training and testing data sets
Unlike `autoclean()`, this function takes cross-validation into account by learning the data transformations
from only the training set, then applying those transformations to both the training and testing set.
By doing so, this function will prevent information leak from the training set into the testing set.
Parameters
----------
training_dataframe: pandas.DataFrame
Training data set
testing_dataframe: pandas.DataFrame
Testing data set
drop_nans: bool
Drop all rows that have a NaN in any column (default: False)
copy: bool
Make a copy of the data set (default: False)
encoder: category_encoders transformer
The a valid category_encoders transformer which is passed an inferred cols list. Default (None: LabelEncoder)
encoder_kwargs: category_encoders
The a valid sklearn transformer to encode categorical features. Default (None)
ignore_update_check: bool
Do not check for the latest version of datacleaner
Returns
----------
output_training_dataframe: pandas.DataFrame
Cleaned training data set
output_testing_dataframe: pandas.DataFrame
Cleaned testing data set
"""
global update_checked
if ignore_update_check:
update_checked = True
if not update_checked:
update_check('datacleaner', __version__)
update_checked = True
if set(training_dataframe.columns.values) != set(testing_dataframe.columns.values):
raise ValueError('The training and testing DataFrames do not have the same columns. '
'Make sure that you are providing the same columns.')
if copy:
training_dataframe = training_dataframe.copy()
testing_dataframe = testing_dataframe.copy()
if drop_nans:
training_dataframe.dropna(inplace=True)
testing_dataframe.dropna(inplace=True)
if encoder_kwargs is None:
encoder_kwargs = {}
for column in training_dataframe.columns.values:
# Replace NaNs with the median or mode of the column depending on the column type
try:
column_median = training_dataframe[column].median()
training_dataframe[column].fillna(column_median, inplace=True)
testing_dataframe[column].fillna(column_median, inplace=True)
except TypeError:
column_mode = training_dataframe[column].mode()[0]
training_dataframe[column].fillna(column_mode, inplace=True)
testing_dataframe[column].fillna(column_mode, inplace=True)
# Encode all strings with numerical equivalents
if str(training_dataframe[column].values.dtype) == 'object':
if encoder is not None:
column_encoder = encoder(**encoder_kwargs).fit(training_dataframe[column].values)
else:
column_encoder = LabelEncoder().fit(training_dataframe[column].values)
training_dataframe[column] = column_encoder.transform(training_dataframe[column].values)
testing_dataframe[column] = column_encoder.transform(testing_dataframe[column].values)
return training_dataframe, testing_dataframe | python | def autoclean_cv(training_dataframe, testing_dataframe, drop_nans=False, copy=False,
encoder=None, encoder_kwargs=None, ignore_update_check=False):
global update_checked
if ignore_update_check:
update_checked = True
if not update_checked:
update_check('datacleaner', __version__)
update_checked = True
if set(training_dataframe.columns.values) != set(testing_dataframe.columns.values):
raise ValueError('The training and testing DataFrames do not have the same columns. '
'Make sure that you are providing the same columns.')
if copy:
training_dataframe = training_dataframe.copy()
testing_dataframe = testing_dataframe.copy()
if drop_nans:
training_dataframe.dropna(inplace=True)
testing_dataframe.dropna(inplace=True)
if encoder_kwargs is None:
encoder_kwargs = {}
for column in training_dataframe.columns.values:
# Replace NaNs with the median or mode of the column depending on the column type
try:
column_median = training_dataframe[column].median()
training_dataframe[column].fillna(column_median, inplace=True)
testing_dataframe[column].fillna(column_median, inplace=True)
except TypeError:
column_mode = training_dataframe[column].mode()[0]
training_dataframe[column].fillna(column_mode, inplace=True)
testing_dataframe[column].fillna(column_mode, inplace=True)
# Encode all strings with numerical equivalents
if str(training_dataframe[column].values.dtype) == 'object':
if encoder is not None:
column_encoder = encoder(**encoder_kwargs).fit(training_dataframe[column].values)
else:
column_encoder = LabelEncoder().fit(training_dataframe[column].values)
training_dataframe[column] = column_encoder.transform(training_dataframe[column].values)
testing_dataframe[column] = column_encoder.transform(testing_dataframe[column].values)
return training_dataframe, testing_dataframe | [
"def",
"autoclean_cv",
"(",
"training_dataframe",
",",
"testing_dataframe",
",",
"drop_nans",
"=",
"False",
",",
"copy",
"=",
"False",
",",
"encoder",
"=",
"None",
",",
"encoder_kwargs",
"=",
"None",
",",
"ignore_update_check",
"=",
"False",
")",
":",
"global"... | Performs a series of automated data cleaning transformations on the provided training and testing data sets
Unlike `autoclean()`, this function takes cross-validation into account by learning the data transformations
from only the training set, then applying those transformations to both the training and testing set.
By doing so, this function will prevent information leak from the training set into the testing set.
Parameters
----------
training_dataframe: pandas.DataFrame
Training data set
testing_dataframe: pandas.DataFrame
Testing data set
drop_nans: bool
Drop all rows that have a NaN in any column (default: False)
copy: bool
Make a copy of the data set (default: False)
encoder: category_encoders transformer
The a valid category_encoders transformer which is passed an inferred cols list. Default (None: LabelEncoder)
encoder_kwargs: category_encoders
The a valid sklearn transformer to encode categorical features. Default (None)
ignore_update_check: bool
Do not check for the latest version of datacleaner
Returns
----------
output_training_dataframe: pandas.DataFrame
Cleaned training data set
output_testing_dataframe: pandas.DataFrame
Cleaned testing data set | [
"Performs",
"a",
"series",
"of",
"automated",
"data",
"cleaning",
"transformations",
"on",
"the",
"provided",
"training",
"and",
"testing",
"data",
"sets"
] | f6f92d763ab385013b72776acf990857d4949e66 | https://github.com/rhiever/datacleaner/blob/f6f92d763ab385013b72776acf990857d4949e66/datacleaner/datacleaner.py#L100-L177 |
232,447 | django-treebeard/django-treebeard | treebeard/models.py | Node.get_foreign_keys | def get_foreign_keys(cls):
"""Get foreign keys and models they refer to, so we can pre-process
the data for load_bulk
"""
foreign_keys = {}
for field in cls._meta.fields:
if (
field.get_internal_type() == 'ForeignKey' and
field.name != 'parent'
):
if django.VERSION >= (1, 9):
foreign_keys[field.name] = field.remote_field.model
else:
foreign_keys[field.name] = field.rel.to
return foreign_keys | python | def get_foreign_keys(cls):
foreign_keys = {}
for field in cls._meta.fields:
if (
field.get_internal_type() == 'ForeignKey' and
field.name != 'parent'
):
if django.VERSION >= (1, 9):
foreign_keys[field.name] = field.remote_field.model
else:
foreign_keys[field.name] = field.rel.to
return foreign_keys | [
"def",
"get_foreign_keys",
"(",
"cls",
")",
":",
"foreign_keys",
"=",
"{",
"}",
"for",
"field",
"in",
"cls",
".",
"_meta",
".",
"fields",
":",
"if",
"(",
"field",
".",
"get_internal_type",
"(",
")",
"==",
"'ForeignKey'",
"and",
"field",
".",
"name",
"!... | Get foreign keys and models they refer to, so we can pre-process
the data for load_bulk | [
"Get",
"foreign",
"keys",
"and",
"models",
"they",
"refer",
"to",
"so",
"we",
"can",
"pre",
"-",
"process",
"the",
"data",
"for",
"load_bulk"
] | 8042ee939cb45394909237da447f8925e3cc6aa3 | https://github.com/django-treebeard/django-treebeard/blob/8042ee939cb45394909237da447f8925e3cc6aa3/treebeard/models.py#L43-L57 |
232,448 | django-treebeard/django-treebeard | treebeard/models.py | Node._process_foreign_keys | def _process_foreign_keys(cls, foreign_keys, node_data):
"""For each foreign key try to load the actual object so load_bulk
doesn't fail trying to load an int where django expects a
model instance
"""
for key in foreign_keys.keys():
if key in node_data:
node_data[key] = foreign_keys[key].objects.get(
pk=node_data[key]) | python | def _process_foreign_keys(cls, foreign_keys, node_data):
for key in foreign_keys.keys():
if key in node_data:
node_data[key] = foreign_keys[key].objects.get(
pk=node_data[key]) | [
"def",
"_process_foreign_keys",
"(",
"cls",
",",
"foreign_keys",
",",
"node_data",
")",
":",
"for",
"key",
"in",
"foreign_keys",
".",
"keys",
"(",
")",
":",
"if",
"key",
"in",
"node_data",
":",
"node_data",
"[",
"key",
"]",
"=",
"foreign_keys",
"[",
"key... | For each foreign key try to load the actual object so load_bulk
doesn't fail trying to load an int where django expects a
model instance | [
"For",
"each",
"foreign",
"key",
"try",
"to",
"load",
"the",
"actual",
"object",
"so",
"load_bulk",
"doesn",
"t",
"fail",
"trying",
"to",
"load",
"an",
"int",
"where",
"django",
"expects",
"a",
"model",
"instance"
] | 8042ee939cb45394909237da447f8925e3cc6aa3 | https://github.com/django-treebeard/django-treebeard/blob/8042ee939cb45394909237da447f8925e3cc6aa3/treebeard/models.py#L60-L68 |
232,449 | django-treebeard/django-treebeard | treebeard/models.py | Node.delete | def delete(self):
"""Removes a node and all it's descendants."""
self.__class__.objects.filter(pk=self.pk).delete() | python | def delete(self):
self.__class__.objects.filter(pk=self.pk).delete() | [
"def",
"delete",
"(",
"self",
")",
":",
"self",
".",
"__class__",
".",
"objects",
".",
"filter",
"(",
"pk",
"=",
"self",
".",
"pk",
")",
".",
"delete",
"(",
")"
] | Removes a node and all it's descendants. | [
"Removes",
"a",
"node",
"and",
"all",
"it",
"s",
"descendants",
"."
] | 8042ee939cb45394909237da447f8925e3cc6aa3 | https://github.com/django-treebeard/django-treebeard/blob/8042ee939cb45394909237da447f8925e3cc6aa3/treebeard/models.py#L508-L510 |
232,450 | django-treebeard/django-treebeard | treebeard/models.py | Node.get_annotated_list_qs | def get_annotated_list_qs(cls, qs):
"""
Gets an annotated list from a queryset.
"""
result, info = [], {}
start_depth, prev_depth = (None, None)
for node in qs:
depth = node.get_depth()
if start_depth is None:
start_depth = depth
open = (depth and (prev_depth is None or depth > prev_depth))
if prev_depth is not None and depth < prev_depth:
info['close'] = list(range(0, prev_depth - depth))
info = {'open': open, 'close': [], 'level': depth - start_depth}
result.append((node, info,))
prev_depth = depth
if start_depth and start_depth > 0:
info['close'] = list(range(0, prev_depth - start_depth + 1))
return result | python | def get_annotated_list_qs(cls, qs):
result, info = [], {}
start_depth, prev_depth = (None, None)
for node in qs:
depth = node.get_depth()
if start_depth is None:
start_depth = depth
open = (depth and (prev_depth is None or depth > prev_depth))
if prev_depth is not None and depth < prev_depth:
info['close'] = list(range(0, prev_depth - depth))
info = {'open': open, 'close': [], 'level': depth - start_depth}
result.append((node, info,))
prev_depth = depth
if start_depth and start_depth > 0:
info['close'] = list(range(0, prev_depth - start_depth + 1))
return result | [
"def",
"get_annotated_list_qs",
"(",
"cls",
",",
"qs",
")",
":",
"result",
",",
"info",
"=",
"[",
"]",
",",
"{",
"}",
"start_depth",
",",
"prev_depth",
"=",
"(",
"None",
",",
"None",
")",
"for",
"node",
"in",
"qs",
":",
"depth",
"=",
"node",
".",
... | Gets an annotated list from a queryset. | [
"Gets",
"an",
"annotated",
"list",
"from",
"a",
"queryset",
"."
] | 8042ee939cb45394909237da447f8925e3cc6aa3 | https://github.com/django-treebeard/django-treebeard/blob/8042ee939cb45394909237da447f8925e3cc6aa3/treebeard/models.py#L574-L592 |
232,451 | django-treebeard/django-treebeard | treebeard/models.py | Node.get_annotated_list | def get_annotated_list(cls, parent=None, max_depth=None):
"""
Gets an annotated list from a tree branch.
:param parent:
The node whose descendants will be annotated. The node itself
will be included in the list. If not given, the entire tree
will be annotated.
:param max_depth:
Optionally limit to specified depth
"""
result, info = [], {}
start_depth, prev_depth = (None, None)
qs = cls.get_tree(parent)
if max_depth:
qs = qs.filter(depth__lte=max_depth)
return cls.get_annotated_list_qs(qs) | python | def get_annotated_list(cls, parent=None, max_depth=None):
result, info = [], {}
start_depth, prev_depth = (None, None)
qs = cls.get_tree(parent)
if max_depth:
qs = qs.filter(depth__lte=max_depth)
return cls.get_annotated_list_qs(qs) | [
"def",
"get_annotated_list",
"(",
"cls",
",",
"parent",
"=",
"None",
",",
"max_depth",
"=",
"None",
")",
":",
"result",
",",
"info",
"=",
"[",
"]",
",",
"{",
"}",
"start_depth",
",",
"prev_depth",
"=",
"(",
"None",
",",
"None",
")",
"qs",
"=",
"cls... | Gets an annotated list from a tree branch.
:param parent:
The node whose descendants will be annotated. The node itself
will be included in the list. If not given, the entire tree
will be annotated.
:param max_depth:
Optionally limit to specified depth | [
"Gets",
"an",
"annotated",
"list",
"from",
"a",
"tree",
"branch",
"."
] | 8042ee939cb45394909237da447f8925e3cc6aa3 | https://github.com/django-treebeard/django-treebeard/blob/8042ee939cb45394909237da447f8925e3cc6aa3/treebeard/models.py#L595-L615 |
232,452 | django-treebeard/django-treebeard | treebeard/admin.py | TreeAdmin.get_urls | def get_urls(self):
"""
Adds a url to move nodes to this admin
"""
urls = super(TreeAdmin, self).get_urls()
if django.VERSION < (1, 10):
from django.views.i18n import javascript_catalog
jsi18n_url = url(r'^jsi18n/$', javascript_catalog, {'packages': ('treebeard',)})
else:
from django.views.i18n import JavaScriptCatalog
jsi18n_url = url(r'^jsi18n/$',
JavaScriptCatalog.as_view(packages=['treebeard']),
name='javascript-catalog'
)
new_urls = [
url('^move/$', self.admin_site.admin_view(self.move_node), ),
jsi18n_url,
]
return new_urls + urls | python | def get_urls(self):
urls = super(TreeAdmin, self).get_urls()
if django.VERSION < (1, 10):
from django.views.i18n import javascript_catalog
jsi18n_url = url(r'^jsi18n/$', javascript_catalog, {'packages': ('treebeard',)})
else:
from django.views.i18n import JavaScriptCatalog
jsi18n_url = url(r'^jsi18n/$',
JavaScriptCatalog.as_view(packages=['treebeard']),
name='javascript-catalog'
)
new_urls = [
url('^move/$', self.admin_site.admin_view(self.move_node), ),
jsi18n_url,
]
return new_urls + urls | [
"def",
"get_urls",
"(",
"self",
")",
":",
"urls",
"=",
"super",
"(",
"TreeAdmin",
",",
"self",
")",
".",
"get_urls",
"(",
")",
"if",
"django",
".",
"VERSION",
"<",
"(",
"1",
",",
"10",
")",
":",
"from",
"django",
".",
"views",
".",
"i18n",
"impor... | Adds a url to move nodes to this admin | [
"Adds",
"a",
"url",
"to",
"move",
"nodes",
"to",
"this",
"admin"
] | 8042ee939cb45394909237da447f8925e3cc6aa3 | https://github.com/django-treebeard/django-treebeard/blob/8042ee939cb45394909237da447f8925e3cc6aa3/treebeard/admin.py#L66-L87 |
232,453 | django-treebeard/django-treebeard | treebeard/forms.py | movenodeform_factory | def movenodeform_factory(model, form=MoveNodeForm, fields=None, exclude=None,
formfield_callback=None, widgets=None):
"""Dynamically build a MoveNodeForm subclass with the proper Meta.
:param Node model:
The subclass of :py:class:`Node` that will be handled
by the form.
:param form:
The form class that will be used as a base. By
default, :py:class:`MoveNodeForm` will be used.
:return: A :py:class:`MoveNodeForm` subclass
"""
_exclude = _get_exclude_for_model(model, exclude)
return django_modelform_factory(
model, form, fields, _exclude, formfield_callback, widgets) | python | def movenodeform_factory(model, form=MoveNodeForm, fields=None, exclude=None,
formfield_callback=None, widgets=None):
_exclude = _get_exclude_for_model(model, exclude)
return django_modelform_factory(
model, form, fields, _exclude, formfield_callback, widgets) | [
"def",
"movenodeform_factory",
"(",
"model",
",",
"form",
"=",
"MoveNodeForm",
",",
"fields",
"=",
"None",
",",
"exclude",
"=",
"None",
",",
"formfield_callback",
"=",
"None",
",",
"widgets",
"=",
"None",
")",
":",
"_exclude",
"=",
"_get_exclude_for_model",
... | Dynamically build a MoveNodeForm subclass with the proper Meta.
:param Node model:
The subclass of :py:class:`Node` that will be handled
by the form.
:param form:
The form class that will be used as a base. By
default, :py:class:`MoveNodeForm` will be used.
:return: A :py:class:`MoveNodeForm` subclass | [
"Dynamically",
"build",
"a",
"MoveNodeForm",
"subclass",
"with",
"the",
"proper",
"Meta",
"."
] | 8042ee939cb45394909237da447f8925e3cc6aa3 | https://github.com/django-treebeard/django-treebeard/blob/8042ee939cb45394909237da447f8925e3cc6aa3/treebeard/forms.py#L197-L215 |
232,454 | django-treebeard/django-treebeard | treebeard/forms.py | MoveNodeForm._clean_cleaned_data | def _clean_cleaned_data(self):
""" delete auxilary fields not belonging to node model """
reference_node_id = 0
if '_ref_node_id' in self.cleaned_data:
reference_node_id = self.cleaned_data['_ref_node_id']
del self.cleaned_data['_ref_node_id']
position_type = self.cleaned_data['_position']
del self.cleaned_data['_position']
return position_type, reference_node_id | python | def _clean_cleaned_data(self):
reference_node_id = 0
if '_ref_node_id' in self.cleaned_data:
reference_node_id = self.cleaned_data['_ref_node_id']
del self.cleaned_data['_ref_node_id']
position_type = self.cleaned_data['_position']
del self.cleaned_data['_position']
return position_type, reference_node_id | [
"def",
"_clean_cleaned_data",
"(",
"self",
")",
":",
"reference_node_id",
"=",
"0",
"if",
"'_ref_node_id'",
"in",
"self",
".",
"cleaned_data",
":",
"reference_node_id",
"=",
"self",
".",
"cleaned_data",
"[",
"'_ref_node_id'",
"]",
"del",
"self",
".",
"cleaned_da... | delete auxilary fields not belonging to node model | [
"delete",
"auxilary",
"fields",
"not",
"belonging",
"to",
"node",
"model"
] | 8042ee939cb45394909237da447f8925e3cc6aa3 | https://github.com/django-treebeard/django-treebeard/blob/8042ee939cb45394909237da447f8925e3cc6aa3/treebeard/forms.py#L120-L131 |
232,455 | django-treebeard/django-treebeard | treebeard/forms.py | MoveNodeForm.add_subtree | def add_subtree(cls, for_node, node, options):
""" Recursively build options tree. """
if cls.is_loop_safe(for_node, node):
options.append(
(node.pk,
mark_safe(cls.mk_indent(node.get_depth()) + escape(node))))
for subnode in node.get_children():
cls.add_subtree(for_node, subnode, options) | python | def add_subtree(cls, for_node, node, options):
if cls.is_loop_safe(for_node, node):
options.append(
(node.pk,
mark_safe(cls.mk_indent(node.get_depth()) + escape(node))))
for subnode in node.get_children():
cls.add_subtree(for_node, subnode, options) | [
"def",
"add_subtree",
"(",
"cls",
",",
"for_node",
",",
"node",
",",
"options",
")",
":",
"if",
"cls",
".",
"is_loop_safe",
"(",
"for_node",
",",
"node",
")",
":",
"options",
".",
"append",
"(",
"(",
"node",
".",
"pk",
",",
"mark_safe",
"(",
"cls",
... | Recursively build options tree. | [
"Recursively",
"build",
"options",
"tree",
"."
] | 8042ee939cb45394909237da447f8925e3cc6aa3 | https://github.com/django-treebeard/django-treebeard/blob/8042ee939cb45394909237da447f8925e3cc6aa3/treebeard/forms.py#L178-L185 |
232,456 | django-treebeard/django-treebeard | treebeard/forms.py | MoveNodeForm.mk_dropdown_tree | def mk_dropdown_tree(cls, model, for_node=None):
""" Creates a tree-like list of choices """
options = [(0, _('-- root --'))]
for node in model.get_root_nodes():
cls.add_subtree(for_node, node, options)
return options | python | def mk_dropdown_tree(cls, model, for_node=None):
options = [(0, _('-- root --'))]
for node in model.get_root_nodes():
cls.add_subtree(for_node, node, options)
return options | [
"def",
"mk_dropdown_tree",
"(",
"cls",
",",
"model",
",",
"for_node",
"=",
"None",
")",
":",
"options",
"=",
"[",
"(",
"0",
",",
"_",
"(",
"'-- root --'",
")",
")",
"]",
"for",
"node",
"in",
"model",
".",
"get_root_nodes",
"(",
")",
":",
"cls",
"."... | Creates a tree-like list of choices | [
"Creates",
"a",
"tree",
"-",
"like",
"list",
"of",
"choices"
] | 8042ee939cb45394909237da447f8925e3cc6aa3 | https://github.com/django-treebeard/django-treebeard/blob/8042ee939cb45394909237da447f8925e3cc6aa3/treebeard/forms.py#L188-L194 |
232,457 | django-treebeard/django-treebeard | treebeard/mp_tree.py | MP_MoveHandler.sanity_updates_after_move | def sanity_updates_after_move(self, oldpath, newpath):
"""
Updates the list of sql statements needed after moving nodes.
1. :attr:`depth` updates *ONLY* needed by mysql databases (*sigh*)
2. update the number of children of parent nodes
"""
if (
self.node_cls.get_database_vendor('write') == 'mysql' and
len(oldpath) != len(newpath)
):
# no words can describe how dumb mysql is
# we must update the depth of the branch in a different query
self.stmts.append(
self.get_mysql_update_depth_in_branch(newpath))
oldparentpath = self.node_cls._get_parent_path_from_path(oldpath)
newparentpath = self.node_cls._get_parent_path_from_path(newpath)
if (
(not oldparentpath and newparentpath) or
(oldparentpath and not newparentpath) or
(oldparentpath != newparentpath)
):
# node changed parent, updating count
if oldparentpath:
self.stmts.append(
self.get_sql_update_numchild(oldparentpath, 'dec'))
if newparentpath:
self.stmts.append(
self.get_sql_update_numchild(newparentpath, 'inc')) | python | def sanity_updates_after_move(self, oldpath, newpath):
if (
self.node_cls.get_database_vendor('write') == 'mysql' and
len(oldpath) != len(newpath)
):
# no words can describe how dumb mysql is
# we must update the depth of the branch in a different query
self.stmts.append(
self.get_mysql_update_depth_in_branch(newpath))
oldparentpath = self.node_cls._get_parent_path_from_path(oldpath)
newparentpath = self.node_cls._get_parent_path_from_path(newpath)
if (
(not oldparentpath and newparentpath) or
(oldparentpath and not newparentpath) or
(oldparentpath != newparentpath)
):
# node changed parent, updating count
if oldparentpath:
self.stmts.append(
self.get_sql_update_numchild(oldparentpath, 'dec'))
if newparentpath:
self.stmts.append(
self.get_sql_update_numchild(newparentpath, 'inc')) | [
"def",
"sanity_updates_after_move",
"(",
"self",
",",
"oldpath",
",",
"newpath",
")",
":",
"if",
"(",
"self",
".",
"node_cls",
".",
"get_database_vendor",
"(",
"'write'",
")",
"==",
"'mysql'",
"and",
"len",
"(",
"oldpath",
")",
"!=",
"len",
"(",
"newpath",... | Updates the list of sql statements needed after moving nodes.
1. :attr:`depth` updates *ONLY* needed by mysql databases (*sigh*)
2. update the number of children of parent nodes | [
"Updates",
"the",
"list",
"of",
"sql",
"statements",
"needed",
"after",
"moving",
"nodes",
"."
] | 8042ee939cb45394909237da447f8925e3cc6aa3 | https://github.com/django-treebeard/django-treebeard/blob/8042ee939cb45394909237da447f8925e3cc6aa3/treebeard/mp_tree.py#L511-L540 |
232,458 | django-treebeard/django-treebeard | treebeard/mp_tree.py | MP_Node.fix_tree | def fix_tree(cls, destructive=False):
"""
Solves some problems that can appear when transactions are not used and
a piece of code breaks, leaving the tree in an inconsistent state.
The problems this method solves are:
1. Nodes with an incorrect ``depth`` or ``numchild`` values due to
incorrect code and lack of database transactions.
2. "Holes" in the tree. This is normal if you move/delete nodes a
lot. Holes in a tree don't affect performance,
3. Incorrect ordering of nodes when ``node_order_by`` is enabled.
Ordering is enforced on *node insertion*, so if an attribute in
``node_order_by`` is modified after the node is inserted, the
tree ordering will be inconsistent.
:param destructive:
A boolean value. If True, a more agressive fix_tree method will be
attempted. If False (the default), it will use a safe (and fast!)
fix approach, but it will only solve the ``depth`` and
``numchild`` nodes, it won't fix the tree holes or broken path
ordering.
.. warning::
Currently what the ``destructive`` method does is:
1. Backup the tree with :meth:`dump_data`
2. Remove all nodes in the tree.
3. Restore the tree with :meth:`load_data`
So, even when the primary keys of your nodes will be preserved,
this method isn't foreign-key friendly. That needs complex
in-place tree reordering, not available at the moment (hint:
patches are welcome).
"""
cls = get_result_class(cls)
vendor = cls.get_database_vendor('write')
if destructive:
dump = cls.dump_bulk(None, True)
cls.objects.all().delete()
cls.load_bulk(dump, None, True)
else:
cursor = cls._get_database_cursor('write')
# fix the depth field
# we need the WHERE to speed up postgres
sql = (
"UPDATE %s "
"SET depth=" + sql_length("path", vendor=vendor) + "/%%s "
"WHERE depth!=" + sql_length("path", vendor=vendor) + "/%%s"
) % (connection.ops.quote_name(cls._meta.db_table), )
vals = [cls.steplen, cls.steplen]
cursor.execute(sql, vals)
# fix the numchild field
vals = ['_' * cls.steplen]
# the cake and sql portability are a lie
if cls.get_database_vendor('read') == 'mysql':
sql = (
"SELECT tbn1.path, tbn1.numchild, ("
"SELECT COUNT(1) "
"FROM %(table)s AS tbn2 "
"WHERE tbn2.path LIKE " +
sql_concat("tbn1.path", "%%s", vendor=vendor) + ") AS real_numchild "
"FROM %(table)s AS tbn1 "
"HAVING tbn1.numchild != real_numchild"
) % {'table': connection.ops.quote_name(cls._meta.db_table)}
else:
subquery = "(SELECT COUNT(1) FROM %(table)s AS tbn2"\
" WHERE tbn2.path LIKE " + sql_concat("tbn1.path", "%%s", vendor=vendor) + ")"
sql = ("SELECT tbn1.path, tbn1.numchild, " + subquery +
" FROM %(table)s AS tbn1 WHERE tbn1.numchild != " +
subquery)
sql = sql % {
'table': connection.ops.quote_name(cls._meta.db_table)}
# we include the subquery twice
vals *= 2
cursor.execute(sql, vals)
sql = "UPDATE %(table)s "\
"SET numchild=%%s "\
"WHERE path=%%s" % {
'table': connection.ops.quote_name(cls._meta.db_table)}
for node_data in cursor.fetchall():
vals = [node_data[2], node_data[0]]
cursor.execute(sql, vals) | python | def fix_tree(cls, destructive=False):
cls = get_result_class(cls)
vendor = cls.get_database_vendor('write')
if destructive:
dump = cls.dump_bulk(None, True)
cls.objects.all().delete()
cls.load_bulk(dump, None, True)
else:
cursor = cls._get_database_cursor('write')
# fix the depth field
# we need the WHERE to speed up postgres
sql = (
"UPDATE %s "
"SET depth=" + sql_length("path", vendor=vendor) + "/%%s "
"WHERE depth!=" + sql_length("path", vendor=vendor) + "/%%s"
) % (connection.ops.quote_name(cls._meta.db_table), )
vals = [cls.steplen, cls.steplen]
cursor.execute(sql, vals)
# fix the numchild field
vals = ['_' * cls.steplen]
# the cake and sql portability are a lie
if cls.get_database_vendor('read') == 'mysql':
sql = (
"SELECT tbn1.path, tbn1.numchild, ("
"SELECT COUNT(1) "
"FROM %(table)s AS tbn2 "
"WHERE tbn2.path LIKE " +
sql_concat("tbn1.path", "%%s", vendor=vendor) + ") AS real_numchild "
"FROM %(table)s AS tbn1 "
"HAVING tbn1.numchild != real_numchild"
) % {'table': connection.ops.quote_name(cls._meta.db_table)}
else:
subquery = "(SELECT COUNT(1) FROM %(table)s AS tbn2"\
" WHERE tbn2.path LIKE " + sql_concat("tbn1.path", "%%s", vendor=vendor) + ")"
sql = ("SELECT tbn1.path, tbn1.numchild, " + subquery +
" FROM %(table)s AS tbn1 WHERE tbn1.numchild != " +
subquery)
sql = sql % {
'table': connection.ops.quote_name(cls._meta.db_table)}
# we include the subquery twice
vals *= 2
cursor.execute(sql, vals)
sql = "UPDATE %(table)s "\
"SET numchild=%%s "\
"WHERE path=%%s" % {
'table': connection.ops.quote_name(cls._meta.db_table)}
for node_data in cursor.fetchall():
vals = [node_data[2], node_data[0]]
cursor.execute(sql, vals) | [
"def",
"fix_tree",
"(",
"cls",
",",
"destructive",
"=",
"False",
")",
":",
"cls",
"=",
"get_result_class",
"(",
"cls",
")",
"vendor",
"=",
"cls",
".",
"get_database_vendor",
"(",
"'write'",
")",
"if",
"destructive",
":",
"dump",
"=",
"cls",
".",
"dump_bu... | Solves some problems that can appear when transactions are not used and
a piece of code breaks, leaving the tree in an inconsistent state.
The problems this method solves are:
1. Nodes with an incorrect ``depth`` or ``numchild`` values due to
incorrect code and lack of database transactions.
2. "Holes" in the tree. This is normal if you move/delete nodes a
lot. Holes in a tree don't affect performance,
3. Incorrect ordering of nodes when ``node_order_by`` is enabled.
Ordering is enforced on *node insertion*, so if an attribute in
``node_order_by`` is modified after the node is inserted, the
tree ordering will be inconsistent.
:param destructive:
A boolean value. If True, a more agressive fix_tree method will be
attempted. If False (the default), it will use a safe (and fast!)
fix approach, but it will only solve the ``depth`` and
``numchild`` nodes, it won't fix the tree holes or broken path
ordering.
.. warning::
Currently what the ``destructive`` method does is:
1. Backup the tree with :meth:`dump_data`
2. Remove all nodes in the tree.
3. Restore the tree with :meth:`load_data`
So, even when the primary keys of your nodes will be preserved,
this method isn't foreign-key friendly. That needs complex
in-place tree reordering, not available at the moment (hint:
patches are welcome). | [
"Solves",
"some",
"problems",
"that",
"can",
"appear",
"when",
"transactions",
"are",
"not",
"used",
"and",
"a",
"piece",
"of",
"code",
"breaks",
"leaving",
"the",
"tree",
"in",
"an",
"inconsistent",
"state",
"."
] | 8042ee939cb45394909237da447f8925e3cc6aa3 | https://github.com/django-treebeard/django-treebeard/blob/8042ee939cb45394909237da447f8925e3cc6aa3/treebeard/mp_tree.py#L730-L817 |
232,459 | django-treebeard/django-treebeard | treebeard/mp_tree.py | MP_Node._get_path | def _get_path(cls, path, depth, newstep):
"""
Builds a path given some values
:param path: the base path
:param depth: the depth of the node
:param newstep: the value (integer) of the new step
"""
parentpath = cls._get_basepath(path, depth - 1)
key = cls._int2str(newstep)
return '{0}{1}{2}'.format(
parentpath,
cls.alphabet[0] * (cls.steplen - len(key)),
key
) | python | def _get_path(cls, path, depth, newstep):
parentpath = cls._get_basepath(path, depth - 1)
key = cls._int2str(newstep)
return '{0}{1}{2}'.format(
parentpath,
cls.alphabet[0] * (cls.steplen - len(key)),
key
) | [
"def",
"_get_path",
"(",
"cls",
",",
"path",
",",
"depth",
",",
"newstep",
")",
":",
"parentpath",
"=",
"cls",
".",
"_get_basepath",
"(",
"path",
",",
"depth",
"-",
"1",
")",
"key",
"=",
"cls",
".",
"_int2str",
"(",
"newstep",
")",
"return",
"'{0}{1}... | Builds a path given some values
:param path: the base path
:param depth: the depth of the node
:param newstep: the value (integer) of the new step | [
"Builds",
"a",
"path",
"given",
"some",
"values"
] | 8042ee939cb45394909237da447f8925e3cc6aa3 | https://github.com/django-treebeard/django-treebeard/blob/8042ee939cb45394909237da447f8925e3cc6aa3/treebeard/mp_tree.py#L1105-L1119 |
232,460 | django-treebeard/django-treebeard | treebeard/numconv.py | int2str | def int2str(num, radix=10, alphabet=BASE85):
"""helper function for quick base conversions from integers to strings"""
return NumConv(radix, alphabet).int2str(num) | python | def int2str(num, radix=10, alphabet=BASE85):
return NumConv(radix, alphabet).int2str(num) | [
"def",
"int2str",
"(",
"num",
",",
"radix",
"=",
"10",
",",
"alphabet",
"=",
"BASE85",
")",
":",
"return",
"NumConv",
"(",
"radix",
",",
"alphabet",
")",
".",
"int2str",
"(",
"num",
")"
] | helper function for quick base conversions from integers to strings | [
"helper",
"function",
"for",
"quick",
"base",
"conversions",
"from",
"integers",
"to",
"strings"
] | 8042ee939cb45394909237da447f8925e3cc6aa3 | https://github.com/django-treebeard/django-treebeard/blob/8042ee939cb45394909237da447f8925e3cc6aa3/treebeard/numconv.py#L108-L110 |
232,461 | django-treebeard/django-treebeard | treebeard/numconv.py | str2int | def str2int(num, radix=10, alphabet=BASE85):
"""helper function for quick base conversions from strings to integers"""
return NumConv(radix, alphabet).str2int(num) | python | def str2int(num, radix=10, alphabet=BASE85):
return NumConv(radix, alphabet).str2int(num) | [
"def",
"str2int",
"(",
"num",
",",
"radix",
"=",
"10",
",",
"alphabet",
"=",
"BASE85",
")",
":",
"return",
"NumConv",
"(",
"radix",
",",
"alphabet",
")",
".",
"str2int",
"(",
"num",
")"
] | helper function for quick base conversions from strings to integers | [
"helper",
"function",
"for",
"quick",
"base",
"conversions",
"from",
"strings",
"to",
"integers"
] | 8042ee939cb45394909237da447f8925e3cc6aa3 | https://github.com/django-treebeard/django-treebeard/blob/8042ee939cb45394909237da447f8925e3cc6aa3/treebeard/numconv.py#L113-L115 |
232,462 | django-treebeard/django-treebeard | treebeard/numconv.py | NumConv.int2str | def int2str(self, num):
"""Converts an integer into a string.
:param num: A numeric value to be converted to another base as a
string.
:rtype: string
:raise TypeError: when *num* isn't an integer
:raise ValueError: when *num* isn't positive
"""
if int(num) != num:
raise TypeError('number must be an integer')
if num < 0:
raise ValueError('number must be positive')
radix, alphabet = self.radix, self.alphabet
if radix in (8, 10, 16) and \
alphabet[:radix].lower() == BASE85[:radix].lower():
return ({8: '%o', 10: '%d', 16: '%x'}[radix] % num).upper()
ret = ''
while True:
ret = alphabet[num % radix] + ret
if num < radix:
break
num //= radix
return ret | python | def int2str(self, num):
if int(num) != num:
raise TypeError('number must be an integer')
if num < 0:
raise ValueError('number must be positive')
radix, alphabet = self.radix, self.alphabet
if radix in (8, 10, 16) and \
alphabet[:radix].lower() == BASE85[:radix].lower():
return ({8: '%o', 10: '%d', 16: '%x'}[radix] % num).upper()
ret = ''
while True:
ret = alphabet[num % radix] + ret
if num < radix:
break
num //= radix
return ret | [
"def",
"int2str",
"(",
"self",
",",
"num",
")",
":",
"if",
"int",
"(",
"num",
")",
"!=",
"num",
":",
"raise",
"TypeError",
"(",
"'number must be an integer'",
")",
"if",
"num",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'number must be positive'",
")",
... | Converts an integer into a string.
:param num: A numeric value to be converted to another base as a
string.
:rtype: string
:raise TypeError: when *num* isn't an integer
:raise ValueError: when *num* isn't positive | [
"Converts",
"an",
"integer",
"into",
"a",
"string",
"."
] | 8042ee939cb45394909237da447f8925e3cc6aa3 | https://github.com/django-treebeard/django-treebeard/blob/8042ee939cb45394909237da447f8925e3cc6aa3/treebeard/numconv.py#L56-L81 |
232,463 | django-treebeard/django-treebeard | treebeard/numconv.py | NumConv.str2int | def str2int(self, num):
"""Converts a string into an integer.
If possible, the built-in python conversion will be used for speed
purposes.
:param num: A string that will be converted to an integer.
:rtype: integer
:raise ValueError: when *num* is invalid
"""
radix, alphabet = self.radix, self.alphabet
if radix <= 36 and alphabet[:radix].lower() == BASE85[:radix].lower():
return int(num, radix)
ret = 0
lalphabet = alphabet[:radix]
for char in num:
if char not in lalphabet:
raise ValueError("invalid literal for radix2int() with radix "
"%d: '%s'" % (radix, num))
ret = ret * radix + self.cached_map[char]
return ret | python | def str2int(self, num):
radix, alphabet = self.radix, self.alphabet
if radix <= 36 and alphabet[:radix].lower() == BASE85[:radix].lower():
return int(num, radix)
ret = 0
lalphabet = alphabet[:radix]
for char in num:
if char not in lalphabet:
raise ValueError("invalid literal for radix2int() with radix "
"%d: '%s'" % (radix, num))
ret = ret * radix + self.cached_map[char]
return ret | [
"def",
"str2int",
"(",
"self",
",",
"num",
")",
":",
"radix",
",",
"alphabet",
"=",
"self",
".",
"radix",
",",
"self",
".",
"alphabet",
"if",
"radix",
"<=",
"36",
"and",
"alphabet",
"[",
":",
"radix",
"]",
".",
"lower",
"(",
")",
"==",
"BASE85",
... | Converts a string into an integer.
If possible, the built-in python conversion will be used for speed
purposes.
:param num: A string that will be converted to an integer.
:rtype: integer
:raise ValueError: when *num* is invalid | [
"Converts",
"a",
"string",
"into",
"an",
"integer",
"."
] | 8042ee939cb45394909237da447f8925e3cc6aa3 | https://github.com/django-treebeard/django-treebeard/blob/8042ee939cb45394909237da447f8925e3cc6aa3/treebeard/numconv.py#L83-L105 |
232,464 | django-treebeard/django-treebeard | treebeard/al_tree.py | AL_NodeManager.get_queryset | def get_queryset(self):
"""Sets the custom queryset as the default."""
if self.model.node_order_by:
order_by = ['parent'] + list(self.model.node_order_by)
else:
order_by = ['parent', 'sib_order']
return super(AL_NodeManager, self).get_queryset().order_by(*order_by) | python | def get_queryset(self):
if self.model.node_order_by:
order_by = ['parent'] + list(self.model.node_order_by)
else:
order_by = ['parent', 'sib_order']
return super(AL_NodeManager, self).get_queryset().order_by(*order_by) | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"if",
"self",
".",
"model",
".",
"node_order_by",
":",
"order_by",
"=",
"[",
"'parent'",
"]",
"+",
"list",
"(",
"self",
".",
"model",
".",
"node_order_by",
")",
"else",
":",
"order_by",
"=",
"[",
"'parent'"... | Sets the custom queryset as the default. | [
"Sets",
"the",
"custom",
"queryset",
"as",
"the",
"default",
"."
] | 8042ee939cb45394909237da447f8925e3cc6aa3 | https://github.com/django-treebeard/django-treebeard/blob/8042ee939cb45394909237da447f8925e3cc6aa3/treebeard/al_tree.py#L36-L42 |
232,465 | dmkoch/django-jsonfield | jsonfield/fields.py | JSONFieldBase.pre_init | def pre_init(self, value, obj):
"""Convert a string value to JSON only if it needs to be deserialized.
SubfieldBase metaclass has been modified to call this method instead of
to_python so that we can check the obj state and determine if it needs to be
deserialized"""
try:
if obj._state.adding:
# Make sure the primary key actually exists on the object before
# checking if it's empty. This is a special case for South datamigrations
# see: https://github.com/bradjasper/django-jsonfield/issues/52
if getattr(obj, "pk", None) is not None:
if isinstance(value, six.string_types):
try:
return json.loads(value, **self.load_kwargs)
except ValueError:
raise ValidationError(_("Enter valid JSON"))
except AttributeError:
# south fake meta class doesn't create proper attributes
# see this:
# https://github.com/bradjasper/django-jsonfield/issues/52
pass
return value | python | def pre_init(self, value, obj):
try:
if obj._state.adding:
# Make sure the primary key actually exists on the object before
# checking if it's empty. This is a special case for South datamigrations
# see: https://github.com/bradjasper/django-jsonfield/issues/52
if getattr(obj, "pk", None) is not None:
if isinstance(value, six.string_types):
try:
return json.loads(value, **self.load_kwargs)
except ValueError:
raise ValidationError(_("Enter valid JSON"))
except AttributeError:
# south fake meta class doesn't create proper attributes
# see this:
# https://github.com/bradjasper/django-jsonfield/issues/52
pass
return value | [
"def",
"pre_init",
"(",
"self",
",",
"value",
",",
"obj",
")",
":",
"try",
":",
"if",
"obj",
".",
"_state",
".",
"adding",
":",
"# Make sure the primary key actually exists on the object before",
"# checking if it's empty. This is a special case for South datamigrations",
"... | Convert a string value to JSON only if it needs to be deserialized.
SubfieldBase metaclass has been modified to call this method instead of
to_python so that we can check the obj state and determine if it needs to be
deserialized | [
"Convert",
"a",
"string",
"value",
"to",
"JSON",
"only",
"if",
"it",
"needs",
"to",
"be",
"deserialized",
"."
] | 19b62ed3c02674b2ee3d61353312ffa75be373c4 | https://github.com/dmkoch/django-jsonfield/blob/19b62ed3c02674b2ee3d61353312ffa75be373c4/jsonfield/fields.py#L68-L93 |
232,466 | klen/peewee_migrate | peewee_migrate/migrator.py | get_model | def get_model(method):
"""Convert string to model class."""
@wraps(method)
def wrapper(migrator, model, *args, **kwargs):
if isinstance(model, str):
return method(migrator, migrator.orm[model], *args, **kwargs)
return method(migrator, model, *args, **kwargs)
return wrapper | python | def get_model(method):
@wraps(method)
def wrapper(migrator, model, *args, **kwargs):
if isinstance(model, str):
return method(migrator, migrator.orm[model], *args, **kwargs)
return method(migrator, model, *args, **kwargs)
return wrapper | [
"def",
"get_model",
"(",
"method",
")",
":",
"@",
"wraps",
"(",
"method",
")",
"def",
"wrapper",
"(",
"migrator",
",",
"model",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"model",
",",
"str",
")",
":",
"return",
... | Convert string to model class. | [
"Convert",
"string",
"to",
"model",
"class",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/migrator.py#L99-L107 |
232,467 | klen/peewee_migrate | peewee_migrate/migrator.py | SchemaMigrator.from_database | def from_database(cls, database):
"""Initialize migrator by db."""
if isinstance(database, PostgresqlDatabase):
return PostgresqlMigrator(database)
if isinstance(database, SqliteDatabase):
return SqliteMigrator(database)
if isinstance(database, MySQLDatabase):
return MySQLMigrator(database)
return super(SchemaMigrator, cls).from_database(database) | python | def from_database(cls, database):
if isinstance(database, PostgresqlDatabase):
return PostgresqlMigrator(database)
if isinstance(database, SqliteDatabase):
return SqliteMigrator(database)
if isinstance(database, MySQLDatabase):
return MySQLMigrator(database)
return super(SchemaMigrator, cls).from_database(database) | [
"def",
"from_database",
"(",
"cls",
",",
"database",
")",
":",
"if",
"isinstance",
"(",
"database",
",",
"PostgresqlDatabase",
")",
":",
"return",
"PostgresqlMigrator",
"(",
"database",
")",
"if",
"isinstance",
"(",
"database",
",",
"SqliteDatabase",
")",
":",... | Initialize migrator by db. | [
"Initialize",
"migrator",
"by",
"db",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/migrator.py#L20-L28 |
232,468 | klen/peewee_migrate | peewee_migrate/migrator.py | SchemaMigrator.change_column | def change_column(self, table, column_name, field):
"""Change column."""
operations = [self.alter_change_column(table, column_name, field)]
if not field.null:
operations.extend([self.add_not_null(table, column_name)])
return operations | python | def change_column(self, table, column_name, field):
operations = [self.alter_change_column(table, column_name, field)]
if not field.null:
operations.extend([self.add_not_null(table, column_name)])
return operations | [
"def",
"change_column",
"(",
"self",
",",
"table",
",",
"column_name",
",",
"field",
")",
":",
"operations",
"=",
"[",
"self",
".",
"alter_change_column",
"(",
"table",
",",
"column_name",
",",
"field",
")",
"]",
"if",
"not",
"field",
".",
"null",
":",
... | Change column. | [
"Change",
"column",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/migrator.py#L34-L39 |
232,469 | klen/peewee_migrate | peewee_migrate/migrator.py | SchemaMigrator.alter_add_column | def alter_add_column(self, table, column_name, field, **kwargs):
"""Fix fieldname for ForeignKeys."""
name = field.name
op = super(SchemaMigrator, self).alter_add_column(table, column_name, field, **kwargs)
if isinstance(field, pw.ForeignKeyField):
field.name = name
return op | python | def alter_add_column(self, table, column_name, field, **kwargs):
name = field.name
op = super(SchemaMigrator, self).alter_add_column(table, column_name, field, **kwargs)
if isinstance(field, pw.ForeignKeyField):
field.name = name
return op | [
"def",
"alter_add_column",
"(",
"self",
",",
"table",
",",
"column_name",
",",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
"=",
"field",
".",
"name",
"op",
"=",
"super",
"(",
"SchemaMigrator",
",",
"self",
")",
".",
"alter_add_column",
"(",
"ta... | Fix fieldname for ForeignKeys. | [
"Fix",
"fieldname",
"for",
"ForeignKeys",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/migrator.py#L54-L60 |
232,470 | klen/peewee_migrate | peewee_migrate/migrator.py | Migrator.run | def run(self):
"""Run operations."""
for op in self.ops:
if isinstance(op, Operation):
LOGGER.info("%s %s", op.method, op.args)
op.run()
else:
op()
self.clean() | python | def run(self):
for op in self.ops:
if isinstance(op, Operation):
LOGGER.info("%s %s", op.method, op.args)
op.run()
else:
op()
self.clean() | [
"def",
"run",
"(",
"self",
")",
":",
"for",
"op",
"in",
"self",
".",
"ops",
":",
"if",
"isinstance",
"(",
"op",
",",
"Operation",
")",
":",
"LOGGER",
".",
"info",
"(",
"\"%s %s\"",
",",
"op",
".",
"method",
",",
"op",
".",
"args",
")",
"op",
".... | Run operations. | [
"Run",
"operations",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/migrator.py#L124-L132 |
232,471 | klen/peewee_migrate | peewee_migrate/migrator.py | Migrator.python | def python(self, func, *args, **kwargs):
"""Run python code."""
self.ops.append(lambda: func(*args, **kwargs)) | python | def python(self, func, *args, **kwargs):
self.ops.append(lambda: func(*args, **kwargs)) | [
"def",
"python",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"ops",
".",
"append",
"(",
"lambda",
":",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | Run python code. | [
"Run",
"python",
"code",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/migrator.py#L134-L136 |
232,472 | klen/peewee_migrate | peewee_migrate/migrator.py | Migrator.sql | def sql(self, sql, *params):
"""Execure raw SQL."""
self.ops.append(self.migrator.sql(sql, *params)) | python | def sql(self, sql, *params):
self.ops.append(self.migrator.sql(sql, *params)) | [
"def",
"sql",
"(",
"self",
",",
"sql",
",",
"*",
"params",
")",
":",
"self",
".",
"ops",
".",
"append",
"(",
"self",
".",
"migrator",
".",
"sql",
"(",
"sql",
",",
"*",
"params",
")",
")"
] | Execure raw SQL. | [
"Execure",
"raw",
"SQL",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/migrator.py#L138-L140 |
232,473 | klen/peewee_migrate | peewee_migrate/migrator.py | Migrator.create_table | def create_table(self, model):
"""Create model and table in database.
>> migrator.create_table(model)
"""
self.orm[model._meta.table_name] = model
model._meta.database = self.database
self.ops.append(model.create_table)
return model | python | def create_table(self, model):
self.orm[model._meta.table_name] = model
model._meta.database = self.database
self.ops.append(model.create_table)
return model | [
"def",
"create_table",
"(",
"self",
",",
"model",
")",
":",
"self",
".",
"orm",
"[",
"model",
".",
"_meta",
".",
"table_name",
"]",
"=",
"model",
"model",
".",
"_meta",
".",
"database",
"=",
"self",
".",
"database",
"self",
".",
"ops",
".",
"append",... | Create model and table in database.
>> migrator.create_table(model) | [
"Create",
"model",
"and",
"table",
"in",
"database",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/migrator.py#L146-L154 |
232,474 | klen/peewee_migrate | peewee_migrate/migrator.py | Migrator.drop_table | def drop_table(self, model, cascade=True):
"""Drop model and table from database.
>> migrator.drop_table(model, cascade=True)
"""
del self.orm[model._meta.table_name]
self.ops.append(self.migrator.drop_table(model, cascade)) | python | def drop_table(self, model, cascade=True):
del self.orm[model._meta.table_name]
self.ops.append(self.migrator.drop_table(model, cascade)) | [
"def",
"drop_table",
"(",
"self",
",",
"model",
",",
"cascade",
"=",
"True",
")",
":",
"del",
"self",
".",
"orm",
"[",
"model",
".",
"_meta",
".",
"table_name",
"]",
"self",
".",
"ops",
".",
"append",
"(",
"self",
".",
"migrator",
".",
"drop_table",
... | Drop model and table from database.
>> migrator.drop_table(model, cascade=True) | [
"Drop",
"model",
"and",
"table",
"from",
"database",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/migrator.py#L159-L165 |
232,475 | klen/peewee_migrate | peewee_migrate/migrator.py | Migrator.add_columns | def add_columns(self, model, **fields):
"""Create new fields."""
for name, field in fields.items():
model._meta.add_field(name, field)
self.ops.append(self.migrator.add_column(
model._meta.table_name, field.column_name, field))
if field.unique:
self.ops.append(self.migrator.add_index(
model._meta.table_name, (field.column_name,), unique=True))
return model | python | def add_columns(self, model, **fields):
for name, field in fields.items():
model._meta.add_field(name, field)
self.ops.append(self.migrator.add_column(
model._meta.table_name, field.column_name, field))
if field.unique:
self.ops.append(self.migrator.add_index(
model._meta.table_name, (field.column_name,), unique=True))
return model | [
"def",
"add_columns",
"(",
"self",
",",
"model",
",",
"*",
"*",
"fields",
")",
":",
"for",
"name",
",",
"field",
"in",
"fields",
".",
"items",
"(",
")",
":",
"model",
".",
"_meta",
".",
"add_field",
"(",
"name",
",",
"field",
")",
"self",
".",
"o... | Create new fields. | [
"Create",
"new",
"fields",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/migrator.py#L170-L179 |
232,476 | klen/peewee_migrate | peewee_migrate/migrator.py | Migrator.change_columns | def change_columns(self, model, **fields):
"""Change fields."""
for name, field in fields.items():
old_field = model._meta.fields.get(name, field)
old_column_name = old_field and old_field.column_name
model._meta.add_field(name, field)
if isinstance(old_field, pw.ForeignKeyField):
self.ops.append(self.migrator.drop_foreign_key_constraint(
model._meta.table_name, old_column_name))
if old_column_name != field.column_name:
self.ops.append(
self.migrator.rename_column(
model._meta.table_name, old_column_name, field.column_name))
if isinstance(field, pw.ForeignKeyField):
on_delete = field.on_delete if field.on_delete else 'RESTRICT'
on_update = field.on_update if field.on_update else 'RESTRICT'
self.ops.append(self.migrator.add_foreign_key_constraint(
model._meta.table_name, field.column_name,
field.rel_model._meta.table_name, field.rel_field.name,
on_delete, on_update))
continue
self.ops.append(self.migrator.change_column(
model._meta.table_name, field.column_name, field))
if field.unique == old_field.unique:
continue
if field.unique:
index = (field.column_name,), field.unique
self.ops.append(self.migrator.add_index(model._meta.table_name, *index))
model._meta.indexes.append(index)
else:
index = (field.column_name,), old_field.unique
self.ops.append(self.migrator.drop_index(model._meta.table_name, *index))
model._meta.indexes.remove(index)
return model | python | def change_columns(self, model, **fields):
for name, field in fields.items():
old_field = model._meta.fields.get(name, field)
old_column_name = old_field and old_field.column_name
model._meta.add_field(name, field)
if isinstance(old_field, pw.ForeignKeyField):
self.ops.append(self.migrator.drop_foreign_key_constraint(
model._meta.table_name, old_column_name))
if old_column_name != field.column_name:
self.ops.append(
self.migrator.rename_column(
model._meta.table_name, old_column_name, field.column_name))
if isinstance(field, pw.ForeignKeyField):
on_delete = field.on_delete if field.on_delete else 'RESTRICT'
on_update = field.on_update if field.on_update else 'RESTRICT'
self.ops.append(self.migrator.add_foreign_key_constraint(
model._meta.table_name, field.column_name,
field.rel_model._meta.table_name, field.rel_field.name,
on_delete, on_update))
continue
self.ops.append(self.migrator.change_column(
model._meta.table_name, field.column_name, field))
if field.unique == old_field.unique:
continue
if field.unique:
index = (field.column_name,), field.unique
self.ops.append(self.migrator.add_index(model._meta.table_name, *index))
model._meta.indexes.append(index)
else:
index = (field.column_name,), old_field.unique
self.ops.append(self.migrator.drop_index(model._meta.table_name, *index))
model._meta.indexes.remove(index)
return model | [
"def",
"change_columns",
"(",
"self",
",",
"model",
",",
"*",
"*",
"fields",
")",
":",
"for",
"name",
",",
"field",
"in",
"fields",
".",
"items",
"(",
")",
":",
"old_field",
"=",
"model",
".",
"_meta",
".",
"fields",
".",
"get",
"(",
"name",
",",
... | Change fields. | [
"Change",
"fields",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/migrator.py#L184-L225 |
232,477 | klen/peewee_migrate | peewee_migrate/migrator.py | Migrator.drop_columns | def drop_columns(self, model, *names, **kwargs):
"""Remove fields from model."""
fields = [field for field in model._meta.fields.values() if field.name in names]
cascade = kwargs.pop('cascade', True)
for field in fields:
self.__del_field__(model, field)
if field.unique:
index_name = make_index_name(model._meta.table_name, [field.column_name])
self.ops.append(self.migrator.drop_index(model._meta.table_name, index_name))
self.ops.append(
self.migrator.drop_column(
model._meta.table_name, field.column_name, cascade=cascade))
return model | python | def drop_columns(self, model, *names, **kwargs):
fields = [field for field in model._meta.fields.values() if field.name in names]
cascade = kwargs.pop('cascade', True)
for field in fields:
self.__del_field__(model, field)
if field.unique:
index_name = make_index_name(model._meta.table_name, [field.column_name])
self.ops.append(self.migrator.drop_index(model._meta.table_name, index_name))
self.ops.append(
self.migrator.drop_column(
model._meta.table_name, field.column_name, cascade=cascade))
return model | [
"def",
"drop_columns",
"(",
"self",
",",
"model",
",",
"*",
"names",
",",
"*",
"*",
"kwargs",
")",
":",
"fields",
"=",
"[",
"field",
"for",
"field",
"in",
"model",
".",
"_meta",
".",
"fields",
".",
"values",
"(",
")",
"if",
"field",
".",
"name",
... | Remove fields from model. | [
"Remove",
"fields",
"from",
"model",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/migrator.py#L230-L242 |
232,478 | klen/peewee_migrate | peewee_migrate/migrator.py | Migrator.rename_column | def rename_column(self, model, old_name, new_name):
"""Rename field in model."""
field = model._meta.fields[old_name]
if isinstance(field, pw.ForeignKeyField):
old_name = field.column_name
self.__del_field__(model, field)
field.name = field.column_name = new_name
model._meta.add_field(new_name, field)
if isinstance(field, pw.ForeignKeyField):
field.column_name = new_name = field.column_name + '_id'
self.ops.append(self.migrator.rename_column(model._meta.table_name, old_name, new_name))
return model | python | def rename_column(self, model, old_name, new_name):
field = model._meta.fields[old_name]
if isinstance(field, pw.ForeignKeyField):
old_name = field.column_name
self.__del_field__(model, field)
field.name = field.column_name = new_name
model._meta.add_field(new_name, field)
if isinstance(field, pw.ForeignKeyField):
field.column_name = new_name = field.column_name + '_id'
self.ops.append(self.migrator.rename_column(model._meta.table_name, old_name, new_name))
return model | [
"def",
"rename_column",
"(",
"self",
",",
"model",
",",
"old_name",
",",
"new_name",
")",
":",
"field",
"=",
"model",
".",
"_meta",
".",
"fields",
"[",
"old_name",
"]",
"if",
"isinstance",
"(",
"field",
",",
"pw",
".",
"ForeignKeyField",
")",
":",
"old... | Rename field in model. | [
"Rename",
"field",
"in",
"model",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/migrator.py#L258-L269 |
232,479 | klen/peewee_migrate | peewee_migrate/migrator.py | Migrator.rename_table | def rename_table(self, model, new_name):
"""Rename table in database."""
del self.orm[model._meta.table_name]
model._meta.table_name = new_name
self.orm[model._meta.table_name] = model
self.ops.append(self.migrator.rename_table(model._meta.table_name, new_name))
return model | python | def rename_table(self, model, new_name):
del self.orm[model._meta.table_name]
model._meta.table_name = new_name
self.orm[model._meta.table_name] = model
self.ops.append(self.migrator.rename_table(model._meta.table_name, new_name))
return model | [
"def",
"rename_table",
"(",
"self",
",",
"model",
",",
"new_name",
")",
":",
"del",
"self",
".",
"orm",
"[",
"model",
".",
"_meta",
".",
"table_name",
"]",
"model",
".",
"_meta",
".",
"table_name",
"=",
"new_name",
"self",
".",
"orm",
"[",
"model",
"... | Rename table in database. | [
"Rename",
"table",
"in",
"database",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/migrator.py#L274-L280 |
232,480 | klen/peewee_migrate | peewee_migrate/migrator.py | Migrator.add_index | def add_index(self, model, *columns, **kwargs):
"""Create indexes."""
unique = kwargs.pop('unique', False)
model._meta.indexes.append((columns, unique))
columns_ = []
for col in columns:
field = model._meta.fields.get(col)
if len(columns) == 1:
field.unique = unique
field.index = not unique
if isinstance(field, pw.ForeignKeyField):
col = col + '_id'
columns_.append(col)
self.ops.append(self.migrator.add_index(model._meta.table_name, columns_, unique=unique))
return model | python | def add_index(self, model, *columns, **kwargs):
unique = kwargs.pop('unique', False)
model._meta.indexes.append((columns, unique))
columns_ = []
for col in columns:
field = model._meta.fields.get(col)
if len(columns) == 1:
field.unique = unique
field.index = not unique
if isinstance(field, pw.ForeignKeyField):
col = col + '_id'
columns_.append(col)
self.ops.append(self.migrator.add_index(model._meta.table_name, columns_, unique=unique))
return model | [
"def",
"add_index",
"(",
"self",
",",
"model",
",",
"*",
"columns",
",",
"*",
"*",
"kwargs",
")",
":",
"unique",
"=",
"kwargs",
".",
"pop",
"(",
"'unique'",
",",
"False",
")",
"model",
".",
"_meta",
".",
"indexes",
".",
"append",
"(",
"(",
"columns... | Create indexes. | [
"Create",
"indexes",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/migrator.py#L283-L300 |
232,481 | klen/peewee_migrate | peewee_migrate/migrator.py | Migrator.drop_index | def drop_index(self, model, *columns):
"""Drop indexes."""
columns_ = []
for col in columns:
field = model._meta.fields.get(col)
if not field:
continue
if len(columns) == 1:
field.unique = field.index = False
if isinstance(field, pw.ForeignKeyField):
col = col + '_id'
columns_.append(col)
index_name = make_index_name(model._meta.table_name, columns_)
model._meta.indexes = [(cols, _) for (cols, _) in model._meta.indexes if columns != cols]
self.ops.append(self.migrator.drop_index(model._meta.table_name, index_name))
return model | python | def drop_index(self, model, *columns):
columns_ = []
for col in columns:
field = model._meta.fields.get(col)
if not field:
continue
if len(columns) == 1:
field.unique = field.index = False
if isinstance(field, pw.ForeignKeyField):
col = col + '_id'
columns_.append(col)
index_name = make_index_name(model._meta.table_name, columns_)
model._meta.indexes = [(cols, _) for (cols, _) in model._meta.indexes if columns != cols]
self.ops.append(self.migrator.drop_index(model._meta.table_name, index_name))
return model | [
"def",
"drop_index",
"(",
"self",
",",
"model",
",",
"*",
"columns",
")",
":",
"columns_",
"=",
"[",
"]",
"for",
"col",
"in",
"columns",
":",
"field",
"=",
"model",
".",
"_meta",
".",
"fields",
".",
"get",
"(",
"col",
")",
"if",
"not",
"field",
"... | Drop indexes. | [
"Drop",
"indexes",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/migrator.py#L303-L320 |
232,482 | klen/peewee_migrate | peewee_migrate/migrator.py | Migrator.add_not_null | def add_not_null(self, model, *names):
"""Add not null."""
for name in names:
field = model._meta.fields[name]
field.null = False
self.ops.append(self.migrator.add_not_null(model._meta.table_name, field.column_name))
return model | python | def add_not_null(self, model, *names):
for name in names:
field = model._meta.fields[name]
field.null = False
self.ops.append(self.migrator.add_not_null(model._meta.table_name, field.column_name))
return model | [
"def",
"add_not_null",
"(",
"self",
",",
"model",
",",
"*",
"names",
")",
":",
"for",
"name",
"in",
"names",
":",
"field",
"=",
"model",
".",
"_meta",
".",
"fields",
"[",
"name",
"]",
"field",
".",
"null",
"=",
"False",
"self",
".",
"ops",
".",
"... | Add not null. | [
"Add",
"not",
"null",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/migrator.py#L323-L329 |
232,483 | klen/peewee_migrate | peewee_migrate/migrator.py | Migrator.drop_not_null | def drop_not_null(self, model, *names):
"""Drop not null."""
for name in names:
field = model._meta.fields[name]
field.null = True
self.ops.append(self.migrator.drop_not_null(model._meta.table_name, field.column_name))
return model | python | def drop_not_null(self, model, *names):
for name in names:
field = model._meta.fields[name]
field.null = True
self.ops.append(self.migrator.drop_not_null(model._meta.table_name, field.column_name))
return model | [
"def",
"drop_not_null",
"(",
"self",
",",
"model",
",",
"*",
"names",
")",
":",
"for",
"name",
"in",
"names",
":",
"field",
"=",
"model",
".",
"_meta",
".",
"fields",
"[",
"name",
"]",
"field",
".",
"null",
"=",
"True",
"self",
".",
"ops",
".",
"... | Drop not null. | [
"Drop",
"not",
"null",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/migrator.py#L332-L338 |
232,484 | klen/peewee_migrate | peewee_migrate/migrator.py | Migrator.add_default | def add_default(self, model, name, default):
"""Add default."""
field = model._meta.fields[name]
model._meta.defaults[field] = field.default = default
self.ops.append(self.migrator.apply_default(model._meta.table_name, name, field))
return model | python | def add_default(self, model, name, default):
field = model._meta.fields[name]
model._meta.defaults[field] = field.default = default
self.ops.append(self.migrator.apply_default(model._meta.table_name, name, field))
return model | [
"def",
"add_default",
"(",
"self",
",",
"model",
",",
"name",
",",
"default",
")",
":",
"field",
"=",
"model",
".",
"_meta",
".",
"fields",
"[",
"name",
"]",
"model",
".",
"_meta",
".",
"defaults",
"[",
"field",
"]",
"=",
"field",
".",
"default",
"... | Add default. | [
"Add",
"default",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/migrator.py#L341-L346 |
232,485 | klen/peewee_migrate | peewee_migrate/cli.py | migrate | def migrate(name=None, database=None, directory=None, verbose=None, fake=False):
"""Migrate database."""
router = get_router(directory, database, verbose)
migrations = router.run(name, fake=fake)
if migrations:
click.echo('Migrations completed: %s' % ', '.join(migrations)) | python | def migrate(name=None, database=None, directory=None, verbose=None, fake=False):
router = get_router(directory, database, verbose)
migrations = router.run(name, fake=fake)
if migrations:
click.echo('Migrations completed: %s' % ', '.join(migrations)) | [
"def",
"migrate",
"(",
"name",
"=",
"None",
",",
"database",
"=",
"None",
",",
"directory",
"=",
"None",
",",
"verbose",
"=",
"None",
",",
"fake",
"=",
"False",
")",
":",
"router",
"=",
"get_router",
"(",
"directory",
",",
"database",
",",
"verbose",
... | Migrate database. | [
"Migrate",
"database",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/cli.py#L60-L65 |
232,486 | klen/peewee_migrate | peewee_migrate/cli.py | rollback | def rollback(name, database=None, directory=None, verbose=None):
"""Rollback a migration with given name."""
router = get_router(directory, database, verbose)
router.rollback(name) | python | def rollback(name, database=None, directory=None, verbose=None):
router = get_router(directory, database, verbose)
router.rollback(name) | [
"def",
"rollback",
"(",
"name",
",",
"database",
"=",
"None",
",",
"directory",
"=",
"None",
",",
"verbose",
"=",
"None",
")",
":",
"router",
"=",
"get_router",
"(",
"directory",
",",
"database",
",",
"verbose",
")",
"router",
".",
"rollback",
"(",
"na... | Rollback a migration with given name. | [
"Rollback",
"a",
"migration",
"with",
"given",
"name",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/cli.py#L92-L95 |
232,487 | klen/peewee_migrate | peewee_migrate/router.py | load_models | def load_models(module):
"""Load models from given module."""
modules = _import_submodules(module)
return {m for module in modules for m in filter(
_check_model, (getattr(module, name) for name in dir(module))
)} | python | def load_models(module):
modules = _import_submodules(module)
return {m for module in modules for m in filter(
_check_model, (getattr(module, name) for name in dir(module))
)} | [
"def",
"load_models",
"(",
"module",
")",
":",
"modules",
"=",
"_import_submodules",
"(",
"module",
")",
"return",
"{",
"m",
"for",
"module",
"in",
"modules",
"for",
"m",
"in",
"filter",
"(",
"_check_model",
",",
"(",
"getattr",
"(",
"module",
",",
"name... | Load models from given module. | [
"Load",
"models",
"from",
"given",
"module",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/router.py#L266-L271 |
232,488 | klen/peewee_migrate | peewee_migrate/router.py | _check_model | def _check_model(obj, models=None):
"""Checks object if it's a peewee model and unique."""
return isinstance(obj, type) and issubclass(obj, pw.Model) and hasattr(obj, '_meta') | python | def _check_model(obj, models=None):
return isinstance(obj, type) and issubclass(obj, pw.Model) and hasattr(obj, '_meta') | [
"def",
"_check_model",
"(",
"obj",
",",
"models",
"=",
"None",
")",
":",
"return",
"isinstance",
"(",
"obj",
",",
"type",
")",
"and",
"issubclass",
"(",
"obj",
",",
"pw",
".",
"Model",
")",
"and",
"hasattr",
"(",
"obj",
",",
"'_meta'",
")"
] | Checks object if it's a peewee model and unique. | [
"Checks",
"object",
"if",
"it",
"s",
"a",
"peewee",
"model",
"and",
"unique",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/router.py#L295-L297 |
232,489 | klen/peewee_migrate | peewee_migrate/router.py | compile_migrations | def compile_migrations(migrator, models, reverse=False):
"""Compile migrations for given models."""
source = migrator.orm.values()
if reverse:
source, models = models, source
migrations = diff_many(models, source, migrator, reverse=reverse)
if not migrations:
return False
migrations = NEWLINE + NEWLINE.join('\n\n'.join(migrations).split('\n'))
return CLEAN_RE.sub('\n', migrations) | python | def compile_migrations(migrator, models, reverse=False):
source = migrator.orm.values()
if reverse:
source, models = models, source
migrations = diff_many(models, source, migrator, reverse=reverse)
if not migrations:
return False
migrations = NEWLINE + NEWLINE.join('\n\n'.join(migrations).split('\n'))
return CLEAN_RE.sub('\n', migrations) | [
"def",
"compile_migrations",
"(",
"migrator",
",",
"models",
",",
"reverse",
"=",
"False",
")",
":",
"source",
"=",
"migrator",
".",
"orm",
".",
"values",
"(",
")",
"if",
"reverse",
":",
"source",
",",
"models",
"=",
"models",
",",
"source",
"migrations"... | Compile migrations for given models. | [
"Compile",
"migrations",
"for",
"given",
"models",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/router.py#L300-L311 |
232,490 | klen/peewee_migrate | peewee_migrate/router.py | BaseRouter.model | def model(self):
"""Initialize and cache MigrationHistory model."""
MigrateHistory._meta.database = self.database
MigrateHistory._meta.table_name = self.migrate_table
MigrateHistory._meta.schema = self.schema
MigrateHistory.create_table(True)
return MigrateHistory | python | def model(self):
MigrateHistory._meta.database = self.database
MigrateHistory._meta.table_name = self.migrate_table
MigrateHistory._meta.schema = self.schema
MigrateHistory.create_table(True)
return MigrateHistory | [
"def",
"model",
"(",
"self",
")",
":",
"MigrateHistory",
".",
"_meta",
".",
"database",
"=",
"self",
".",
"database",
"MigrateHistory",
".",
"_meta",
".",
"table_name",
"=",
"self",
".",
"migrate_table",
"MigrateHistory",
".",
"_meta",
".",
"schema",
"=",
... | Initialize and cache MigrationHistory model. | [
"Initialize",
"and",
"cache",
"MigrationHistory",
"model",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/router.py#L41-L47 |
232,491 | klen/peewee_migrate | peewee_migrate/router.py | BaseRouter.done | def done(self):
"""Scan migrations in database."""
return [mm.name for mm in self.model.select().order_by(self.model.id)] | python | def done(self):
return [mm.name for mm in self.model.select().order_by(self.model.id)] | [
"def",
"done",
"(",
"self",
")",
":",
"return",
"[",
"mm",
".",
"name",
"for",
"mm",
"in",
"self",
".",
"model",
".",
"select",
"(",
")",
".",
"order_by",
"(",
"self",
".",
"model",
".",
"id",
")",
"]"
] | Scan migrations in database. | [
"Scan",
"migrations",
"in",
"database",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/router.py#L54-L56 |
232,492 | klen/peewee_migrate | peewee_migrate/router.py | BaseRouter.diff | def diff(self):
"""Calculate difference between fs and db."""
done = set(self.done)
return [name for name in self.todo if name not in done] | python | def diff(self):
done = set(self.done)
return [name for name in self.todo if name not in done] | [
"def",
"diff",
"(",
"self",
")",
":",
"done",
"=",
"set",
"(",
"self",
".",
"done",
")",
"return",
"[",
"name",
"for",
"name",
"in",
"self",
".",
"todo",
"if",
"name",
"not",
"in",
"done",
"]"
] | Calculate difference between fs and db. | [
"Calculate",
"difference",
"between",
"fs",
"and",
"db",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/router.py#L59-L62 |
232,493 | klen/peewee_migrate | peewee_migrate/router.py | BaseRouter.migrator | def migrator(self):
"""Create migrator and setup it with fake migrations."""
migrator = Migrator(self.database)
for name in self.done:
self.run_one(name, migrator)
return migrator | python | def migrator(self):
migrator = Migrator(self.database)
for name in self.done:
self.run_one(name, migrator)
return migrator | [
"def",
"migrator",
"(",
"self",
")",
":",
"migrator",
"=",
"Migrator",
"(",
"self",
".",
"database",
")",
"for",
"name",
"in",
"self",
".",
"done",
":",
"self",
".",
"run_one",
"(",
"name",
",",
"migrator",
")",
"return",
"migrator"
] | Create migrator and setup it with fake migrations. | [
"Create",
"migrator",
"and",
"setup",
"it",
"with",
"fake",
"migrations",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/router.py#L65-L70 |
232,494 | klen/peewee_migrate | peewee_migrate/router.py | Router.todo | def todo(self):
"""Scan migrations in file system."""
if not os.path.exists(self.migrate_dir):
self.logger.warn('Migration directory: %s does not exist.', self.migrate_dir)
os.makedirs(self.migrate_dir)
return sorted(f[:-3] for f in os.listdir(self.migrate_dir) if self.filemask.match(f)) | python | def todo(self):
if not os.path.exists(self.migrate_dir):
self.logger.warn('Migration directory: %s does not exist.', self.migrate_dir)
os.makedirs(self.migrate_dir)
return sorted(f[:-3] for f in os.listdir(self.migrate_dir) if self.filemask.match(f)) | [
"def",
"todo",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"migrate_dir",
")",
":",
"self",
".",
"logger",
".",
"warn",
"(",
"'Migration directory: %s does not exist.'",
",",
"self",
".",
"migrate_dir",
")",
"o... | Scan migrations in file system. | [
"Scan",
"migrations",
"in",
"file",
"system",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/router.py#L211-L216 |
232,495 | klen/peewee_migrate | peewee_migrate/router.py | Router.read | def read(self, name):
"""Read migration from file."""
call_params = dict()
if os.name == 'nt' and sys.version_info >= (3, 0):
# if system is windows - force utf-8 encoding
call_params['encoding'] = 'utf-8'
with open(os.path.join(self.migrate_dir, name + '.py'), **call_params) as f:
code = f.read()
scope = {}
exec_in(code, scope)
return scope.get('migrate', VOID), scope.get('rollback', VOID) | python | def read(self, name):
call_params = dict()
if os.name == 'nt' and sys.version_info >= (3, 0):
# if system is windows - force utf-8 encoding
call_params['encoding'] = 'utf-8'
with open(os.path.join(self.migrate_dir, name + '.py'), **call_params) as f:
code = f.read()
scope = {}
exec_in(code, scope)
return scope.get('migrate', VOID), scope.get('rollback', VOID) | [
"def",
"read",
"(",
"self",
",",
"name",
")",
":",
"call_params",
"=",
"dict",
"(",
")",
"if",
"os",
".",
"name",
"==",
"'nt'",
"and",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"0",
")",
":",
"# if system is windows - force utf-8 encoding",
"call_... | Read migration from file. | [
"Read",
"migration",
"from",
"file",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/router.py#L231-L241 |
232,496 | klen/peewee_migrate | peewee_migrate/router.py | Router.clear | def clear(self):
"""Remove migrations from fs."""
super(Router, self).clear()
for name in self.todo:
filename = os.path.join(self.migrate_dir, name + '.py')
os.remove(filename) | python | def clear(self):
super(Router, self).clear()
for name in self.todo:
filename = os.path.join(self.migrate_dir, name + '.py')
os.remove(filename) | [
"def",
"clear",
"(",
"self",
")",
":",
"super",
"(",
"Router",
",",
"self",
")",
".",
"clear",
"(",
")",
"for",
"name",
"in",
"self",
".",
"todo",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"migrate_dir",
",",
"name",... | Remove migrations from fs. | [
"Remove",
"migrations",
"from",
"fs",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/router.py#L243-L248 |
232,497 | klen/peewee_migrate | peewee_migrate/auto.py | diff_one | def diff_one(model1, model2, **kwargs):
"""Find difference between given peewee models."""
changes = []
fields1 = model1._meta.fields
fields2 = model2._meta.fields
# Add fields
names1 = set(fields1) - set(fields2)
if names1:
fields = [fields1[name] for name in names1]
changes.append(create_fields(model1, *fields, **kwargs))
# Drop fields
names2 = set(fields2) - set(fields1)
if names2:
changes.append(drop_fields(model1, *names2))
# Change fields
fields_ = []
nulls_ = []
indexes_ = []
for name in set(fields1) - names1 - names2:
field1, field2 = fields1[name], fields2[name]
diff = compare_fields(field1, field2)
null = diff.pop('null', None)
index = diff.pop('index', None)
if diff:
fields_.append(field1)
if null is not None:
nulls_.append((name, null))
if index is not None:
indexes_.append((name, index[0], index[1]))
if fields_:
changes.append(change_fields(model1, *fields_, **kwargs))
for name, null in nulls_:
changes.append(change_not_null(model1, name, null))
for name, index, unique in indexes_:
if index is True or unique is True:
if fields2[name].unique or fields2[name].index:
changes.append(drop_index(model1, name))
changes.append(add_index(model1, name, unique))
else:
changes.append(drop_index(model1, name))
return changes | python | def diff_one(model1, model2, **kwargs):
changes = []
fields1 = model1._meta.fields
fields2 = model2._meta.fields
# Add fields
names1 = set(fields1) - set(fields2)
if names1:
fields = [fields1[name] for name in names1]
changes.append(create_fields(model1, *fields, **kwargs))
# Drop fields
names2 = set(fields2) - set(fields1)
if names2:
changes.append(drop_fields(model1, *names2))
# Change fields
fields_ = []
nulls_ = []
indexes_ = []
for name in set(fields1) - names1 - names2:
field1, field2 = fields1[name], fields2[name]
diff = compare_fields(field1, field2)
null = diff.pop('null', None)
index = diff.pop('index', None)
if diff:
fields_.append(field1)
if null is not None:
nulls_.append((name, null))
if index is not None:
indexes_.append((name, index[0], index[1]))
if fields_:
changes.append(change_fields(model1, *fields_, **kwargs))
for name, null in nulls_:
changes.append(change_not_null(model1, name, null))
for name, index, unique in indexes_:
if index is True or unique is True:
if fields2[name].unique or fields2[name].index:
changes.append(drop_index(model1, name))
changes.append(add_index(model1, name, unique))
else:
changes.append(drop_index(model1, name))
return changes | [
"def",
"diff_one",
"(",
"model1",
",",
"model2",
",",
"*",
"*",
"kwargs",
")",
":",
"changes",
"=",
"[",
"]",
"fields1",
"=",
"model1",
".",
"_meta",
".",
"fields",
"fields2",
"=",
"model2",
".",
"_meta",
".",
"fields",
"# Add fields",
"names1",
"=",
... | Find difference between given peewee models. | [
"Find",
"difference",
"between",
"given",
"peewee",
"models",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/auto.py#L77-L128 |
232,498 | klen/peewee_migrate | peewee_migrate/auto.py | diff_many | def diff_many(models1, models2, migrator=None, reverse=False):
"""Calculate changes for migrations from models2 to models1."""
models1 = pw.sort_models(models1)
models2 = pw.sort_models(models2)
if reverse:
models1 = reversed(models1)
models2 = reversed(models2)
models1 = OrderedDict([(m._meta.name, m) for m in models1])
models2 = OrderedDict([(m._meta.name, m) for m in models2])
changes = []
for name, model1 in models1.items():
if name not in models2:
continue
changes += diff_one(model1, models2[name], migrator=migrator)
# Add models
for name in [m for m in models1 if m not in models2]:
changes.append(create_model(models1[name], migrator=migrator))
# Remove models
for name in [m for m in models2 if m not in models1]:
changes.append(remove_model(models2[name]))
return changes | python | def diff_many(models1, models2, migrator=None, reverse=False):
models1 = pw.sort_models(models1)
models2 = pw.sort_models(models2)
if reverse:
models1 = reversed(models1)
models2 = reversed(models2)
models1 = OrderedDict([(m._meta.name, m) for m in models1])
models2 = OrderedDict([(m._meta.name, m) for m in models2])
changes = []
for name, model1 in models1.items():
if name not in models2:
continue
changes += diff_one(model1, models2[name], migrator=migrator)
# Add models
for name in [m for m in models1 if m not in models2]:
changes.append(create_model(models1[name], migrator=migrator))
# Remove models
for name in [m for m in models2 if m not in models1]:
changes.append(remove_model(models2[name]))
return changes | [
"def",
"diff_many",
"(",
"models1",
",",
"models2",
",",
"migrator",
"=",
"None",
",",
"reverse",
"=",
"False",
")",
":",
"models1",
"=",
"pw",
".",
"sort_models",
"(",
"models1",
")",
"models2",
"=",
"pw",
".",
"sort_models",
"(",
"models2",
")",
"if"... | Calculate changes for migrations from models2 to models1. | [
"Calculate",
"changes",
"for",
"migrations",
"from",
"models2",
"to",
"models1",
"."
] | b77895ab1c9be3121bc127e0c2dfb047eed8b24c | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/auto.py#L131-L158 |
232,499 | samuelcolvin/watchgod | watchgod/main.py | watch | def watch(path: Union[Path, str], **kwargs):
"""
Watch a directory and yield a set of changes whenever files change in that directory or its subdirectories.
"""
loop = asyncio.new_event_loop()
try:
_awatch = awatch(path, loop=loop, **kwargs)
while True:
try:
yield loop.run_until_complete(_awatch.__anext__())
except StopAsyncIteration:
break
except KeyboardInterrupt:
logger.debug('KeyboardInterrupt, exiting')
finally:
loop.close() | python | def watch(path: Union[Path, str], **kwargs):
loop = asyncio.new_event_loop()
try:
_awatch = awatch(path, loop=loop, **kwargs)
while True:
try:
yield loop.run_until_complete(_awatch.__anext__())
except StopAsyncIteration:
break
except KeyboardInterrupt:
logger.debug('KeyboardInterrupt, exiting')
finally:
loop.close() | [
"def",
"watch",
"(",
"path",
":",
"Union",
"[",
"Path",
",",
"str",
"]",
",",
"*",
"*",
"kwargs",
")",
":",
"loop",
"=",
"asyncio",
".",
"new_event_loop",
"(",
")",
"try",
":",
"_awatch",
"=",
"awatch",
"(",
"path",
",",
"loop",
"=",
"loop",
",",... | Watch a directory and yield a set of changes whenever files change in that directory or its subdirectories. | [
"Watch",
"a",
"directory",
"and",
"yield",
"a",
"set",
"of",
"changes",
"whenever",
"files",
"change",
"in",
"that",
"directory",
"or",
"its",
"subdirectories",
"."
] | 15c72be2fca0afe2a081e4076f9353e5cdd8e42f | https://github.com/samuelcolvin/watchgod/blob/15c72be2fca0afe2a081e4076f9353e5cdd8e42f/watchgod/main.py#L24-L39 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.