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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
227,400 | buguroo/pyknow | pyknow/matchers/rete/nodes.py | NotNode._activate_left | def _activate_left(self, token):
"""
Activate from the left.
In case of a valid token this activations test the right memory
with the given token and looks for the number of matches. The
token and the number of occurences are stored in the left
memory.
If the number of matches is zero the token activates all children.
"""
if not self.right_memory:
if token.is_valid():
self.left_memory[token.to_info()] = 0
else:
del self.left_memory[token.to_info()]
for child in self.children:
child.callback(token)
elif token.is_valid():
count = 0
for _, right_context in self.right_memory:
if self.matcher(token.context, dict(right_context)):
count += 1
if count == 0:
for child in self.children:
child.callback(token)
self.left_memory[token.to_info()] = count
else:
count = 0
for _, right_context in self.right_memory:
if self.matcher(token.context, dict(right_context)):
count += 1
break
if count == 0:
for child in self.children:
child.callback(token)
del self.left_memory[token.to_info()] | python | def _activate_left(self, token):
if not self.right_memory:
if token.is_valid():
self.left_memory[token.to_info()] = 0
else:
del self.left_memory[token.to_info()]
for child in self.children:
child.callback(token)
elif token.is_valid():
count = 0
for _, right_context in self.right_memory:
if self.matcher(token.context, dict(right_context)):
count += 1
if count == 0:
for child in self.children:
child.callback(token)
self.left_memory[token.to_info()] = count
else:
count = 0
for _, right_context in self.right_memory:
if self.matcher(token.context, dict(right_context)):
count += 1
break
if count == 0:
for child in self.children:
child.callback(token)
del self.left_memory[token.to_info()] | [
"def",
"_activate_left",
"(",
"self",
",",
"token",
")",
":",
"if",
"not",
"self",
".",
"right_memory",
":",
"if",
"token",
".",
"is_valid",
"(",
")",
":",
"self",
".",
"left_memory",
"[",
"token",
".",
"to_info",
"(",
")",
"]",
"=",
"0",
"else",
"... | Activate from the left.
In case of a valid token this activations test the right memory
with the given token and looks for the number of matches. The
token and the number of occurences are stored in the left
memory.
If the number of matches is zero the token activates all children. | [
"Activate",
"from",
"the",
"left",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/matchers/rete/nodes.py#L323-L367 |
227,401 | buguroo/pyknow | pyknow/matchers/rete/nodes.py | NotNode._activate_right | def _activate_right(self, token):
"""
Activate from the right.
Go over the left memory and find matching data, when found
update the counter (substracting if the given token is invalid
and adding otherwise). Depending on the result of this operation
a new token is generated and passing to all children.
"""
if token.is_valid():
self.right_memory.append(token.to_info())
inc = 1
else:
inc = -1
self.right_memory.remove(token.to_info())
for left in self.left_memory:
if self.matcher(dict(left.context), token.context):
self.left_memory[left] += inc
newcount = self.left_memory[left]
if (newcount == 0 and inc == -1) or \
(newcount == 1 and inc == 1):
if inc == -1:
newtoken = left.to_valid_token()
else:
newtoken = left.to_invalid_token()
for child in self.children:
child.callback(newtoken) | python | def _activate_right(self, token):
if token.is_valid():
self.right_memory.append(token.to_info())
inc = 1
else:
inc = -1
self.right_memory.remove(token.to_info())
for left in self.left_memory:
if self.matcher(dict(left.context), token.context):
self.left_memory[left] += inc
newcount = self.left_memory[left]
if (newcount == 0 and inc == -1) or \
(newcount == 1 and inc == 1):
if inc == -1:
newtoken = left.to_valid_token()
else:
newtoken = left.to_invalid_token()
for child in self.children:
child.callback(newtoken) | [
"def",
"_activate_right",
"(",
"self",
",",
"token",
")",
":",
"if",
"token",
".",
"is_valid",
"(",
")",
":",
"self",
".",
"right_memory",
".",
"append",
"(",
"token",
".",
"to_info",
"(",
")",
")",
"inc",
"=",
"1",
"else",
":",
"inc",
"=",
"-",
... | Activate from the right.
Go over the left memory and find matching data, when found
update the counter (substracting if the given token is invalid
and adding otherwise). Depending on the result of this operation
a new token is generated and passing to all children. | [
"Activate",
"from",
"the",
"right",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/matchers/rete/nodes.py#L369-L398 |
227,402 | buguroo/pyknow | pyknow/factlist.py | FactList.retract | def retract(self, idx_or_fact):
"""
Retract a previously asserted fact.
See `"Retract that fact" in Clips User Guide
<http://clipsrules.sourceforge.net/doc\
umentation/v624/ug.htm#_Toc412126077>`_.
:param idx: The index of the fact to retract in the factlist
:return: (int) The retracted fact's index
:throws IndexError: If the fact's index providen does not exist
"""
if isinstance(idx_or_fact, int):
idx = idx_or_fact
else:
idx = idx_or_fact.__factid__
if idx not in self:
raise IndexError('Fact not found.')
fact = self[idx]
# Decrement value reference counter
fact_id = self._get_fact_id(fact)
self.reference_counter[fact_id] -= 1
if self.reference_counter[fact_id] == 0:
self.reference_counter.pop(fact_id)
watchers.FACTS.info(" <== %s: %r", fact, fact)
self.removed.append(fact)
del self[idx]
return idx | python | def retract(self, idx_or_fact):
if isinstance(idx_or_fact, int):
idx = idx_or_fact
else:
idx = idx_or_fact.__factid__
if idx not in self:
raise IndexError('Fact not found.')
fact = self[idx]
# Decrement value reference counter
fact_id = self._get_fact_id(fact)
self.reference_counter[fact_id] -= 1
if self.reference_counter[fact_id] == 0:
self.reference_counter.pop(fact_id)
watchers.FACTS.info(" <== %s: %r", fact, fact)
self.removed.append(fact)
del self[idx]
return idx | [
"def",
"retract",
"(",
"self",
",",
"idx_or_fact",
")",
":",
"if",
"isinstance",
"(",
"idx_or_fact",
",",
"int",
")",
":",
"idx",
"=",
"idx_or_fact",
"else",
":",
"idx",
"=",
"idx_or_fact",
".",
"__factid__",
"if",
"idx",
"not",
"in",
"self",
":",
"rai... | Retract a previously asserted fact.
See `"Retract that fact" in Clips User Guide
<http://clipsrules.sourceforge.net/doc\
umentation/v624/ug.htm#_Toc412126077>`_.
:param idx: The index of the fact to retract in the factlist
:return: (int) The retracted fact's index
:throws IndexError: If the fact's index providen does not exist | [
"Retract",
"a",
"previously",
"asserted",
"fact",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/factlist.py#L92-L126 |
227,403 | buguroo/pyknow | pyknow/factlist.py | FactList.changes | def changes(self):
"""
Return a tuple with the removed and added facts since last run.
"""
try:
return self.added, self.removed
finally:
self.added = list()
self.removed = list() | python | def changes(self):
try:
return self.added, self.removed
finally:
self.added = list()
self.removed = list() | [
"def",
"changes",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"added",
",",
"self",
".",
"removed",
"finally",
":",
"self",
".",
"added",
"=",
"list",
"(",
")",
"self",
".",
"removed",
"=",
"list",
"(",
")"
] | Return a tuple with the removed and added facts since last run. | [
"Return",
"a",
"tuple",
"with",
"the",
"removed",
"and",
"added",
"facts",
"since",
"last",
"run",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/factlist.py#L129-L137 |
227,404 | buguroo/pyknow | pyknow/rule.py | Rule.new_conditions | def new_conditions(self, *args):
"""
Generate a new rule with the same attributes but with the given
conditions.
"""
obj = self.__class__(*args, salience=self.salience)
if self._wrapped:
obj = obj(self._wrapped)
return obj | python | def new_conditions(self, *args):
obj = self.__class__(*args, salience=self.salience)
if self._wrapped:
obj = obj(self._wrapped)
return obj | [
"def",
"new_conditions",
"(",
"self",
",",
"*",
"args",
")",
":",
"obj",
"=",
"self",
".",
"__class__",
"(",
"*",
"args",
",",
"salience",
"=",
"self",
".",
"salience",
")",
"if",
"self",
".",
"_wrapped",
":",
"obj",
"=",
"obj",
"(",
"self",
".",
... | Generate a new rule with the same attributes but with the given
conditions. | [
"Generate",
"a",
"new",
"rule",
"with",
"the",
"same",
"attributes",
"but",
"with",
"the",
"given",
"conditions",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/rule.py#L34-L45 |
227,405 | buguroo/pyknow | pyknow/fact.py | Fact.as_dict | def as_dict(self):
"""Return a dictionary containing this `Fact` data."""
return {k: unfreeze(v)
for k, v in self.items()
if not self.is_special(k)} | python | def as_dict(self):
return {k: unfreeze(v)
for k, v in self.items()
if not self.is_special(k)} | [
"def",
"as_dict",
"(",
"self",
")",
":",
"return",
"{",
"k",
":",
"unfreeze",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"items",
"(",
")",
"if",
"not",
"self",
".",
"is_special",
"(",
"k",
")",
"}"
] | Return a dictionary containing this `Fact` data. | [
"Return",
"a",
"dictionary",
"containing",
"this",
"Fact",
"data",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/fact.py#L100-L104 |
227,406 | buguroo/pyknow | pyknow/fact.py | Fact.copy | def copy(self):
"""Return a copy of this `Fact`."""
content = [(k, v) for k, v in self.items()]
intidx = [(k, v) for k, v in content if isinstance(k, int)]
args = [v for k, v in sorted(intidx)]
kwargs = {k: v
for k, v in content
if not isinstance(k, int) and not self.is_special(k)}
return self.__class__(*args, **kwargs) | python | def copy(self):
content = [(k, v) for k, v in self.items()]
intidx = [(k, v) for k, v in content if isinstance(k, int)]
args = [v for k, v in sorted(intidx)]
kwargs = {k: v
for k, v in content
if not isinstance(k, int) and not self.is_special(k)}
return self.__class__(*args, **kwargs) | [
"def",
"copy",
"(",
"self",
")",
":",
"content",
"=",
"[",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"items",
"(",
")",
"]",
"intidx",
"=",
"[",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"content",
"if",... | Return a copy of this `Fact`. | [
"Return",
"a",
"copy",
"of",
"this",
"Fact",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/fact.py#L106-L116 |
227,407 | buguroo/pyknow | pyknow/matchers/rete/mixins.py | AnyChild.add_child | def add_child(self, node, callback):
"""Add node and callback to the children set."""
if node not in self.children:
self.children.append(ChildNode(node, callback)) | python | def add_child(self, node, callback):
if node not in self.children:
self.children.append(ChildNode(node, callback)) | [
"def",
"add_child",
"(",
"self",
",",
"node",
",",
"callback",
")",
":",
"if",
"node",
"not",
"in",
"self",
".",
"children",
":",
"self",
".",
"children",
".",
"append",
"(",
"ChildNode",
"(",
"node",
",",
"callback",
")",
")"
] | Add node and callback to the children set. | [
"Add",
"node",
"and",
"callback",
"to",
"the",
"children",
"set",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/matchers/rete/mixins.py#L20-L23 |
227,408 | buguroo/pyknow | pyknow/matchers/rete/token.py | Token.valid | def valid(cls, data, context=None):
"""Shortcut to create a VALID Token."""
return cls(cls.TagType.VALID, data, context) | python | def valid(cls, data, context=None):
return cls(cls.TagType.VALID, data, context) | [
"def",
"valid",
"(",
"cls",
",",
"data",
",",
"context",
"=",
"None",
")",
":",
"return",
"cls",
"(",
"cls",
".",
"TagType",
".",
"VALID",
",",
"data",
",",
"context",
")"
] | Shortcut to create a VALID Token. | [
"Shortcut",
"to",
"create",
"a",
"VALID",
"Token",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/matchers/rete/token.py#L76-L78 |
227,409 | buguroo/pyknow | pyknow/matchers/rete/token.py | Token.invalid | def invalid(cls, data, context=None):
"""Shortcut to create an INVALID Token."""
return cls(cls.TagType.INVALID, data, context) | python | def invalid(cls, data, context=None):
return cls(cls.TagType.INVALID, data, context) | [
"def",
"invalid",
"(",
"cls",
",",
"data",
",",
"context",
"=",
"None",
")",
":",
"return",
"cls",
"(",
"cls",
".",
"TagType",
".",
"INVALID",
",",
"data",
",",
"context",
")"
] | Shortcut to create an INVALID Token. | [
"Shortcut",
"to",
"create",
"an",
"INVALID",
"Token",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/matchers/rete/token.py#L81-L83 |
227,410 | buguroo/pyknow | pyknow/matchers/rete/token.py | Token.copy | def copy(self):
"""
Make a new instance of this Token.
This method makes a copy of the mutable part of the token before
making the instance.
"""
return self.__class__(self.tag, self.data.copy(), self.context.copy()) | python | def copy(self):
return self.__class__(self.tag, self.data.copy(), self.context.copy()) | [
"def",
"copy",
"(",
"self",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"self",
".",
"tag",
",",
"self",
".",
"data",
".",
"copy",
"(",
")",
",",
"self",
".",
"context",
".",
"copy",
"(",
")",
")"
] | Make a new instance of this Token.
This method makes a copy of the mutable part of the token before
making the instance. | [
"Make",
"a",
"new",
"instance",
"of",
"this",
"Token",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/matchers/rete/token.py#L89-L97 |
227,411 | myusuf3/delorean | delorean/interface.py | parse | def parse(datetime_str, timezone=None, isofirst=True, dayfirst=True, yearfirst=True):
"""
Parses a datetime string and returns a `Delorean` object.
:param datetime_str: The string to be interpreted into a `Delorean` object.
:param timezone: Pass this parameter and the returned Delorean object will be normalized to this timezone. Any
offsets passed as part of datetime_str will be ignored.
:param isofirst: try to parse string as date in ISO format before everything else.
:param dayfirst: Whether to interpret the first value in an ambiguous 3-integer date (ex. 01/05/09) as the day
(True) or month (False). If yearfirst is set to True, this distinguishes between YDM and YMD.
:param yearfirst: Whether to interpret the first value in an ambiguous 3-integer date (ex. 01/05/09) as the
year. If True, the first number is taken to be the year, otherwise the last number is taken to be the year.
.. testsetup::
from delorean import Delorean
from delorean import parse
.. doctest::
>>> parse('2015-01-01 00:01:02')
Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone='UTC')
If a fixed offset is provided in the datetime_str, it will be parsed and the returned `Delorean` object will store a
`pytz.FixedOffest` as it's timezone.
.. doctest::
>>> parse('2015-01-01 00:01:02 -0800')
Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone=pytz.FixedOffset(-480))
If the timezone argument is supplied, the returned Delorean object will be in the timezone supplied. Any offsets in
the datetime_str will be ignored.
.. doctest::
>>> parse('2015-01-01 00:01:02 -0500', timezone='US/Pacific')
Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone='US/Pacific')
If an unambiguous timezone is detected in the datetime string, a Delorean object with that datetime and
timezone will be returned.
.. doctest::
>>> parse('2015-01-01 00:01:02 PST')
Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone='America/Los_Angeles')
However if the provided timezone is ambiguous, parse will ignore the timezone and return a `Delorean` object in UTC
time.
>>> parse('2015-01-01 00:01:02 EST')
Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone='UTC')
"""
# parse string to datetime object
dt = None
if isofirst:
try:
dt = isocapture(datetime_str)
except Exception:
pass
if dt is None:
dt = capture(datetime_str, dayfirst=dayfirst, yearfirst=yearfirst)
if timezone:
dt = dt.replace(tzinfo=None)
do = Delorean(datetime=dt, timezone=timezone)
elif dt.tzinfo is None:
# assuming datetime object passed in is UTC
do = Delorean(datetime=dt, timezone='UTC')
elif isinstance(dt.tzinfo, tzoffset):
utcoffset = dt.tzinfo.utcoffset(None)
total_seconds = (
(utcoffset.microseconds + (utcoffset.seconds + utcoffset.days * 24 * 3600) * 10**6) / 10**6)
tz = pytz.FixedOffset(total_seconds / 60)
dt = dt.replace(tzinfo=None)
do = Delorean(dt, timezone=tz)
elif isinstance(dt.tzinfo, tzlocal):
tz = get_localzone()
dt = dt.replace(tzinfo=None)
do = Delorean(dt, timezone=tz)
else:
dt = pytz.utc.normalize(dt)
# making dt naive so we can pass it to Delorean
dt = dt.replace(tzinfo=None)
# if parse string has tzinfo we return a normalized UTC
# delorean object that represents the time.
do = Delorean(datetime=dt, timezone='UTC')
return do | python | def parse(datetime_str, timezone=None, isofirst=True, dayfirst=True, yearfirst=True):
# parse string to datetime object
dt = None
if isofirst:
try:
dt = isocapture(datetime_str)
except Exception:
pass
if dt is None:
dt = capture(datetime_str, dayfirst=dayfirst, yearfirst=yearfirst)
if timezone:
dt = dt.replace(tzinfo=None)
do = Delorean(datetime=dt, timezone=timezone)
elif dt.tzinfo is None:
# assuming datetime object passed in is UTC
do = Delorean(datetime=dt, timezone='UTC')
elif isinstance(dt.tzinfo, tzoffset):
utcoffset = dt.tzinfo.utcoffset(None)
total_seconds = (
(utcoffset.microseconds + (utcoffset.seconds + utcoffset.days * 24 * 3600) * 10**6) / 10**6)
tz = pytz.FixedOffset(total_seconds / 60)
dt = dt.replace(tzinfo=None)
do = Delorean(dt, timezone=tz)
elif isinstance(dt.tzinfo, tzlocal):
tz = get_localzone()
dt = dt.replace(tzinfo=None)
do = Delorean(dt, timezone=tz)
else:
dt = pytz.utc.normalize(dt)
# making dt naive so we can pass it to Delorean
dt = dt.replace(tzinfo=None)
# if parse string has tzinfo we return a normalized UTC
# delorean object that represents the time.
do = Delorean(datetime=dt, timezone='UTC')
return do | [
"def",
"parse",
"(",
"datetime_str",
",",
"timezone",
"=",
"None",
",",
"isofirst",
"=",
"True",
",",
"dayfirst",
"=",
"True",
",",
"yearfirst",
"=",
"True",
")",
":",
"# parse string to datetime object",
"dt",
"=",
"None",
"if",
"isofirst",
":",
"try",
":... | Parses a datetime string and returns a `Delorean` object.
:param datetime_str: The string to be interpreted into a `Delorean` object.
:param timezone: Pass this parameter and the returned Delorean object will be normalized to this timezone. Any
offsets passed as part of datetime_str will be ignored.
:param isofirst: try to parse string as date in ISO format before everything else.
:param dayfirst: Whether to interpret the first value in an ambiguous 3-integer date (ex. 01/05/09) as the day
(True) or month (False). If yearfirst is set to True, this distinguishes between YDM and YMD.
:param yearfirst: Whether to interpret the first value in an ambiguous 3-integer date (ex. 01/05/09) as the
year. If True, the first number is taken to be the year, otherwise the last number is taken to be the year.
.. testsetup::
from delorean import Delorean
from delorean import parse
.. doctest::
>>> parse('2015-01-01 00:01:02')
Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone='UTC')
If a fixed offset is provided in the datetime_str, it will be parsed and the returned `Delorean` object will store a
`pytz.FixedOffest` as it's timezone.
.. doctest::
>>> parse('2015-01-01 00:01:02 -0800')
Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone=pytz.FixedOffset(-480))
If the timezone argument is supplied, the returned Delorean object will be in the timezone supplied. Any offsets in
the datetime_str will be ignored.
.. doctest::
>>> parse('2015-01-01 00:01:02 -0500', timezone='US/Pacific')
Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone='US/Pacific')
If an unambiguous timezone is detected in the datetime string, a Delorean object with that datetime and
timezone will be returned.
.. doctest::
>>> parse('2015-01-01 00:01:02 PST')
Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone='America/Los_Angeles')
However if the provided timezone is ambiguous, parse will ignore the timezone and return a `Delorean` object in UTC
time.
>>> parse('2015-01-01 00:01:02 EST')
Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone='UTC') | [
"Parses",
"a",
"datetime",
"string",
"and",
"returns",
"a",
"Delorean",
"object",
"."
] | 3e8a7b8cfd4c26546f62bde2f34002893adfa08a | https://github.com/myusuf3/delorean/blob/3e8a7b8cfd4c26546f62bde2f34002893adfa08a/delorean/interface.py#L15-L105 |
227,412 | myusuf3/delorean | delorean/interface.py | range_daily | def range_daily(start=None, stop=None, timezone='UTC', count=None):
"""
This an alternative way to generating sets of Delorean objects with
DAILY stops
"""
return stops(start=start, stop=stop, freq=DAILY, timezone=timezone, count=count) | python | def range_daily(start=None, stop=None, timezone='UTC', count=None):
return stops(start=start, stop=stop, freq=DAILY, timezone=timezone, count=count) | [
"def",
"range_daily",
"(",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
",",
"timezone",
"=",
"'UTC'",
",",
"count",
"=",
"None",
")",
":",
"return",
"stops",
"(",
"start",
"=",
"start",
",",
"stop",
"=",
"stop",
",",
"freq",
"=",
"DAILY",
",",
... | This an alternative way to generating sets of Delorean objects with
DAILY stops | [
"This",
"an",
"alternative",
"way",
"to",
"generating",
"sets",
"of",
"Delorean",
"objects",
"with",
"DAILY",
"stops"
] | 3e8a7b8cfd4c26546f62bde2f34002893adfa08a | https://github.com/myusuf3/delorean/blob/3e8a7b8cfd4c26546f62bde2f34002893adfa08a/delorean/interface.py#L108-L113 |
227,413 | myusuf3/delorean | delorean/interface.py | range_hourly | def range_hourly(start=None, stop=None, timezone='UTC', count=None):
"""
This an alternative way to generating sets of Delorean objects with
HOURLY stops
"""
return stops(start=start, stop=stop, freq=HOURLY, timezone=timezone, count=count) | python | def range_hourly(start=None, stop=None, timezone='UTC', count=None):
return stops(start=start, stop=stop, freq=HOURLY, timezone=timezone, count=count) | [
"def",
"range_hourly",
"(",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
",",
"timezone",
"=",
"'UTC'",
",",
"count",
"=",
"None",
")",
":",
"return",
"stops",
"(",
"start",
"=",
"start",
",",
"stop",
"=",
"stop",
",",
"freq",
"=",
"HOURLY",
","... | This an alternative way to generating sets of Delorean objects with
HOURLY stops | [
"This",
"an",
"alternative",
"way",
"to",
"generating",
"sets",
"of",
"Delorean",
"objects",
"with",
"HOURLY",
"stops"
] | 3e8a7b8cfd4c26546f62bde2f34002893adfa08a | https://github.com/myusuf3/delorean/blob/3e8a7b8cfd4c26546f62bde2f34002893adfa08a/delorean/interface.py#L116-L121 |
227,414 | myusuf3/delorean | delorean/interface.py | range_monthly | def range_monthly(start=None, stop=None, timezone='UTC', count=None):
"""
This an alternative way to generating sets of Delorean objects with
MONTHLY stops
"""
return stops(start=start, stop=stop, freq=MONTHLY, timezone=timezone, count=count) | python | def range_monthly(start=None, stop=None, timezone='UTC', count=None):
return stops(start=start, stop=stop, freq=MONTHLY, timezone=timezone, count=count) | [
"def",
"range_monthly",
"(",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
",",
"timezone",
"=",
"'UTC'",
",",
"count",
"=",
"None",
")",
":",
"return",
"stops",
"(",
"start",
"=",
"start",
",",
"stop",
"=",
"stop",
",",
"freq",
"=",
"MONTHLY",
"... | This an alternative way to generating sets of Delorean objects with
MONTHLY stops | [
"This",
"an",
"alternative",
"way",
"to",
"generating",
"sets",
"of",
"Delorean",
"objects",
"with",
"MONTHLY",
"stops"
] | 3e8a7b8cfd4c26546f62bde2f34002893adfa08a | https://github.com/myusuf3/delorean/blob/3e8a7b8cfd4c26546f62bde2f34002893adfa08a/delorean/interface.py#L124-L129 |
227,415 | myusuf3/delorean | delorean/interface.py | range_yearly | def range_yearly(start=None, stop=None, timezone='UTC', count=None):
"""
This an alternative way to generating sets of Delorean objects with
YEARLY stops
"""
return stops(start=start, stop=stop, freq=YEARLY, timezone=timezone, count=count) | python | def range_yearly(start=None, stop=None, timezone='UTC', count=None):
return stops(start=start, stop=stop, freq=YEARLY, timezone=timezone, count=count) | [
"def",
"range_yearly",
"(",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
",",
"timezone",
"=",
"'UTC'",
",",
"count",
"=",
"None",
")",
":",
"return",
"stops",
"(",
"start",
"=",
"start",
",",
"stop",
"=",
"stop",
",",
"freq",
"=",
"YEARLY",
","... | This an alternative way to generating sets of Delorean objects with
YEARLY stops | [
"This",
"an",
"alternative",
"way",
"to",
"generating",
"sets",
"of",
"Delorean",
"objects",
"with",
"YEARLY",
"stops"
] | 3e8a7b8cfd4c26546f62bde2f34002893adfa08a | https://github.com/myusuf3/delorean/blob/3e8a7b8cfd4c26546f62bde2f34002893adfa08a/delorean/interface.py#L132-L137 |
227,416 | myusuf3/delorean | delorean/interface.py | stops | def stops(freq, interval=1, count=None, wkst=None, bysetpos=None,
bymonth=None, bymonthday=None, byyearday=None, byeaster=None,
byweekno=None, byweekday=None, byhour=None, byminute=None,
bysecond=None, timezone='UTC', start=None, stop=None):
"""
This will create a list of delorean objects the apply to
setting possed in.
"""
# check to see if datetimees passed in are naive if so process them
# with given timezone.
if all([(start is None or is_datetime_naive(start)),
(stop is None or is_datetime_naive(stop))]):
pass
else:
raise DeloreanInvalidDatetime('Provide a naive datetime object')
# if no datetimes are passed in create a proper datetime object for
# start default because default in dateutil is datetime.now() :(
if start is None:
start = datetime_timezone(timezone)
for dt in rrule(freq, interval=interval, count=count, wkst=wkst, bysetpos=bysetpos,
bymonth=bymonth, bymonthday=bymonthday, byyearday=byyearday, byeaster=byeaster,
byweekno=byweekno, byweekday=byweekday, byhour=byhour, byminute=byminute,
bysecond=bysecond, until=stop, dtstart=start):
# make the delorean object
# yield it.
# doing this to make sure delorean receives a naive datetime.
dt = dt.replace(tzinfo=None)
d = Delorean(datetime=dt, timezone=timezone)
yield d | python | def stops(freq, interval=1, count=None, wkst=None, bysetpos=None,
bymonth=None, bymonthday=None, byyearday=None, byeaster=None,
byweekno=None, byweekday=None, byhour=None, byminute=None,
bysecond=None, timezone='UTC', start=None, stop=None):
# check to see if datetimees passed in are naive if so process them
# with given timezone.
if all([(start is None or is_datetime_naive(start)),
(stop is None or is_datetime_naive(stop))]):
pass
else:
raise DeloreanInvalidDatetime('Provide a naive datetime object')
# if no datetimes are passed in create a proper datetime object for
# start default because default in dateutil is datetime.now() :(
if start is None:
start = datetime_timezone(timezone)
for dt in rrule(freq, interval=interval, count=count, wkst=wkst, bysetpos=bysetpos,
bymonth=bymonth, bymonthday=bymonthday, byyearday=byyearday, byeaster=byeaster,
byweekno=byweekno, byweekday=byweekday, byhour=byhour, byminute=byminute,
bysecond=bysecond, until=stop, dtstart=start):
# make the delorean object
# yield it.
# doing this to make sure delorean receives a naive datetime.
dt = dt.replace(tzinfo=None)
d = Delorean(datetime=dt, timezone=timezone)
yield d | [
"def",
"stops",
"(",
"freq",
",",
"interval",
"=",
"1",
",",
"count",
"=",
"None",
",",
"wkst",
"=",
"None",
",",
"bysetpos",
"=",
"None",
",",
"bymonth",
"=",
"None",
",",
"bymonthday",
"=",
"None",
",",
"byyearday",
"=",
"None",
",",
"byeaster",
... | This will create a list of delorean objects the apply to
setting possed in. | [
"This",
"will",
"create",
"a",
"list",
"of",
"delorean",
"objects",
"the",
"apply",
"to",
"setting",
"possed",
"in",
"."
] | 3e8a7b8cfd4c26546f62bde2f34002893adfa08a | https://github.com/myusuf3/delorean/blob/3e8a7b8cfd4c26546f62bde2f34002893adfa08a/delorean/interface.py#L140-L170 |
227,417 | myusuf3/delorean | delorean/dates.py | _move_datetime | def _move_datetime(dt, direction, delta):
"""
Move datetime given delta by given direction
"""
if direction == 'next':
dt = dt + delta
elif direction == 'last':
dt = dt - delta
else:
pass
# raise some delorean error here
return dt | python | def _move_datetime(dt, direction, delta):
if direction == 'next':
dt = dt + delta
elif direction == 'last':
dt = dt - delta
else:
pass
# raise some delorean error here
return dt | [
"def",
"_move_datetime",
"(",
"dt",
",",
"direction",
",",
"delta",
")",
":",
"if",
"direction",
"==",
"'next'",
":",
"dt",
"=",
"dt",
"+",
"delta",
"elif",
"direction",
"==",
"'last'",
":",
"dt",
"=",
"dt",
"-",
"delta",
"else",
":",
"pass",
"# rais... | Move datetime given delta by given direction | [
"Move",
"datetime",
"given",
"delta",
"by",
"given",
"direction"
] | 3e8a7b8cfd4c26546f62bde2f34002893adfa08a | https://github.com/myusuf3/delorean/blob/3e8a7b8cfd4c26546f62bde2f34002893adfa08a/delorean/dates.py#L45-L56 |
227,418 | myusuf3/delorean | delorean/dates.py | move_datetime_month | def move_datetime_month(dt, direction, num_shifts):
"""
Move datetime 1 month in the chosen direction.
unit is a no-op, to keep the API the same as the day case
"""
delta = relativedelta(months=+num_shifts)
return _move_datetime(dt, direction, delta) | python | def move_datetime_month(dt, direction, num_shifts):
delta = relativedelta(months=+num_shifts)
return _move_datetime(dt, direction, delta) | [
"def",
"move_datetime_month",
"(",
"dt",
",",
"direction",
",",
"num_shifts",
")",
":",
"delta",
"=",
"relativedelta",
"(",
"months",
"=",
"+",
"num_shifts",
")",
"return",
"_move_datetime",
"(",
"dt",
",",
"direction",
",",
"delta",
")"
] | Move datetime 1 month in the chosen direction.
unit is a no-op, to keep the API the same as the day case | [
"Move",
"datetime",
"1",
"month",
"in",
"the",
"chosen",
"direction",
".",
"unit",
"is",
"a",
"no",
"-",
"op",
"to",
"keep",
"the",
"API",
"the",
"same",
"as",
"the",
"day",
"case"
] | 3e8a7b8cfd4c26546f62bde2f34002893adfa08a | https://github.com/myusuf3/delorean/blob/3e8a7b8cfd4c26546f62bde2f34002893adfa08a/delorean/dates.py#L95-L101 |
227,419 | myusuf3/delorean | delorean/dates.py | move_datetime_week | def move_datetime_week(dt, direction, num_shifts):
"""
Move datetime 1 week in the chosen direction.
unit is a no-op, to keep the API the same as the day case
"""
delta = relativedelta(weeks=+num_shifts)
return _move_datetime(dt, direction, delta) | python | def move_datetime_week(dt, direction, num_shifts):
delta = relativedelta(weeks=+num_shifts)
return _move_datetime(dt, direction, delta) | [
"def",
"move_datetime_week",
"(",
"dt",
",",
"direction",
",",
"num_shifts",
")",
":",
"delta",
"=",
"relativedelta",
"(",
"weeks",
"=",
"+",
"num_shifts",
")",
"return",
"_move_datetime",
"(",
"dt",
",",
"direction",
",",
"delta",
")"
] | Move datetime 1 week in the chosen direction.
unit is a no-op, to keep the API the same as the day case | [
"Move",
"datetime",
"1",
"week",
"in",
"the",
"chosen",
"direction",
".",
"unit",
"is",
"a",
"no",
"-",
"op",
"to",
"keep",
"the",
"API",
"the",
"same",
"as",
"the",
"day",
"case"
] | 3e8a7b8cfd4c26546f62bde2f34002893adfa08a | https://github.com/myusuf3/delorean/blob/3e8a7b8cfd4c26546f62bde2f34002893adfa08a/delorean/dates.py#L104-L110 |
227,420 | myusuf3/delorean | delorean/dates.py | move_datetime_year | def move_datetime_year(dt, direction, num_shifts):
"""
Move datetime 1 year in the chosen direction.
unit is a no-op, to keep the API the same as the day case
"""
delta = relativedelta(years=+num_shifts)
return _move_datetime(dt, direction, delta) | python | def move_datetime_year(dt, direction, num_shifts):
delta = relativedelta(years=+num_shifts)
return _move_datetime(dt, direction, delta) | [
"def",
"move_datetime_year",
"(",
"dt",
",",
"direction",
",",
"num_shifts",
")",
":",
"delta",
"=",
"relativedelta",
"(",
"years",
"=",
"+",
"num_shifts",
")",
"return",
"_move_datetime",
"(",
"dt",
",",
"direction",
",",
"delta",
")"
] | Move datetime 1 year in the chosen direction.
unit is a no-op, to keep the API the same as the day case | [
"Move",
"datetime",
"1",
"year",
"in",
"the",
"chosen",
"direction",
".",
"unit",
"is",
"a",
"no",
"-",
"op",
"to",
"keep",
"the",
"API",
"the",
"same",
"as",
"the",
"day",
"case"
] | 3e8a7b8cfd4c26546f62bde2f34002893adfa08a | https://github.com/myusuf3/delorean/blob/3e8a7b8cfd4c26546f62bde2f34002893adfa08a/delorean/dates.py#L113-L119 |
227,421 | myusuf3/delorean | delorean/dates.py | datetime_timezone | def datetime_timezone(tz):
"""
This method given a timezone returns a localized datetime object.
"""
utc_datetime_naive = datetime.utcnow()
# return a localized datetime to UTC
utc_localized_datetime = localize(utc_datetime_naive, 'UTC')
# normalize the datetime to given timezone
normalized_datetime = normalize(utc_localized_datetime, tz)
return normalized_datetime | python | def datetime_timezone(tz):
utc_datetime_naive = datetime.utcnow()
# return a localized datetime to UTC
utc_localized_datetime = localize(utc_datetime_naive, 'UTC')
# normalize the datetime to given timezone
normalized_datetime = normalize(utc_localized_datetime, tz)
return normalized_datetime | [
"def",
"datetime_timezone",
"(",
"tz",
")",
":",
"utc_datetime_naive",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"# return a localized datetime to UTC",
"utc_localized_datetime",
"=",
"localize",
"(",
"utc_datetime_naive",
",",
"'UTC'",
")",
"# normalize the datetime to g... | This method given a timezone returns a localized datetime object. | [
"This",
"method",
"given",
"a",
"timezone",
"returns",
"a",
"localized",
"datetime",
"object",
"."
] | 3e8a7b8cfd4c26546f62bde2f34002893adfa08a | https://github.com/myusuf3/delorean/blob/3e8a7b8cfd4c26546f62bde2f34002893adfa08a/delorean/dates.py#L137-L146 |
227,422 | myusuf3/delorean | delorean/dates.py | localize | def localize(dt, tz):
"""
Given a naive datetime object this method will return a localized
datetime object
"""
if not isinstance(tz, tzinfo):
tz = pytz.timezone(tz)
return tz.localize(dt) | python | def localize(dt, tz):
if not isinstance(tz, tzinfo):
tz = pytz.timezone(tz)
return tz.localize(dt) | [
"def",
"localize",
"(",
"dt",
",",
"tz",
")",
":",
"if",
"not",
"isinstance",
"(",
"tz",
",",
"tzinfo",
")",
":",
"tz",
"=",
"pytz",
".",
"timezone",
"(",
"tz",
")",
"return",
"tz",
".",
"localize",
"(",
"dt",
")"
] | Given a naive datetime object this method will return a localized
datetime object | [
"Given",
"a",
"naive",
"datetime",
"object",
"this",
"method",
"will",
"return",
"a",
"localized",
"datetime",
"object"
] | 3e8a7b8cfd4c26546f62bde2f34002893adfa08a | https://github.com/myusuf3/delorean/blob/3e8a7b8cfd4c26546f62bde2f34002893adfa08a/delorean/dates.py#L149-L157 |
227,423 | myusuf3/delorean | delorean/dates.py | normalize | def normalize(dt, tz):
"""
Given a object with a timezone return a datetime object
normalized to the proper timezone.
This means take the give localized datetime and returns the
datetime normalized to match the specificed timezone.
"""
if not isinstance(tz, tzinfo):
tz = pytz.timezone(tz)
dt = tz.normalize(dt)
return dt | python | def normalize(dt, tz):
if not isinstance(tz, tzinfo):
tz = pytz.timezone(tz)
dt = tz.normalize(dt)
return dt | [
"def",
"normalize",
"(",
"dt",
",",
"tz",
")",
":",
"if",
"not",
"isinstance",
"(",
"tz",
",",
"tzinfo",
")",
":",
"tz",
"=",
"pytz",
".",
"timezone",
"(",
"tz",
")",
"dt",
"=",
"tz",
".",
"normalize",
"(",
"dt",
")",
"return",
"dt"
] | Given a object with a timezone return a datetime object
normalized to the proper timezone.
This means take the give localized datetime and returns the
datetime normalized to match the specificed timezone. | [
"Given",
"a",
"object",
"with",
"a",
"timezone",
"return",
"a",
"datetime",
"object",
"normalized",
"to",
"the",
"proper",
"timezone",
"."
] | 3e8a7b8cfd4c26546f62bde2f34002893adfa08a | https://github.com/myusuf3/delorean/blob/3e8a7b8cfd4c26546f62bde2f34002893adfa08a/delorean/dates.py#L160-L171 |
227,424 | myusuf3/delorean | delorean/dates.py | Delorean.shift | def shift(self, timezone):
"""
Shifts the timezone from the current timezone to the specified timezone associated with the Delorean object,
modifying the Delorean object and returning the modified object.
.. testsetup::
from datetime import datetime
from delorean import Delorean
.. doctest::
>>> d = Delorean(datetime(2015, 1, 1), timezone='US/Pacific')
>>> d.shift('UTC')
Delorean(datetime=datetime.datetime(2015, 1, 1, 8, 0), timezone='UTC')
"""
try:
self._tzinfo = pytz.timezone(timezone)
except pytz.UnknownTimeZoneError:
raise DeloreanInvalidTimezone('Provide a valid timezone')
self._dt = self._tzinfo.normalize(self._dt.astimezone(self._tzinfo))
self._tzinfo = self._dt.tzinfo
return self | python | def shift(self, timezone):
try:
self._tzinfo = pytz.timezone(timezone)
except pytz.UnknownTimeZoneError:
raise DeloreanInvalidTimezone('Provide a valid timezone')
self._dt = self._tzinfo.normalize(self._dt.astimezone(self._tzinfo))
self._tzinfo = self._dt.tzinfo
return self | [
"def",
"shift",
"(",
"self",
",",
"timezone",
")",
":",
"try",
":",
"self",
".",
"_tzinfo",
"=",
"pytz",
".",
"timezone",
"(",
"timezone",
")",
"except",
"pytz",
".",
"UnknownTimeZoneError",
":",
"raise",
"DeloreanInvalidTimezone",
"(",
"'Provide a valid timez... | Shifts the timezone from the current timezone to the specified timezone associated with the Delorean object,
modifying the Delorean object and returning the modified object.
.. testsetup::
from datetime import datetime
from delorean import Delorean
.. doctest::
>>> d = Delorean(datetime(2015, 1, 1), timezone='US/Pacific')
>>> d.shift('UTC')
Delorean(datetime=datetime.datetime(2015, 1, 1, 8, 0), timezone='UTC') | [
"Shifts",
"the",
"timezone",
"from",
"the",
"current",
"timezone",
"to",
"the",
"specified",
"timezone",
"associated",
"with",
"the",
"Delorean",
"object",
"modifying",
"the",
"Delorean",
"object",
"and",
"returning",
"the",
"modified",
"object",
"."
] | 3e8a7b8cfd4c26546f62bde2f34002893adfa08a | https://github.com/myusuf3/delorean/blob/3e8a7b8cfd4c26546f62bde2f34002893adfa08a/delorean/dates.py#L466-L489 |
227,425 | myusuf3/delorean | delorean/dates.py | Delorean.epoch | def epoch(self):
"""
Returns the total seconds since epoch associated with
the Delorean object.
.. testsetup::
from datetime import datetime
from delorean import Delorean
.. doctest::
>>> d = Delorean(datetime(2015, 1, 1), timezone='US/Pacific')
>>> d.epoch
1420099200.0
"""
epoch_sec = pytz.utc.localize(datetime.utcfromtimestamp(0))
now_sec = pytz.utc.normalize(self._dt)
delta_sec = now_sec - epoch_sec
return get_total_second(delta_sec) | python | def epoch(self):
epoch_sec = pytz.utc.localize(datetime.utcfromtimestamp(0))
now_sec = pytz.utc.normalize(self._dt)
delta_sec = now_sec - epoch_sec
return get_total_second(delta_sec) | [
"def",
"epoch",
"(",
"self",
")",
":",
"epoch_sec",
"=",
"pytz",
".",
"utc",
".",
"localize",
"(",
"datetime",
".",
"utcfromtimestamp",
"(",
"0",
")",
")",
"now_sec",
"=",
"pytz",
".",
"utc",
".",
"normalize",
"(",
"self",
".",
"_dt",
")",
"delta_sec... | Returns the total seconds since epoch associated with
the Delorean object.
.. testsetup::
from datetime import datetime
from delorean import Delorean
.. doctest::
>>> d = Delorean(datetime(2015, 1, 1), timezone='US/Pacific')
>>> d.epoch
1420099200.0 | [
"Returns",
"the",
"total",
"seconds",
"since",
"epoch",
"associated",
"with",
"the",
"Delorean",
"object",
"."
] | 3e8a7b8cfd4c26546f62bde2f34002893adfa08a | https://github.com/myusuf3/delorean/blob/3e8a7b8cfd4c26546f62bde2f34002893adfa08a/delorean/dates.py#L492-L512 |
227,426 | myusuf3/delorean | delorean/dates.py | Delorean.replace | def replace(self, **kwargs):
"""
Returns a new Delorean object after applying replace on the
existing datetime object.
.. testsetup::
from datetime import datetime
from delorean import Delorean
.. doctest::
>>> d = Delorean(datetime(2015, 1, 1, 12, 15), timezone='UTC')
>>> d.replace(hour=8)
Delorean(datetime=datetime.datetime(2015, 1, 1, 8, 15), timezone='UTC')
"""
return Delorean(datetime=self._dt.replace(**kwargs), timezone=self.timezone) | python | def replace(self, **kwargs):
return Delorean(datetime=self._dt.replace(**kwargs), timezone=self.timezone) | [
"def",
"replace",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"Delorean",
"(",
"datetime",
"=",
"self",
".",
"_dt",
".",
"replace",
"(",
"*",
"*",
"kwargs",
")",
",",
"timezone",
"=",
"self",
".",
"timezone",
")"
] | Returns a new Delorean object after applying replace on the
existing datetime object.
.. testsetup::
from datetime import datetime
from delorean import Delorean
.. doctest::
>>> d = Delorean(datetime(2015, 1, 1, 12, 15), timezone='UTC')
>>> d.replace(hour=8)
Delorean(datetime=datetime.datetime(2015, 1, 1, 8, 15), timezone='UTC') | [
"Returns",
"a",
"new",
"Delorean",
"object",
"after",
"applying",
"replace",
"on",
"the",
"existing",
"datetime",
"object",
"."
] | 3e8a7b8cfd4c26546f62bde2f34002893adfa08a | https://github.com/myusuf3/delorean/blob/3e8a7b8cfd4c26546f62bde2f34002893adfa08a/delorean/dates.py#L553-L570 |
227,427 | myusuf3/delorean | delorean/dates.py | Delorean.format_datetime | def format_datetime(self, format='medium', locale='en_US'):
"""
Return a date string formatted to the given pattern.
.. testsetup::
from delorean import Delorean
.. doctest::
>>> d = Delorean(datetime(2015, 1, 1, 12, 30), timezone='US/Pacific')
>>> d.format_datetime(locale='en_US')
u'Jan 1, 2015, 12:30:00 PM'
>>> d.format_datetime(format='long', locale='de_DE')
u'1. Januar 2015 12:30:00 -0800'
:param format: one of "full", "long", "medium", "short", or a custom datetime pattern
:param locale: a locale identifier
"""
return format_datetime(self._dt, format=format, locale=locale) | python | def format_datetime(self, format='medium', locale='en_US'):
return format_datetime(self._dt, format=format, locale=locale) | [
"def",
"format_datetime",
"(",
"self",
",",
"format",
"=",
"'medium'",
",",
"locale",
"=",
"'en_US'",
")",
":",
"return",
"format_datetime",
"(",
"self",
".",
"_dt",
",",
"format",
"=",
"format",
",",
"locale",
"=",
"locale",
")"
] | Return a date string formatted to the given pattern.
.. testsetup::
from delorean import Delorean
.. doctest::
>>> d = Delorean(datetime(2015, 1, 1, 12, 30), timezone='US/Pacific')
>>> d.format_datetime(locale='en_US')
u'Jan 1, 2015, 12:30:00 PM'
>>> d.format_datetime(format='long', locale='de_DE')
u'1. Januar 2015 12:30:00 -0800'
:param format: one of "full", "long", "medium", "short", or a custom datetime pattern
:param locale: a locale identifier | [
"Return",
"a",
"date",
"string",
"formatted",
"to",
"the",
"given",
"pattern",
"."
] | 3e8a7b8cfd4c26546f62bde2f34002893adfa08a | https://github.com/myusuf3/delorean/blob/3e8a7b8cfd4c26546f62bde2f34002893adfa08a/delorean/dates.py#L592-L613 |
227,428 | Bouke/django-two-factor-auth | two_factor/templatetags/two_factor.py | mask_phone_number | def mask_phone_number(number):
"""
Masks a phone number, only first 3 and last 2 digits visible.
Examples:
* `+31 * ******58`
:param number: str or phonenumber object
:return: str
"""
if isinstance(number, phonenumbers.PhoneNumber):
number = format_phone_number(number)
return phone_mask.sub('*', number) | python | def mask_phone_number(number):
if isinstance(number, phonenumbers.PhoneNumber):
number = format_phone_number(number)
return phone_mask.sub('*', number) | [
"def",
"mask_phone_number",
"(",
"number",
")",
":",
"if",
"isinstance",
"(",
"number",
",",
"phonenumbers",
".",
"PhoneNumber",
")",
":",
"number",
"=",
"format_phone_number",
"(",
"number",
")",
"return",
"phone_mask",
".",
"sub",
"(",
"'*'",
",",
"number"... | Masks a phone number, only first 3 and last 2 digits visible.
Examples:
* `+31 * ******58`
:param number: str or phonenumber object
:return: str | [
"Masks",
"a",
"phone",
"number",
"only",
"first",
"3",
"and",
"last",
"2",
"digits",
"visible",
"."
] | 8fa0c574b5781a724797c89d7f7ba8cbe9fae94a | https://github.com/Bouke/django-two-factor-auth/blob/8fa0c574b5781a724797c89d7f7ba8cbe9fae94a/two_factor/templatetags/two_factor.py#L15-L28 |
227,429 | Bouke/django-two-factor-auth | two_factor/models.py | PhoneDevice.generate_challenge | def generate_challenge(self):
# local import to avoid circular import
from two_factor.utils import totp_digits
"""
Sends the current TOTP token to `self.number` using `self.method`.
"""
no_digits = totp_digits()
token = str(totp(self.bin_key, digits=no_digits)).zfill(no_digits)
if self.method == 'call':
make_call(device=self, token=token)
else:
send_sms(device=self, token=token) | python | def generate_challenge(self):
# local import to avoid circular import
from two_factor.utils import totp_digits
no_digits = totp_digits()
token = str(totp(self.bin_key, digits=no_digits)).zfill(no_digits)
if self.method == 'call':
make_call(device=self, token=token)
else:
send_sms(device=self, token=token) | [
"def",
"generate_challenge",
"(",
"self",
")",
":",
"# local import to avoid circular import",
"from",
"two_factor",
".",
"utils",
"import",
"totp_digits",
"no_digits",
"=",
"totp_digits",
"(",
")",
"token",
"=",
"str",
"(",
"totp",
"(",
"self",
".",
"bin_key",
... | Sends the current TOTP token to `self.number` using `self.method`. | [
"Sends",
"the",
"current",
"TOTP",
"token",
"to",
"self",
".",
"number",
"using",
"self",
".",
"method",
"."
] | 8fa0c574b5781a724797c89d7f7ba8cbe9fae94a | https://github.com/Bouke/django-two-factor-auth/blob/8fa0c574b5781a724797c89d7f7ba8cbe9fae94a/two_factor/models.py#L108-L120 |
227,430 | Bouke/django-two-factor-auth | two_factor/admin.py | AdminSiteOTPRequiredMixin.login | def login(self, request, extra_context=None):
"""
Redirects to the site login page for the given HttpRequest.
"""
redirect_to = request.POST.get(REDIRECT_FIELD_NAME, request.GET.get(REDIRECT_FIELD_NAME))
if not redirect_to or not is_safe_url(url=redirect_to, allowed_hosts=[request.get_host()]):
redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)
return redirect_to_login(redirect_to) | python | def login(self, request, extra_context=None):
redirect_to = request.POST.get(REDIRECT_FIELD_NAME, request.GET.get(REDIRECT_FIELD_NAME))
if not redirect_to or not is_safe_url(url=redirect_to, allowed_hosts=[request.get_host()]):
redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)
return redirect_to_login(redirect_to) | [
"def",
"login",
"(",
"self",
",",
"request",
",",
"extra_context",
"=",
"None",
")",
":",
"redirect_to",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"REDIRECT_FIELD_NAME",
",",
"request",
".",
"GET",
".",
"get",
"(",
"REDIRECT_FIELD_NAME",
")",
")",
"i... | Redirects to the site login page for the given HttpRequest. | [
"Redirects",
"to",
"the",
"site",
"login",
"page",
"for",
"the",
"given",
"HttpRequest",
"."
] | 8fa0c574b5781a724797c89d7f7ba8cbe9fae94a | https://github.com/Bouke/django-two-factor-auth/blob/8fa0c574b5781a724797c89d7f7ba8cbe9fae94a/two_factor/admin.py#L30-L39 |
227,431 | Bouke/django-two-factor-auth | two_factor/views/utils.py | class_view_decorator | def class_view_decorator(function_decorator):
"""
Converts a function based decorator into a class based decorator usable
on class based Views.
Can't subclass the `View` as it breaks inheritance (super in particular),
so we monkey-patch instead.
From: http://stackoverflow.com/a/8429311/58107
"""
def simple_decorator(View):
View.dispatch = method_decorator(function_decorator)(View.dispatch)
return View
return simple_decorator | python | def class_view_decorator(function_decorator):
def simple_decorator(View):
View.dispatch = method_decorator(function_decorator)(View.dispatch)
return View
return simple_decorator | [
"def",
"class_view_decorator",
"(",
"function_decorator",
")",
":",
"def",
"simple_decorator",
"(",
"View",
")",
":",
"View",
".",
"dispatch",
"=",
"method_decorator",
"(",
"function_decorator",
")",
"(",
"View",
".",
"dispatch",
")",
"return",
"View",
"return",... | Converts a function based decorator into a class based decorator usable
on class based Views.
Can't subclass the `View` as it breaks inheritance (super in particular),
so we monkey-patch instead.
From: http://stackoverflow.com/a/8429311/58107 | [
"Converts",
"a",
"function",
"based",
"decorator",
"into",
"a",
"class",
"based",
"decorator",
"usable",
"on",
"class",
"based",
"Views",
"."
] | 8fa0c574b5781a724797c89d7f7ba8cbe9fae94a | https://github.com/Bouke/django-two-factor-auth/blob/8fa0c574b5781a724797c89d7f7ba8cbe9fae94a/two_factor/views/utils.py#L183-L196 |
227,432 | Bouke/django-two-factor-auth | two_factor/views/utils.py | IdempotentSessionWizardView.is_step_visible | def is_step_visible(self, step):
"""
Returns whether the given `step` should be included in the wizard; it
is included if either the form is idempotent or not filled in before.
"""
return self.idempotent_dict.get(step, True) or \
step not in self.storage.validated_step_data | python | def is_step_visible(self, step):
return self.idempotent_dict.get(step, True) or \
step not in self.storage.validated_step_data | [
"def",
"is_step_visible",
"(",
"self",
",",
"step",
")",
":",
"return",
"self",
".",
"idempotent_dict",
".",
"get",
"(",
"step",
",",
"True",
")",
"or",
"step",
"not",
"in",
"self",
".",
"storage",
".",
"validated_step_data"
] | Returns whether the given `step` should be included in the wizard; it
is included if either the form is idempotent or not filled in before. | [
"Returns",
"whether",
"the",
"given",
"step",
"should",
"be",
"included",
"in",
"the",
"wizard",
";",
"it",
"is",
"included",
"if",
"either",
"the",
"form",
"is",
"idempotent",
"or",
"not",
"filled",
"in",
"before",
"."
] | 8fa0c574b5781a724797c89d7f7ba8cbe9fae94a | https://github.com/Bouke/django-two-factor-auth/blob/8fa0c574b5781a724797c89d7f7ba8cbe9fae94a/two_factor/views/utils.py#L48-L54 |
227,433 | Bouke/django-two-factor-auth | two_factor/views/utils.py | IdempotentSessionWizardView.post | def post(self, *args, **kwargs):
"""
Check if the current step is still available. It might not be if
conditions have changed.
"""
if self.steps.current not in self.steps.all:
logger.warning("Current step '%s' is no longer valid, returning "
"to last valid step in the wizard.",
self.steps.current)
return self.render_goto_step(self.steps.all[-1])
# -- Duplicated code from upstream
# Look for a wizard_goto_step element in the posted data which
# contains a valid step name. If one was found, render the requested
# form. (This makes stepping back a lot easier).
wizard_goto_step = self.request.POST.get('wizard_goto_step', None)
if wizard_goto_step and wizard_goto_step in self.get_form_list():
return self.render_goto_step(wizard_goto_step)
# Check if form was refreshed
management_form = ManagementForm(self.request.POST, prefix=self.prefix)
if not management_form.is_valid():
raise SuspiciousOperation(_('ManagementForm data is missing or has been tampered with'))
form_current_step = management_form.cleaned_data['current_step']
if (form_current_step != self.steps.current and
self.storage.current_step is not None):
# form refreshed, change current step
self.storage.current_step = form_current_step
# -- End duplicated code from upstream
# This is different from the first check, as this checks
# if the new step is available. See issue #65.
if self.steps.current not in self.steps.all:
logger.warning("Requested step '%s' is no longer valid, returning "
"to last valid step in the wizard.",
self.steps.current)
return self.render_goto_step(self.steps.all[-1])
return super(IdempotentSessionWizardView, self).post(*args, **kwargs) | python | def post(self, *args, **kwargs):
if self.steps.current not in self.steps.all:
logger.warning("Current step '%s' is no longer valid, returning "
"to last valid step in the wizard.",
self.steps.current)
return self.render_goto_step(self.steps.all[-1])
# -- Duplicated code from upstream
# Look for a wizard_goto_step element in the posted data which
# contains a valid step name. If one was found, render the requested
# form. (This makes stepping back a lot easier).
wizard_goto_step = self.request.POST.get('wizard_goto_step', None)
if wizard_goto_step and wizard_goto_step in self.get_form_list():
return self.render_goto_step(wizard_goto_step)
# Check if form was refreshed
management_form = ManagementForm(self.request.POST, prefix=self.prefix)
if not management_form.is_valid():
raise SuspiciousOperation(_('ManagementForm data is missing or has been tampered with'))
form_current_step = management_form.cleaned_data['current_step']
if (form_current_step != self.steps.current and
self.storage.current_step is not None):
# form refreshed, change current step
self.storage.current_step = form_current_step
# -- End duplicated code from upstream
# This is different from the first check, as this checks
# if the new step is available. See issue #65.
if self.steps.current not in self.steps.all:
logger.warning("Requested step '%s' is no longer valid, returning "
"to last valid step in the wizard.",
self.steps.current)
return self.render_goto_step(self.steps.all[-1])
return super(IdempotentSessionWizardView, self).post(*args, **kwargs) | [
"def",
"post",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"steps",
".",
"current",
"not",
"in",
"self",
".",
"steps",
".",
"all",
":",
"logger",
".",
"warning",
"(",
"\"Current step '%s' is no longer valid, retur... | Check if the current step is still available. It might not be if
conditions have changed. | [
"Check",
"if",
"the",
"current",
"step",
"is",
"still",
"available",
".",
"It",
"might",
"not",
"be",
"if",
"conditions",
"have",
"changed",
"."
] | 8fa0c574b5781a724797c89d7f7ba8cbe9fae94a | https://github.com/Bouke/django-two-factor-auth/blob/8fa0c574b5781a724797c89d7f7ba8cbe9fae94a/two_factor/views/utils.py#L89-L128 |
227,434 | Bouke/django-two-factor-auth | two_factor/views/utils.py | IdempotentSessionWizardView.process_step | def process_step(self, form):
"""
Stores the validated data for `form` and cleans out validated forms
for next steps, as those might be affected by the current step. Note
that this behaviour is relied upon by the `LoginView` to prevent users
from bypassing the `TokenForm` by going steps back and changing
credentials.
"""
step = self.steps.current
# If the form is not-idempotent (cannot be validated multiple times),
# the cleaned data should be stored; marking the form as validated.
self.storage.validated_step_data[step] = form.cleaned_data
# It is assumed that earlier steps affect later steps; so even though
# those forms might not be idempotent, we'll remove the validated data
# to force re-entry.
# form_list = self.get_form_list(idempotent=False)
form_list = self.get_form_list()
keys = list(form_list.keys())
key = keys.index(step) + 1
for next_step in keys[key:]:
self.storage.validated_step_data.pop(next_step, None)
return super(IdempotentSessionWizardView, self).process_step(form) | python | def process_step(self, form):
step = self.steps.current
# If the form is not-idempotent (cannot be validated multiple times),
# the cleaned data should be stored; marking the form as validated.
self.storage.validated_step_data[step] = form.cleaned_data
# It is assumed that earlier steps affect later steps; so even though
# those forms might not be idempotent, we'll remove the validated data
# to force re-entry.
# form_list = self.get_form_list(idempotent=False)
form_list = self.get_form_list()
keys = list(form_list.keys())
key = keys.index(step) + 1
for next_step in keys[key:]:
self.storage.validated_step_data.pop(next_step, None)
return super(IdempotentSessionWizardView, self).process_step(form) | [
"def",
"process_step",
"(",
"self",
",",
"form",
")",
":",
"step",
"=",
"self",
".",
"steps",
".",
"current",
"# If the form is not-idempotent (cannot be validated multiple times),",
"# the cleaned data should be stored; marking the form as validated.",
"self",
".",
"storage",
... | Stores the validated data for `form` and cleans out validated forms
for next steps, as those might be affected by the current step. Note
that this behaviour is relied upon by the `LoginView` to prevent users
from bypassing the `TokenForm` by going steps back and changing
credentials. | [
"Stores",
"the",
"validated",
"data",
"for",
"form",
"and",
"cleans",
"out",
"validated",
"forms",
"for",
"next",
"steps",
"as",
"those",
"might",
"be",
"affected",
"by",
"the",
"current",
"step",
".",
"Note",
"that",
"this",
"behaviour",
"is",
"relied",
"... | 8fa0c574b5781a724797c89d7f7ba8cbe9fae94a | https://github.com/Bouke/django-two-factor-auth/blob/8fa0c574b5781a724797c89d7f7ba8cbe9fae94a/two_factor/views/utils.py#L130-L154 |
227,435 | aviaryan/python-gsearch | gsearch/googlesearch.py | download | def download(query, num_results):
"""
downloads HTML after google search
"""
# https://stackoverflow.com/questions/11818362/how-to-deal-with-unicode-string-in-url-in-python3
name = quote(query)
name = name.replace(' ','+')
url = 'http://www.google.com/search?q=' + name
if num_results != 10:
url += '&num=' + str(num_results) # adding this param might hint Google towards a bot
req = request.Request(url, headers={
'User-Agent' : choice(user_agents),
# 'Referer': 'google.com'
})
try:
response = request.urlopen(req)
except Exception: # catch connection issues
# may also catch 503 rate limit exceed
print('ERROR\n')
traceback.print_exc()
return ''
# response.read is bytes in Py 3
if isPython2:
# trick: decode unicode as early as possible
data = response.read().decode('utf8', errors='ignore')
else:
data = str(response.read(), 'utf-8', errors='ignore')
# print(data)
return data | python | def download(query, num_results):
# https://stackoverflow.com/questions/11818362/how-to-deal-with-unicode-string-in-url-in-python3
name = quote(query)
name = name.replace(' ','+')
url = 'http://www.google.com/search?q=' + name
if num_results != 10:
url += '&num=' + str(num_results) # adding this param might hint Google towards a bot
req = request.Request(url, headers={
'User-Agent' : choice(user_agents),
# 'Referer': 'google.com'
})
try:
response = request.urlopen(req)
except Exception: # catch connection issues
# may also catch 503 rate limit exceed
print('ERROR\n')
traceback.print_exc()
return ''
# response.read is bytes in Py 3
if isPython2:
# trick: decode unicode as early as possible
data = response.read().decode('utf8', errors='ignore')
else:
data = str(response.read(), 'utf-8', errors='ignore')
# print(data)
return data | [
"def",
"download",
"(",
"query",
",",
"num_results",
")",
":",
"# https://stackoverflow.com/questions/11818362/how-to-deal-with-unicode-string-in-url-in-python3",
"name",
"=",
"quote",
"(",
"query",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"' '",
",",
"'+'",
")"... | downloads HTML after google search | [
"downloads",
"HTML",
"after",
"google",
"search"
] | fba2f42fbf4c2672b72d05b53120adcb25ba8b69 | https://github.com/aviaryan/python-gsearch/blob/fba2f42fbf4c2672b72d05b53120adcb25ba8b69/gsearch/googlesearch.py#L36-L65 |
227,436 | aviaryan/python-gsearch | gsearch/googlesearch.py | convert_unicode | def convert_unicode(text):
"""
converts unicode HTML to real Unicode
"""
if isPython2:
h = HTMLParser()
s = h.unescape(text)
else:
try:
s = unescape(text)
except Exception:
# Python 3.3 and below
# https://stackoverflow.com/a/2360639/2295672
s = HTMLParser().unescape(text)
return s | python | def convert_unicode(text):
if isPython2:
h = HTMLParser()
s = h.unescape(text)
else:
try:
s = unescape(text)
except Exception:
# Python 3.3 and below
# https://stackoverflow.com/a/2360639/2295672
s = HTMLParser().unescape(text)
return s | [
"def",
"convert_unicode",
"(",
"text",
")",
":",
"if",
"isPython2",
":",
"h",
"=",
"HTMLParser",
"(",
")",
"s",
"=",
"h",
".",
"unescape",
"(",
"text",
")",
"else",
":",
"try",
":",
"s",
"=",
"unescape",
"(",
"text",
")",
"except",
"Exception",
":"... | converts unicode HTML to real Unicode | [
"converts",
"unicode",
"HTML",
"to",
"real",
"Unicode"
] | fba2f42fbf4c2672b72d05b53120adcb25ba8b69 | https://github.com/aviaryan/python-gsearch/blob/fba2f42fbf4c2672b72d05b53120adcb25ba8b69/gsearch/googlesearch.py#L84-L98 |
227,437 | mingchen/django-cas-ng | django_cas_ng/decorators.py | permission_required | def permission_required(perm, login_url=None):
"""Replacement for django.contrib.auth.decorators.permission_required that
returns 403 Forbidden if the user is already logged in.
"""
return user_passes_test(lambda u: u.has_perm(perm), login_url=login_url) | python | def permission_required(perm, login_url=None):
return user_passes_test(lambda u: u.has_perm(perm), login_url=login_url) | [
"def",
"permission_required",
"(",
"perm",
",",
"login_url",
"=",
"None",
")",
":",
"return",
"user_passes_test",
"(",
"lambda",
"u",
":",
"u",
".",
"has_perm",
"(",
"perm",
")",
",",
"login_url",
"=",
"login_url",
")"
] | Replacement for django.contrib.auth.decorators.permission_required that
returns 403 Forbidden if the user is already logged in. | [
"Replacement",
"for",
"django",
".",
"contrib",
".",
"auth",
".",
"decorators",
".",
"permission_required",
"that",
"returns",
"403",
"Forbidden",
"if",
"the",
"user",
"is",
"already",
"logged",
"in",
"."
] | 202ca92cd770d9679bfe4e9e20b41fd19b81c311 | https://github.com/mingchen/django-cas-ng/blob/202ca92cd770d9679bfe4e9e20b41fd19b81c311/django_cas_ng/decorators.py#L41-L46 |
227,438 | mingchen/django-cas-ng | django_cas_ng/backends.py | CASBackend.authenticate | def authenticate(self, request, ticket, service):
"""Verifies CAS ticket and gets or creates User object"""
client = get_cas_client(service_url=service, request=request)
username, attributes, pgtiou = client.verify_ticket(ticket)
if attributes and request:
request.session['attributes'] = attributes
if settings.CAS_USERNAME_ATTRIBUTE != 'uid' and settings.CAS_VERSION != 'CAS_2_SAML_1_0':
if attributes:
username = attributes.get(settings.CAS_USERNAME_ATTRIBUTE)
else:
return None
if not username:
return None
user = None
username = self.clean_username(username)
if attributes:
reject = self.bad_attributes_reject(request, username, attributes)
if reject:
return None
# If we can, we rename the attributes as described in the settings file
# Existing attributes will be overwritten
for cas_attr_name, req_attr_name in settings.CAS_RENAME_ATTRIBUTES.items():
if cas_attr_name in attributes and cas_attr_name is not req_attr_name:
attributes[req_attr_name] = attributes[cas_attr_name]
attributes.pop(cas_attr_name)
UserModel = get_user_model()
# Note that this could be accomplished in one try-except clause, but
# instead we use get_or_create when creating unknown users since it has
# built-in safeguards for multiple threads.
if settings.CAS_CREATE_USER:
user_kwargs = {
UserModel.USERNAME_FIELD: username
}
if settings.CAS_CREATE_USER_WITH_ID:
user_kwargs['id'] = self.get_user_id(attributes)
user, created = UserModel._default_manager.get_or_create(**user_kwargs)
if created:
user = self.configure_user(user)
else:
created = False
try:
if settings.CAS_LOCAL_NAME_FIELD:
user_kwargs = {
settings.CAS_LOCAL_NAME_FIELD: username
}
user = UserModel._default_manager.get(**user_kwargs)
else:
user = UserModel._default_manager.get_by_natural_key(username)
except UserModel.DoesNotExist:
pass
if not self.user_can_authenticate(user):
return None
if pgtiou and settings.CAS_PROXY_CALLBACK and request:
request.session['pgtiou'] = pgtiou
if settings.CAS_APPLY_ATTRIBUTES_TO_USER and attributes:
# If we are receiving None for any values which cannot be NULL
# in the User model, set them to an empty string instead.
# Possibly it would be desirable to let these throw an error
# and push the responsibility to the CAS provider or remove
# them from the dictionary entirely instead. Handling these
# is a little ambiguous.
user_model_fields = UserModel._meta.fields
for field in user_model_fields:
# Handle null -> '' conversions mentioned above
if not field.null:
try:
if attributes[field.name] is None:
attributes[field.name] = ''
except KeyError:
continue
# Coerce boolean strings into true booleans
if field.get_internal_type() == 'BooleanField':
try:
boolean_value = attributes[field.name] == 'True'
attributes[field.name] = boolean_value
except KeyError:
continue
user.__dict__.update(attributes)
# If we are keeping a local copy of the user model we
# should save these attributes which have a corresponding
# instance in the DB.
if settings.CAS_CREATE_USER:
user.save()
# send the `cas_user_authenticated` signal
cas_user_authenticated.send(
sender=self,
user=user,
created=created,
username=username,
attributes=attributes,
pgtiou=pgtiou,
ticket=ticket,
service=service,
request=request
)
return user | python | def authenticate(self, request, ticket, service):
client = get_cas_client(service_url=service, request=request)
username, attributes, pgtiou = client.verify_ticket(ticket)
if attributes and request:
request.session['attributes'] = attributes
if settings.CAS_USERNAME_ATTRIBUTE != 'uid' and settings.CAS_VERSION != 'CAS_2_SAML_1_0':
if attributes:
username = attributes.get(settings.CAS_USERNAME_ATTRIBUTE)
else:
return None
if not username:
return None
user = None
username = self.clean_username(username)
if attributes:
reject = self.bad_attributes_reject(request, username, attributes)
if reject:
return None
# If we can, we rename the attributes as described in the settings file
# Existing attributes will be overwritten
for cas_attr_name, req_attr_name in settings.CAS_RENAME_ATTRIBUTES.items():
if cas_attr_name in attributes and cas_attr_name is not req_attr_name:
attributes[req_attr_name] = attributes[cas_attr_name]
attributes.pop(cas_attr_name)
UserModel = get_user_model()
# Note that this could be accomplished in one try-except clause, but
# instead we use get_or_create when creating unknown users since it has
# built-in safeguards for multiple threads.
if settings.CAS_CREATE_USER:
user_kwargs = {
UserModel.USERNAME_FIELD: username
}
if settings.CAS_CREATE_USER_WITH_ID:
user_kwargs['id'] = self.get_user_id(attributes)
user, created = UserModel._default_manager.get_or_create(**user_kwargs)
if created:
user = self.configure_user(user)
else:
created = False
try:
if settings.CAS_LOCAL_NAME_FIELD:
user_kwargs = {
settings.CAS_LOCAL_NAME_FIELD: username
}
user = UserModel._default_manager.get(**user_kwargs)
else:
user = UserModel._default_manager.get_by_natural_key(username)
except UserModel.DoesNotExist:
pass
if not self.user_can_authenticate(user):
return None
if pgtiou and settings.CAS_PROXY_CALLBACK and request:
request.session['pgtiou'] = pgtiou
if settings.CAS_APPLY_ATTRIBUTES_TO_USER and attributes:
# If we are receiving None for any values which cannot be NULL
# in the User model, set them to an empty string instead.
# Possibly it would be desirable to let these throw an error
# and push the responsibility to the CAS provider or remove
# them from the dictionary entirely instead. Handling these
# is a little ambiguous.
user_model_fields = UserModel._meta.fields
for field in user_model_fields:
# Handle null -> '' conversions mentioned above
if not field.null:
try:
if attributes[field.name] is None:
attributes[field.name] = ''
except KeyError:
continue
# Coerce boolean strings into true booleans
if field.get_internal_type() == 'BooleanField':
try:
boolean_value = attributes[field.name] == 'True'
attributes[field.name] = boolean_value
except KeyError:
continue
user.__dict__.update(attributes)
# If we are keeping a local copy of the user model we
# should save these attributes which have a corresponding
# instance in the DB.
if settings.CAS_CREATE_USER:
user.save()
# send the `cas_user_authenticated` signal
cas_user_authenticated.send(
sender=self,
user=user,
created=created,
username=username,
attributes=attributes,
pgtiou=pgtiou,
ticket=ticket,
service=service,
request=request
)
return user | [
"def",
"authenticate",
"(",
"self",
",",
"request",
",",
"ticket",
",",
"service",
")",
":",
"client",
"=",
"get_cas_client",
"(",
"service_url",
"=",
"service",
",",
"request",
"=",
"request",
")",
"username",
",",
"attributes",
",",
"pgtiou",
"=",
"clien... | Verifies CAS ticket and gets or creates User object | [
"Verifies",
"CAS",
"ticket",
"and",
"gets",
"or",
"creates",
"User",
"object"
] | 202ca92cd770d9679bfe4e9e20b41fd19b81c311 | https://github.com/mingchen/django-cas-ng/blob/202ca92cd770d9679bfe4e9e20b41fd19b81c311/django_cas_ng/backends.py#L18-L127 |
227,439 | mingchen/django-cas-ng | django_cas_ng/backends.py | CASBackend.get_user_id | def get_user_id(self, attributes):
"""
For use when CAS_CREATE_USER_WITH_ID is True. Will raise ImproperlyConfigured
exceptions when a user_id cannot be accessed. This is important because we
shouldn't create Users with automatically assigned ids if we are trying to
keep User primary key's in sync.
"""
if not attributes:
raise ImproperlyConfigured("CAS_CREATE_USER_WITH_ID is True, but "
"no attributes were provided")
user_id = attributes.get('id')
if not user_id:
raise ImproperlyConfigured("CAS_CREATE_USER_WITH_ID is True, but "
"`'id'` is not part of attributes.")
return user_id | python | def get_user_id(self, attributes):
if not attributes:
raise ImproperlyConfigured("CAS_CREATE_USER_WITH_ID is True, but "
"no attributes were provided")
user_id = attributes.get('id')
if not user_id:
raise ImproperlyConfigured("CAS_CREATE_USER_WITH_ID is True, but "
"`'id'` is not part of attributes.")
return user_id | [
"def",
"get_user_id",
"(",
"self",
",",
"attributes",
")",
":",
"if",
"not",
"attributes",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"CAS_CREATE_USER_WITH_ID is True, but \"",
"\"no attributes were provided\"",
")",
"user_id",
"=",
"attributes",
".",
"get",
"(",
"'... | For use when CAS_CREATE_USER_WITH_ID is True. Will raise ImproperlyConfigured
exceptions when a user_id cannot be accessed. This is important because we
shouldn't create Users with automatically assigned ids if we are trying to
keep User primary key's in sync. | [
"For",
"use",
"when",
"CAS_CREATE_USER_WITH_ID",
"is",
"True",
".",
"Will",
"raise",
"ImproperlyConfigured",
"exceptions",
"when",
"a",
"user_id",
"cannot",
"be",
"accessed",
".",
"This",
"is",
"important",
"because",
"we",
"shouldn",
"t",
"create",
"Users",
"wi... | 202ca92cd770d9679bfe4e9e20b41fd19b81c311 | https://github.com/mingchen/django-cas-ng/blob/202ca92cd770d9679bfe4e9e20b41fd19b81c311/django_cas_ng/backends.py#L136-L153 |
227,440 | mingchen/django-cas-ng | django_cas_ng/backends.py | CASBackend.clean_username | def clean_username(self, username):
"""
Performs any cleaning on the "username" prior to using it to get or
create the user object. Returns the cleaned username.
By default, changes the username case according to
`settings.CAS_FORCE_CHANGE_USERNAME_CASE`.
"""
username_case = settings.CAS_FORCE_CHANGE_USERNAME_CASE
if username_case == 'lower':
username = username.lower()
elif username_case == 'upper':
username = username.upper()
elif username_case is not None:
raise ImproperlyConfigured(
"Invalid value for the CAS_FORCE_CHANGE_USERNAME_CASE setting. "
"Valid values are `'lower'`, `'upper'`, and `None`.")
return username | python | def clean_username(self, username):
username_case = settings.CAS_FORCE_CHANGE_USERNAME_CASE
if username_case == 'lower':
username = username.lower()
elif username_case == 'upper':
username = username.upper()
elif username_case is not None:
raise ImproperlyConfigured(
"Invalid value for the CAS_FORCE_CHANGE_USERNAME_CASE setting. "
"Valid values are `'lower'`, `'upper'`, and `None`.")
return username | [
"def",
"clean_username",
"(",
"self",
",",
"username",
")",
":",
"username_case",
"=",
"settings",
".",
"CAS_FORCE_CHANGE_USERNAME_CASE",
"if",
"username_case",
"==",
"'lower'",
":",
"username",
"=",
"username",
".",
"lower",
"(",
")",
"elif",
"username_case",
"... | Performs any cleaning on the "username" prior to using it to get or
create the user object. Returns the cleaned username.
By default, changes the username case according to
`settings.CAS_FORCE_CHANGE_USERNAME_CASE`. | [
"Performs",
"any",
"cleaning",
"on",
"the",
"username",
"prior",
"to",
"using",
"it",
"to",
"get",
"or",
"create",
"the",
"user",
"object",
".",
"Returns",
"the",
"cleaned",
"username",
"."
] | 202ca92cd770d9679bfe4e9e20b41fd19b81c311 | https://github.com/mingchen/django-cas-ng/blob/202ca92cd770d9679bfe4e9e20b41fd19b81c311/django_cas_ng/backends.py#L155-L172 |
227,441 | mingchen/django-cas-ng | django_cas_ng/utils.py | get_service_url | def get_service_url(request, redirect_to=None):
"""Generates application django service URL for CAS"""
if hasattr(django_settings, 'CAS_ROOT_PROXIED_AS'):
service = django_settings.CAS_ROOT_PROXIED_AS + request.path
else:
protocol = get_protocol(request)
host = request.get_host()
service = urllib_parse.urlunparse(
(protocol, host, request.path, '', '', ''),
)
if not django_settings.CAS_STORE_NEXT:
if '?' in service:
service += '&'
else:
service += '?'
service += urllib_parse.urlencode({
REDIRECT_FIELD_NAME: redirect_to or get_redirect_url(request)
})
return service | python | def get_service_url(request, redirect_to=None):
if hasattr(django_settings, 'CAS_ROOT_PROXIED_AS'):
service = django_settings.CAS_ROOT_PROXIED_AS + request.path
else:
protocol = get_protocol(request)
host = request.get_host()
service = urllib_parse.urlunparse(
(protocol, host, request.path, '', '', ''),
)
if not django_settings.CAS_STORE_NEXT:
if '?' in service:
service += '&'
else:
service += '?'
service += urllib_parse.urlencode({
REDIRECT_FIELD_NAME: redirect_to or get_redirect_url(request)
})
return service | [
"def",
"get_service_url",
"(",
"request",
",",
"redirect_to",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"django_settings",
",",
"'CAS_ROOT_PROXIED_AS'",
")",
":",
"service",
"=",
"django_settings",
".",
"CAS_ROOT_PROXIED_AS",
"+",
"request",
".",
"path",
"els... | Generates application django service URL for CAS | [
"Generates",
"application",
"django",
"service",
"URL",
"for",
"CAS"
] | 202ca92cd770d9679bfe4e9e20b41fd19b81c311 | https://github.com/mingchen/django-cas-ng/blob/202ca92cd770d9679bfe4e9e20b41fd19b81c311/django_cas_ng/utils.py#L43-L61 |
227,442 | mingchen/django-cas-ng | django_cas_ng/models.py | ProxyGrantingTicket.retrieve_pt | def retrieve_pt(cls, request, service):
"""`request` should be the current HttpRequest object
`service` a string representing the service for witch we want to
retrieve a ticket.
The function return a Proxy Ticket or raise `ProxyError`
"""
try:
pgt = cls.objects.get(user=request.user, session_key=request.session.session_key).pgt
except cls.DoesNotExist:
raise ProxyError(
"INVALID_TICKET",
"No proxy ticket found for this HttpRequest object"
)
else:
client = get_cas_client(service_url=service, request=request)
try:
return client.get_proxy_ticket(pgt)
# change CASError to ProxyError nicely
except CASError as error:
raise ProxyError(*error.args)
# just embed other errors
except Exception as e:
raise ProxyError(e) | python | def retrieve_pt(cls, request, service):
try:
pgt = cls.objects.get(user=request.user, session_key=request.session.session_key).pgt
except cls.DoesNotExist:
raise ProxyError(
"INVALID_TICKET",
"No proxy ticket found for this HttpRequest object"
)
else:
client = get_cas_client(service_url=service, request=request)
try:
return client.get_proxy_ticket(pgt)
# change CASError to ProxyError nicely
except CASError as error:
raise ProxyError(*error.args)
# just embed other errors
except Exception as e:
raise ProxyError(e) | [
"def",
"retrieve_pt",
"(",
"cls",
",",
"request",
",",
"service",
")",
":",
"try",
":",
"pgt",
"=",
"cls",
".",
"objects",
".",
"get",
"(",
"user",
"=",
"request",
".",
"user",
",",
"session_key",
"=",
"request",
".",
"session",
".",
"session_key",
"... | `request` should be the current HttpRequest object
`service` a string representing the service for witch we want to
retrieve a ticket.
The function return a Proxy Ticket or raise `ProxyError` | [
"request",
"should",
"be",
"the",
"current",
"HttpRequest",
"object",
"service",
"a",
"string",
"representing",
"the",
"service",
"for",
"witch",
"we",
"want",
"to",
"retrieve",
"a",
"ticket",
".",
"The",
"function",
"return",
"a",
"Proxy",
"Ticket",
"or",
"... | 202ca92cd770d9679bfe4e9e20b41fd19b81c311 | https://github.com/mingchen/django-cas-ng/blob/202ca92cd770d9679bfe4e9e20b41fd19b81c311/django_cas_ng/models.py#L41-L63 |
227,443 | rtfd/recommonmark | recommonmark/states.py | DummyStateMachine.reset | def reset(self, document, parent, level):
"""Reset the state of state machine.
After reset, self and self.state can be used to
passed to docutils.parsers.rst.Directive.run
Parameters
----------
document: docutils document
Current document of the node.
parent: parent node
Parent node that will be used to interpret role and directives.
level: int
Current section level.
"""
self.language = languages.get_language(
document.settings.language_code)
# setup memo
self.memo.document = document
self.memo.reporter = document.reporter
self.memo.language = self.language
self.memo.section_level = level
# setup inliner
if self.memo.inliner is None:
self.memo.inliner = Inliner()
self.memo.inliner.init_customizations(document.settings)
inliner = self.memo.inliner
inliner.reporter = document.reporter
inliner.document = document
inliner.language = self.language
inliner.parent = parent
# setup self
self.document = document
self.reporter = self.memo.reporter
self.node = parent
self.state.runtime_init()
self.input_lines = document['source'] | python | def reset(self, document, parent, level):
self.language = languages.get_language(
document.settings.language_code)
# setup memo
self.memo.document = document
self.memo.reporter = document.reporter
self.memo.language = self.language
self.memo.section_level = level
# setup inliner
if self.memo.inliner is None:
self.memo.inliner = Inliner()
self.memo.inliner.init_customizations(document.settings)
inliner = self.memo.inliner
inliner.reporter = document.reporter
inliner.document = document
inliner.language = self.language
inliner.parent = parent
# setup self
self.document = document
self.reporter = self.memo.reporter
self.node = parent
self.state.runtime_init()
self.input_lines = document['source'] | [
"def",
"reset",
"(",
"self",
",",
"document",
",",
"parent",
",",
"level",
")",
":",
"self",
".",
"language",
"=",
"languages",
".",
"get_language",
"(",
"document",
".",
"settings",
".",
"language_code",
")",
"# setup memo",
"self",
".",
"memo",
".",
"d... | Reset the state of state machine.
After reset, self and self.state can be used to
passed to docutils.parsers.rst.Directive.run
Parameters
----------
document: docutils document
Current document of the node.
parent: parent node
Parent node that will be used to interpret role and directives.
level: int
Current section level. | [
"Reset",
"the",
"state",
"of",
"state",
"machine",
"."
] | 815d75ea503f30af26ab67c6820078f84875b1fc | https://github.com/rtfd/recommonmark/blob/815d75ea503f30af26ab67c6820078f84875b1fc/recommonmark/states.py#L26-L62 |
227,444 | rtfd/recommonmark | recommonmark/states.py | DummyStateMachine.run_directive | def run_directive(self, name,
arguments=None,
options=None,
content=None):
"""Generate directive node given arguments.
Parameters
----------
name : str
name of directive.
arguments : list
list of positional arguments.
options : dict
key value arguments.
content : content
content of the directive
Returns
-------
node : docutil Node
Node generated by the arguments.
"""
if options is None:
options = {}
if content is None:
content = []
if arguments is None:
arguments = []
direc, _ = directive(name, self.language, self.document)
direc = direc(name=name,
arguments=arguments,
options=options,
content=content,
lineno=self.node.line,
content_offset=0,
block_text='Dummy BlockText',
state=self.state,
state_machine=self)
return direc.run() | python | def run_directive(self, name,
arguments=None,
options=None,
content=None):
if options is None:
options = {}
if content is None:
content = []
if arguments is None:
arguments = []
direc, _ = directive(name, self.language, self.document)
direc = direc(name=name,
arguments=arguments,
options=options,
content=content,
lineno=self.node.line,
content_offset=0,
block_text='Dummy BlockText',
state=self.state,
state_machine=self)
return direc.run() | [
"def",
"run_directive",
"(",
"self",
",",
"name",
",",
"arguments",
"=",
"None",
",",
"options",
"=",
"None",
",",
"content",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"if",
"content",
"is",
"None",
":",
"... | Generate directive node given arguments.
Parameters
----------
name : str
name of directive.
arguments : list
list of positional arguments.
options : dict
key value arguments.
content : content
content of the directive
Returns
-------
node : docutil Node
Node generated by the arguments. | [
"Generate",
"directive",
"node",
"given",
"arguments",
"."
] | 815d75ea503f30af26ab67c6820078f84875b1fc | https://github.com/rtfd/recommonmark/blob/815d75ea503f30af26ab67c6820078f84875b1fc/recommonmark/states.py#L64-L102 |
227,445 | rtfd/recommonmark | recommonmark/states.py | DummyStateMachine.run_role | def run_role(self, name,
options=None,
content=None):
"""Generate a role node.
options : dict
key value arguments.
content : content
content of the directive
Returns
-------
node : docutil Node
Node generated by the arguments.
"""
if options is None:
options = {}
if content is None:
content = []
role_fn, _ = role(name,
self.language,
self.node.line,
self.reporter)
vec, _ = role_fn(name,
rawtext=str(content),
text=str(content),
lineno=self.node.line,
inliner=self.memo.inliner,
options=options,
content=content)
assert len(vec) == 1, 'only support one list in role'
return vec[0] | python | def run_role(self, name,
options=None,
content=None):
if options is None:
options = {}
if content is None:
content = []
role_fn, _ = role(name,
self.language,
self.node.line,
self.reporter)
vec, _ = role_fn(name,
rawtext=str(content),
text=str(content),
lineno=self.node.line,
inliner=self.memo.inliner,
options=options,
content=content)
assert len(vec) == 1, 'only support one list in role'
return vec[0] | [
"def",
"run_role",
"(",
"self",
",",
"name",
",",
"options",
"=",
"None",
",",
"content",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"if",
"content",
"is",
"None",
":",
"content",
"=",
"[",
"]",
"role_fn",
... | Generate a role node.
options : dict
key value arguments.
content : content
content of the directive
Returns
-------
node : docutil Node
Node generated by the arguments. | [
"Generate",
"a",
"role",
"node",
"."
] | 815d75ea503f30af26ab67c6820078f84875b1fc | https://github.com/rtfd/recommonmark/blob/815d75ea503f30af26ab67c6820078f84875b1fc/recommonmark/states.py#L104-L135 |
227,446 | rtfd/recommonmark | recommonmark/parser.py | CommonMarkParser.default_depart | def default_depart(self, mdnode):
"""Default node depart handler
If there is a matching ``visit_<type>`` method for a container node,
then we should make sure to back up to it's parent element when the node
is exited.
"""
if mdnode.is_container():
fn_name = 'visit_{0}'.format(mdnode.t)
if not hasattr(self, fn_name):
warn("Container node skipped: type={0}".format(mdnode.t))
else:
self.current_node = self.current_node.parent | python | def default_depart(self, mdnode):
if mdnode.is_container():
fn_name = 'visit_{0}'.format(mdnode.t)
if not hasattr(self, fn_name):
warn("Container node skipped: type={0}".format(mdnode.t))
else:
self.current_node = self.current_node.parent | [
"def",
"default_depart",
"(",
"self",
",",
"mdnode",
")",
":",
"if",
"mdnode",
".",
"is_container",
"(",
")",
":",
"fn_name",
"=",
"'visit_{0}'",
".",
"format",
"(",
"mdnode",
".",
"t",
")",
"if",
"not",
"hasattr",
"(",
"self",
",",
"fn_name",
")",
"... | Default node depart handler
If there is a matching ``visit_<type>`` method for a container node,
then we should make sure to back up to it's parent element when the node
is exited. | [
"Default",
"node",
"depart",
"handler"
] | 815d75ea503f30af26ab67c6820078f84875b1fc | https://github.com/rtfd/recommonmark/blob/815d75ea503f30af26ab67c6820078f84875b1fc/recommonmark/parser.py#L55-L67 |
227,447 | rtfd/recommonmark | recommonmark/parser.py | CommonMarkParser.depart_heading | def depart_heading(self, _):
"""Finish establishing section
Wrap up title node, but stick in the section node. Add the section names
based on all the text nodes added to the title.
"""
assert isinstance(self.current_node, nodes.title)
# The title node has a tree of text nodes, use the whole thing to
# determine the section id and names
text = self.current_node.astext()
if self.translate_section_name:
text = self.translate_section_name(text)
name = nodes.fully_normalize_name(text)
section = self.current_node.parent
section['names'].append(name)
self.document.note_implicit_target(section, section)
self.current_node = section | python | def depart_heading(self, _):
assert isinstance(self.current_node, nodes.title)
# The title node has a tree of text nodes, use the whole thing to
# determine the section id and names
text = self.current_node.astext()
if self.translate_section_name:
text = self.translate_section_name(text)
name = nodes.fully_normalize_name(text)
section = self.current_node.parent
section['names'].append(name)
self.document.note_implicit_target(section, section)
self.current_node = section | [
"def",
"depart_heading",
"(",
"self",
",",
"_",
")",
":",
"assert",
"isinstance",
"(",
"self",
".",
"current_node",
",",
"nodes",
".",
"title",
")",
"# The title node has a tree of text nodes, use the whole thing to",
"# determine the section id and names",
"text",
"=",
... | Finish establishing section
Wrap up title node, but stick in the section node. Add the section names
based on all the text nodes added to the title. | [
"Finish",
"establishing",
"section"
] | 815d75ea503f30af26ab67c6820078f84875b1fc | https://github.com/rtfd/recommonmark/blob/815d75ea503f30af26ab67c6820078f84875b1fc/recommonmark/parser.py#L88-L104 |
227,448 | rtfd/recommonmark | recommonmark/transform.py | AutoStructify.parse_ref | def parse_ref(self, ref):
"""Analyze the ref block, and return the information needed.
Parameters
----------
ref : nodes.reference
Returns
-------
result : tuple of (str, str, str)
The returned result is tuple of (title, uri, docpath).
title is the display title of the ref.
uri is the html uri of to the ref after resolve.
docpath is the absolute document path to the document, if
the target corresponds to an internal document, this can bex None
"""
title = None
if len(ref.children) == 0:
title = ref['name'] if 'name' in ref else None
elif isinstance(ref.children[0], nodes.Text):
title = ref.children[0].astext()
uri = ref['refuri']
if uri.find('://') != -1:
return (title, uri, None)
anchor = None
arr = uri.split('#')
if len(arr) == 2:
anchor = arr[1]
if len(arr) > 2 or len(arr[0]) == 0:
return (title, uri, None)
uri = arr[0]
abspath = os.path.abspath(os.path.join(self.file_dir, uri))
relpath = os.path.relpath(abspath, self.root_dir)
suffix = abspath.rsplit('.', 1)
if len(suffix) == 2 and suffix[1] in AutoStructify.suffix_set and (
os.path.exists(abspath) and abspath.startswith(self.root_dir)):
# replace the path separator if running on non-UNIX environment
if os.path.sep != '/':
relpath = relpath.replace(os.path.sep, '/')
docpath = '/' + relpath.rsplit('.', 1)[0]
# rewrite suffix to html, this is suboptimal
uri = docpath + '.html'
if anchor is None:
return (title, uri, docpath)
else:
return (title, uri + '#' + anchor, None)
else:
# use url resolver
if self.url_resolver:
uri = self.url_resolver(relpath)
if anchor:
uri += '#' + anchor
return (title, uri, None) | python | def parse_ref(self, ref):
title = None
if len(ref.children) == 0:
title = ref['name'] if 'name' in ref else None
elif isinstance(ref.children[0], nodes.Text):
title = ref.children[0].astext()
uri = ref['refuri']
if uri.find('://') != -1:
return (title, uri, None)
anchor = None
arr = uri.split('#')
if len(arr) == 2:
anchor = arr[1]
if len(arr) > 2 or len(arr[0]) == 0:
return (title, uri, None)
uri = arr[0]
abspath = os.path.abspath(os.path.join(self.file_dir, uri))
relpath = os.path.relpath(abspath, self.root_dir)
suffix = abspath.rsplit('.', 1)
if len(suffix) == 2 and suffix[1] in AutoStructify.suffix_set and (
os.path.exists(abspath) and abspath.startswith(self.root_dir)):
# replace the path separator if running on non-UNIX environment
if os.path.sep != '/':
relpath = relpath.replace(os.path.sep, '/')
docpath = '/' + relpath.rsplit('.', 1)[0]
# rewrite suffix to html, this is suboptimal
uri = docpath + '.html'
if anchor is None:
return (title, uri, docpath)
else:
return (title, uri + '#' + anchor, None)
else:
# use url resolver
if self.url_resolver:
uri = self.url_resolver(relpath)
if anchor:
uri += '#' + anchor
return (title, uri, None) | [
"def",
"parse_ref",
"(",
"self",
",",
"ref",
")",
":",
"title",
"=",
"None",
"if",
"len",
"(",
"ref",
".",
"children",
")",
"==",
"0",
":",
"title",
"=",
"ref",
"[",
"'name'",
"]",
"if",
"'name'",
"in",
"ref",
"else",
"None",
"elif",
"isinstance",
... | Analyze the ref block, and return the information needed.
Parameters
----------
ref : nodes.reference
Returns
-------
result : tuple of (str, str, str)
The returned result is tuple of (title, uri, docpath).
title is the display title of the ref.
uri is the html uri of to the ref after resolve.
docpath is the absolute document path to the document, if
the target corresponds to an internal document, this can bex None | [
"Analyze",
"the",
"ref",
"block",
"and",
"return",
"the",
"information",
"needed",
"."
] | 815d75ea503f30af26ab67c6820078f84875b1fc | https://github.com/rtfd/recommonmark/blob/815d75ea503f30af26ab67c6820078f84875b1fc/recommonmark/transform.py#L53-L106 |
227,449 | rtfd/recommonmark | recommonmark/transform.py | AutoStructify.auto_toc_tree | def auto_toc_tree(self, node): # pylint: disable=too-many-branches
"""Try to convert a list block to toctree in rst.
This function detects if the matches the condition and return
a converted toc tree node. The matching condition:
The list only contains one level, and only contains references
Parameters
----------
node: nodes.Sequential
A list node in the doctree
Returns
-------
tocnode: docutils node
The converted toc tree node, None if conversion is not possible.
"""
if not self.config['enable_auto_toc_tree']:
return None
# when auto_toc_tree_section is set
# only auto generate toctree under the specified section title
sec = self.config['auto_toc_tree_section']
if sec is not None:
if node.parent is None:
return None
title = None
if isinstance(node.parent, nodes.section):
child = node.parent.first_child_matching_class(nodes.title)
if child is not None:
title = node.parent.children[child]
elif isinstance(node.parent, nodes.paragraph):
child = node.parent.parent.first_child_matching_class(nodes.title)
if child is not None:
title = node.parent.parent.children[child]
if not title:
return None
if title.astext().strip() != sec:
return None
numbered = None
if isinstance(node, nodes.bullet_list):
numbered = 0
elif isinstance(node, nodes.enumerated_list):
numbered = 1
if numbered is None:
return None
refs = []
for nd in node.children[:]:
assert isinstance(nd, nodes.list_item)
if len(nd.children) != 1:
return None
par = nd.children[0]
if not isinstance(par, nodes.paragraph):
return None
if len(par.children) != 1:
return None
ref = par.children[0]
if isinstance(ref, addnodes.pending_xref):
ref = ref.children[0]
if not isinstance(ref, nodes.reference):
return None
title, uri, docpath = self.parse_ref(ref)
if title is None or uri.startswith('#'):
return None
if docpath:
refs.append((title, docpath))
else:
refs.append((title, uri))
self.state_machine.reset(self.document,
node.parent,
self.current_level)
return self.state_machine.run_directive(
'toctree',
options={'maxdepth': 1, 'numbered': numbered},
content=['%s <%s>' % (k, v) for k, v in refs]) | python | def auto_toc_tree(self, node): # pylint: disable=too-many-branches
if not self.config['enable_auto_toc_tree']:
return None
# when auto_toc_tree_section is set
# only auto generate toctree under the specified section title
sec = self.config['auto_toc_tree_section']
if sec is not None:
if node.parent is None:
return None
title = None
if isinstance(node.parent, nodes.section):
child = node.parent.first_child_matching_class(nodes.title)
if child is not None:
title = node.parent.children[child]
elif isinstance(node.parent, nodes.paragraph):
child = node.parent.parent.first_child_matching_class(nodes.title)
if child is not None:
title = node.parent.parent.children[child]
if not title:
return None
if title.astext().strip() != sec:
return None
numbered = None
if isinstance(node, nodes.bullet_list):
numbered = 0
elif isinstance(node, nodes.enumerated_list):
numbered = 1
if numbered is None:
return None
refs = []
for nd in node.children[:]:
assert isinstance(nd, nodes.list_item)
if len(nd.children) != 1:
return None
par = nd.children[0]
if not isinstance(par, nodes.paragraph):
return None
if len(par.children) != 1:
return None
ref = par.children[0]
if isinstance(ref, addnodes.pending_xref):
ref = ref.children[0]
if not isinstance(ref, nodes.reference):
return None
title, uri, docpath = self.parse_ref(ref)
if title is None or uri.startswith('#'):
return None
if docpath:
refs.append((title, docpath))
else:
refs.append((title, uri))
self.state_machine.reset(self.document,
node.parent,
self.current_level)
return self.state_machine.run_directive(
'toctree',
options={'maxdepth': 1, 'numbered': numbered},
content=['%s <%s>' % (k, v) for k, v in refs]) | [
"def",
"auto_toc_tree",
"(",
"self",
",",
"node",
")",
":",
"# pylint: disable=too-many-branches",
"if",
"not",
"self",
".",
"config",
"[",
"'enable_auto_toc_tree'",
"]",
":",
"return",
"None",
"# when auto_toc_tree_section is set",
"# only auto generate toctree under the s... | Try to convert a list block to toctree in rst.
This function detects if the matches the condition and return
a converted toc tree node. The matching condition:
The list only contains one level, and only contains references
Parameters
----------
node: nodes.Sequential
A list node in the doctree
Returns
-------
tocnode: docutils node
The converted toc tree node, None if conversion is not possible. | [
"Try",
"to",
"convert",
"a",
"list",
"block",
"to",
"toctree",
"in",
"rst",
"."
] | 815d75ea503f30af26ab67c6820078f84875b1fc | https://github.com/rtfd/recommonmark/blob/815d75ea503f30af26ab67c6820078f84875b1fc/recommonmark/transform.py#L108-L183 |
227,450 | rtfd/recommonmark | recommonmark/transform.py | AutoStructify.auto_inline_code | def auto_inline_code(self, node):
"""Try to automatically generate nodes for inline literals.
Parameters
----------
node : nodes.literal
Original codeblock node
Returns
-------
tocnode: docutils node
The converted toc tree node, None if conversion is not possible.
"""
assert isinstance(node, nodes.literal)
if len(node.children) != 1:
return None
content = node.children[0]
if not isinstance(content, nodes.Text):
return None
content = content.astext().strip()
if content.startswith('$') and content.endswith('$'):
if not self.config['enable_inline_math']:
return None
content = content[1:-1]
self.state_machine.reset(self.document,
node.parent,
self.current_level)
return self.state_machine.run_role('math', content=content)
else:
return None | python | def auto_inline_code(self, node):
assert isinstance(node, nodes.literal)
if len(node.children) != 1:
return None
content = node.children[0]
if not isinstance(content, nodes.Text):
return None
content = content.astext().strip()
if content.startswith('$') and content.endswith('$'):
if not self.config['enable_inline_math']:
return None
content = content[1:-1]
self.state_machine.reset(self.document,
node.parent,
self.current_level)
return self.state_machine.run_role('math', content=content)
else:
return None | [
"def",
"auto_inline_code",
"(",
"self",
",",
"node",
")",
":",
"assert",
"isinstance",
"(",
"node",
",",
"nodes",
".",
"literal",
")",
"if",
"len",
"(",
"node",
".",
"children",
")",
"!=",
"1",
":",
"return",
"None",
"content",
"=",
"node",
".",
"chi... | Try to automatically generate nodes for inline literals.
Parameters
----------
node : nodes.literal
Original codeblock node
Returns
-------
tocnode: docutils node
The converted toc tree node, None if conversion is not possible. | [
"Try",
"to",
"automatically",
"generate",
"nodes",
"for",
"inline",
"literals",
"."
] | 815d75ea503f30af26ab67c6820078f84875b1fc | https://github.com/rtfd/recommonmark/blob/815d75ea503f30af26ab67c6820078f84875b1fc/recommonmark/transform.py#L185-L213 |
227,451 | rtfd/recommonmark | recommonmark/transform.py | AutoStructify.auto_code_block | def auto_code_block(self, node):
"""Try to automatically generate nodes for codeblock syntax.
Parameters
----------
node : nodes.literal_block
Original codeblock node
Returns
-------
tocnode: docutils node
The converted toc tree node, None if conversion is not possible.
"""
assert isinstance(node, nodes.literal_block)
original_node = node
if 'language' not in node:
return None
self.state_machine.reset(self.document,
node.parent,
self.current_level)
content = node.rawsource.split('\n')
language = node['language']
if language == 'math':
if self.config['enable_math']:
return self.state_machine.run_directive(
'math', content=content)
elif language == 'eval_rst':
if self.config['enable_eval_rst']:
# allow embed non section level rst
node = nodes.section()
self.state_machine.state.nested_parse(
StringList(content, source=original_node.source),
0, node=node, match_titles=True)
return node.children[:]
else:
match = re.search('[ ]?[\w_-]+::.*', language)
if match:
parser = Parser()
new_doc = new_document(None, self.document.settings)
newsource = u'.. ' + match.group(0) + '\n' + node.rawsource
parser.parse(newsource, new_doc)
return new_doc.children[:]
else:
return self.state_machine.run_directive(
'code-block', arguments=[language],
content=content)
return None | python | def auto_code_block(self, node):
assert isinstance(node, nodes.literal_block)
original_node = node
if 'language' not in node:
return None
self.state_machine.reset(self.document,
node.parent,
self.current_level)
content = node.rawsource.split('\n')
language = node['language']
if language == 'math':
if self.config['enable_math']:
return self.state_machine.run_directive(
'math', content=content)
elif language == 'eval_rst':
if self.config['enable_eval_rst']:
# allow embed non section level rst
node = nodes.section()
self.state_machine.state.nested_parse(
StringList(content, source=original_node.source),
0, node=node, match_titles=True)
return node.children[:]
else:
match = re.search('[ ]?[\w_-]+::.*', language)
if match:
parser = Parser()
new_doc = new_document(None, self.document.settings)
newsource = u'.. ' + match.group(0) + '\n' + node.rawsource
parser.parse(newsource, new_doc)
return new_doc.children[:]
else:
return self.state_machine.run_directive(
'code-block', arguments=[language],
content=content)
return None | [
"def",
"auto_code_block",
"(",
"self",
",",
"node",
")",
":",
"assert",
"isinstance",
"(",
"node",
",",
"nodes",
".",
"literal_block",
")",
"original_node",
"=",
"node",
"if",
"'language'",
"not",
"in",
"node",
":",
"return",
"None",
"self",
".",
"state_ma... | Try to automatically generate nodes for codeblock syntax.
Parameters
----------
node : nodes.literal_block
Original codeblock node
Returns
-------
tocnode: docutils node
The converted toc tree node, None if conversion is not possible. | [
"Try",
"to",
"automatically",
"generate",
"nodes",
"for",
"codeblock",
"syntax",
"."
] | 815d75ea503f30af26ab67c6820078f84875b1fc | https://github.com/rtfd/recommonmark/blob/815d75ea503f30af26ab67c6820078f84875b1fc/recommonmark/transform.py#L215-L260 |
227,452 | rtfd/recommonmark | recommonmark/transform.py | AutoStructify.find_replace | def find_replace(self, node):
"""Try to find replace node for current node.
Parameters
----------
node : docutil node
Node to find replacement for.
Returns
-------
nodes : node or list of node
The replacement nodes of current node.
Returns None if no replacement can be found.
"""
newnode = None
if isinstance(node, nodes.Sequential):
newnode = self.auto_toc_tree(node)
elif isinstance(node, nodes.literal_block):
newnode = self.auto_code_block(node)
elif isinstance(node, nodes.literal):
newnode = self.auto_inline_code(node)
return newnode | python | def find_replace(self, node):
newnode = None
if isinstance(node, nodes.Sequential):
newnode = self.auto_toc_tree(node)
elif isinstance(node, nodes.literal_block):
newnode = self.auto_code_block(node)
elif isinstance(node, nodes.literal):
newnode = self.auto_inline_code(node)
return newnode | [
"def",
"find_replace",
"(",
"self",
",",
"node",
")",
":",
"newnode",
"=",
"None",
"if",
"isinstance",
"(",
"node",
",",
"nodes",
".",
"Sequential",
")",
":",
"newnode",
"=",
"self",
".",
"auto_toc_tree",
"(",
"node",
")",
"elif",
"isinstance",
"(",
"n... | Try to find replace node for current node.
Parameters
----------
node : docutil node
Node to find replacement for.
Returns
-------
nodes : node or list of node
The replacement nodes of current node.
Returns None if no replacement can be found. | [
"Try",
"to",
"find",
"replace",
"node",
"for",
"current",
"node",
"."
] | 815d75ea503f30af26ab67c6820078f84875b1fc | https://github.com/rtfd/recommonmark/blob/815d75ea503f30af26ab67c6820078f84875b1fc/recommonmark/transform.py#L262-L283 |
227,453 | rtfd/recommonmark | recommonmark/transform.py | AutoStructify.apply | def apply(self):
"""Apply the transformation by configuration."""
source = self.document['source']
self.reporter.info('AutoStructify: %s' % source)
# only transform markdowns
if not source.endswith(tuple(self.config['commonmark_suffixes'])):
return
self.url_resolver = self.config['url_resolver']
assert callable(self.url_resolver)
self.state_machine = DummyStateMachine()
self.current_level = 0
self.file_dir = os.path.abspath(os.path.dirname(self.document['source']))
self.root_dir = os.path.abspath(self.document.settings.env.srcdir)
self.traverse(self.document) | python | def apply(self):
source = self.document['source']
self.reporter.info('AutoStructify: %s' % source)
# only transform markdowns
if not source.endswith(tuple(self.config['commonmark_suffixes'])):
return
self.url_resolver = self.config['url_resolver']
assert callable(self.url_resolver)
self.state_machine = DummyStateMachine()
self.current_level = 0
self.file_dir = os.path.abspath(os.path.dirname(self.document['source']))
self.root_dir = os.path.abspath(self.document.settings.env.srcdir)
self.traverse(self.document) | [
"def",
"apply",
"(",
"self",
")",
":",
"source",
"=",
"self",
".",
"document",
"[",
"'source'",
"]",
"self",
".",
"reporter",
".",
"info",
"(",
"'AutoStructify: %s'",
"%",
"source",
")",
"# only transform markdowns",
"if",
"not",
"source",
".",
"endswith",
... | Apply the transformation by configuration. | [
"Apply",
"the",
"transformation",
"by",
"configuration",
"."
] | 815d75ea503f30af26ab67c6820078f84875b1fc | https://github.com/rtfd/recommonmark/blob/815d75ea503f30af26ab67c6820078f84875b1fc/recommonmark/transform.py#L311-L328 |
227,454 | bakwc/JamSpell | evaluate/context_spell_prototype.py | correction | def correction(sentence, pos):
"Most probable spelling correction for word."
word = sentence[pos]
cands = candidates(word)
if not cands:
cands = candidates(word, False)
if not cands:
return word
cands = sorted(cands, key=lambda w: P(w, sentence, pos), reverse=True)
cands = [c[0] for c in cands]
return cands | python | def correction(sentence, pos):
"Most probable spelling correction for word."
word = sentence[pos]
cands = candidates(word)
if not cands:
cands = candidates(word, False)
if not cands:
return word
cands = sorted(cands, key=lambda w: P(w, sentence, pos), reverse=True)
cands = [c[0] for c in cands]
return cands | [
"def",
"correction",
"(",
"sentence",
",",
"pos",
")",
":",
"word",
"=",
"sentence",
"[",
"pos",
"]",
"cands",
"=",
"candidates",
"(",
"word",
")",
"if",
"not",
"cands",
":",
"cands",
"=",
"candidates",
"(",
"word",
",",
"False",
")",
"if",
"not",
... | Most probable spelling correction for word. | [
"Most",
"probable",
"spelling",
"correction",
"for",
"word",
"."
] | bfdfd889436df4dbcd9ec86b20d2baeb815068bd | https://github.com/bakwc/JamSpell/blob/bfdfd889436df4dbcd9ec86b20d2baeb815068bd/evaluate/context_spell_prototype.py#L33-L43 |
227,455 | pydot/pydot | pydot.py | graph_from_dot_file | def graph_from_dot_file(path, encoding=None):
"""Load graphs from DOT file at `path`.
@param path: to DOT file
@param encoding: as passed to `io.open`.
For example, `'utf-8'`.
@return: Graphs that result from parsing.
@rtype: `list` of `pydot.Dot`
"""
with io.open(path, 'rt', encoding=encoding) as f:
s = f.read()
if not PY3:
s = unicode(s)
graphs = graph_from_dot_data(s)
return graphs | python | def graph_from_dot_file(path, encoding=None):
with io.open(path, 'rt', encoding=encoding) as f:
s = f.read()
if not PY3:
s = unicode(s)
graphs = graph_from_dot_data(s)
return graphs | [
"def",
"graph_from_dot_file",
"(",
"path",
",",
"encoding",
"=",
"None",
")",
":",
"with",
"io",
".",
"open",
"(",
"path",
",",
"'rt'",
",",
"encoding",
"=",
"encoding",
")",
"as",
"f",
":",
"s",
"=",
"f",
".",
"read",
"(",
")",
"if",
"not",
"PY3... | Load graphs from DOT file at `path`.
@param path: to DOT file
@param encoding: as passed to `io.open`.
For example, `'utf-8'`.
@return: Graphs that result from parsing.
@rtype: `list` of `pydot.Dot` | [
"Load",
"graphs",
"from",
"DOT",
"file",
"at",
"path",
"."
] | 48ba231b36012c5e13611807c9aac7d8ae8c15c4 | https://github.com/pydot/pydot/blob/48ba231b36012c5e13611807c9aac7d8ae8c15c4/pydot.py#L285-L300 |
227,456 | pydot/pydot | pydot.py | Node.to_string | def to_string(self):
"""Return string representation of node in DOT language."""
# RMF: special case defaults for node, edge and graph properties.
#
node = quote_if_necessary(self.obj_dict['name'])
node_attr = list()
for attr in sorted(self.obj_dict['attributes']):
value = self.obj_dict['attributes'][attr]
if value == '':
value = '""'
if value is not None:
node_attr.append(
'%s=%s' % (attr, quote_if_necessary(value) ) )
else:
node_attr.append( attr )
# No point in having nodes setting any defaults if the don't set
# any attributes...
#
if node in ('graph', 'node', 'edge') and len(node_attr) == 0:
return ''
node_attr = ', '.join(node_attr)
if node_attr:
node += ' [' + node_attr + ']'
return node + ';' | python | def to_string(self):
# RMF: special case defaults for node, edge and graph properties.
#
node = quote_if_necessary(self.obj_dict['name'])
node_attr = list()
for attr in sorted(self.obj_dict['attributes']):
value = self.obj_dict['attributes'][attr]
if value == '':
value = '""'
if value is not None:
node_attr.append(
'%s=%s' % (attr, quote_if_necessary(value) ) )
else:
node_attr.append( attr )
# No point in having nodes setting any defaults if the don't set
# any attributes...
#
if node in ('graph', 'node', 'edge') and len(node_attr) == 0:
return ''
node_attr = ', '.join(node_attr)
if node_attr:
node += ' [' + node_attr + ']'
return node + ';' | [
"def",
"to_string",
"(",
"self",
")",
":",
"# RMF: special case defaults for node, edge and graph properties.",
"#",
"node",
"=",
"quote_if_necessary",
"(",
"self",
".",
"obj_dict",
"[",
"'name'",
"]",
")",
"node_attr",
"=",
"list",
"(",
")",
"for",
"attr",
"in",
... | Return string representation of node in DOT language. | [
"Return",
"string",
"representation",
"of",
"node",
"in",
"DOT",
"language",
"."
] | 48ba231b36012c5e13611807c9aac7d8ae8c15c4 | https://github.com/pydot/pydot/blob/48ba231b36012c5e13611807c9aac7d8ae8c15c4/pydot.py#L654-L686 |
227,457 | pydot/pydot | pydot.py | Graph.add_node | def add_node(self, graph_node):
"""Adds a node object to the graph.
It takes a node object as its only argument and returns
None.
"""
if not isinstance(graph_node, Node):
raise TypeError(
'add_node() received ' +
'a non node class object: ' + str(graph_node))
node = self.get_node(graph_node.get_name())
if not node:
self.obj_dict['nodes'][graph_node.get_name()] = [
graph_node.obj_dict ]
#self.node_dict[graph_node.get_name()] = graph_node.attributes
graph_node.set_parent_graph(self.get_parent_graph())
else:
self.obj_dict['nodes'][graph_node.get_name()].append(
graph_node.obj_dict )
graph_node.set_sequence(self.get_next_sequence_number()) | python | def add_node(self, graph_node):
if not isinstance(graph_node, Node):
raise TypeError(
'add_node() received ' +
'a non node class object: ' + str(graph_node))
node = self.get_node(graph_node.get_name())
if not node:
self.obj_dict['nodes'][graph_node.get_name()] = [
graph_node.obj_dict ]
#self.node_dict[graph_node.get_name()] = graph_node.attributes
graph_node.set_parent_graph(self.get_parent_graph())
else:
self.obj_dict['nodes'][graph_node.get_name()].append(
graph_node.obj_dict )
graph_node.set_sequence(self.get_next_sequence_number()) | [
"def",
"add_node",
"(",
"self",
",",
"graph_node",
")",
":",
"if",
"not",
"isinstance",
"(",
"graph_node",
",",
"Node",
")",
":",
"raise",
"TypeError",
"(",
"'add_node() received '",
"+",
"'a non node class object: '",
"+",
"str",
"(",
"graph_node",
")",
")",
... | Adds a node object to the graph.
It takes a node object as its only argument and returns
None. | [
"Adds",
"a",
"node",
"object",
"to",
"the",
"graph",
"."
] | 48ba231b36012c5e13611807c9aac7d8ae8c15c4 | https://github.com/pydot/pydot/blob/48ba231b36012c5e13611807c9aac7d8ae8c15c4/pydot.py#L1126-L1154 |
227,458 | pydot/pydot | pydot.py | Graph.del_node | def del_node(self, name, index=None):
"""Delete a node from the graph.
Given a node's name all node(s) with that same name
will be deleted if 'index' is not specified or set
to None.
If there are several nodes with that same name and
'index' is given, only the node in that position
will be deleted.
'index' should be an integer specifying the position
of the node to delete. If index is larger than the
number of nodes with that name, no action is taken.
If nodes are deleted it returns True. If no action
is taken it returns False.
"""
if isinstance(name, Node):
name = name.get_name()
if name in self.obj_dict['nodes']:
if (index is not None and
index < len(self.obj_dict['nodes'][name])):
del self.obj_dict['nodes'][name][index]
return True
else:
del self.obj_dict['nodes'][name]
return True
return False | python | def del_node(self, name, index=None):
if isinstance(name, Node):
name = name.get_name()
if name in self.obj_dict['nodes']:
if (index is not None and
index < len(self.obj_dict['nodes'][name])):
del self.obj_dict['nodes'][name][index]
return True
else:
del self.obj_dict['nodes'][name]
return True
return False | [
"def",
"del_node",
"(",
"self",
",",
"name",
",",
"index",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"name",
",",
"Node",
")",
":",
"name",
"=",
"name",
".",
"get_name",
"(",
")",
"if",
"name",
"in",
"self",
".",
"obj_dict",
"[",
"'nodes'",
... | Delete a node from the graph.
Given a node's name all node(s) with that same name
will be deleted if 'index' is not specified or set
to None.
If there are several nodes with that same name and
'index' is given, only the node in that position
will be deleted.
'index' should be an integer specifying the position
of the node to delete. If index is larger than the
number of nodes with that name, no action is taken.
If nodes are deleted it returns True. If no action
is taken it returns False. | [
"Delete",
"a",
"node",
"from",
"the",
"graph",
"."
] | 48ba231b36012c5e13611807c9aac7d8ae8c15c4 | https://github.com/pydot/pydot/blob/48ba231b36012c5e13611807c9aac7d8ae8c15c4/pydot.py#L1158-L1189 |
227,459 | pydot/pydot | pydot.py | Graph.get_edge | def get_edge(self, src_or_list, dst=None):
"""Retrieved an edge from the graph.
Given an edge's source and destination the corresponding
Edge instance(s) will be returned.
If one or more edges exist with that source and destination
a list of Edge instances is returned.
An empty list is returned otherwise.
"""
if isinstance( src_or_list, (list, tuple)) and dst is None:
edge_points = tuple(src_or_list)
edge_points_reverse = (edge_points[1], edge_points[0])
else:
edge_points = (src_or_list, dst)
edge_points_reverse = (dst, src_or_list)
match = list()
if edge_points in self.obj_dict['edges'] or (
self.get_top_graph_type() == 'graph' and
edge_points_reverse in self.obj_dict['edges']):
edges_obj_dict = self.obj_dict['edges'].get(
edge_points,
self.obj_dict['edges'].get( edge_points_reverse, None ))
for edge_obj_dict in edges_obj_dict:
match.append(
Edge(edge_points[0],
edge_points[1],
obj_dict=edge_obj_dict))
return match | python | def get_edge(self, src_or_list, dst=None):
if isinstance( src_or_list, (list, tuple)) and dst is None:
edge_points = tuple(src_or_list)
edge_points_reverse = (edge_points[1], edge_points[0])
else:
edge_points = (src_or_list, dst)
edge_points_reverse = (dst, src_or_list)
match = list()
if edge_points in self.obj_dict['edges'] or (
self.get_top_graph_type() == 'graph' and
edge_points_reverse in self.obj_dict['edges']):
edges_obj_dict = self.obj_dict['edges'].get(
edge_points,
self.obj_dict['edges'].get( edge_points_reverse, None ))
for edge_obj_dict in edges_obj_dict:
match.append(
Edge(edge_points[0],
edge_points[1],
obj_dict=edge_obj_dict))
return match | [
"def",
"get_edge",
"(",
"self",
",",
"src_or_list",
",",
"dst",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"src_or_list",
",",
"(",
"list",
",",
"tuple",
")",
")",
"and",
"dst",
"is",
"None",
":",
"edge_points",
"=",
"tuple",
"(",
"src_or_list",
... | Retrieved an edge from the graph.
Given an edge's source and destination the corresponding
Edge instance(s) will be returned.
If one or more edges exist with that source and destination
a list of Edge instances is returned.
An empty list is returned otherwise. | [
"Retrieved",
"an",
"edge",
"from",
"the",
"graph",
"."
] | 48ba231b36012c5e13611807c9aac7d8ae8c15c4 | https://github.com/pydot/pydot/blob/48ba231b36012c5e13611807c9aac7d8ae8c15c4/pydot.py#L1312-L1346 |
227,460 | pydot/pydot | pydot.py | Graph.get_subgraph | def get_subgraph(self, name):
"""Retrieved a subgraph from the graph.
Given a subgraph's name the corresponding
Subgraph instance will be returned.
If one or more subgraphs exist with the same name, a list of
Subgraph instances is returned.
An empty list is returned otherwise.
"""
match = list()
if name in self.obj_dict['subgraphs']:
sgraphs_obj_dict = self.obj_dict['subgraphs'].get( name )
for obj_dict_list in sgraphs_obj_dict:
#match.extend( Subgraph( obj_dict = obj_d )
# for obj_d in obj_dict_list )
match.append( Subgraph( obj_dict = obj_dict_list ) )
return match | python | def get_subgraph(self, name):
match = list()
if name in self.obj_dict['subgraphs']:
sgraphs_obj_dict = self.obj_dict['subgraphs'].get( name )
for obj_dict_list in sgraphs_obj_dict:
#match.extend( Subgraph( obj_dict = obj_d )
# for obj_d in obj_dict_list )
match.append( Subgraph( obj_dict = obj_dict_list ) )
return match | [
"def",
"get_subgraph",
"(",
"self",
",",
"name",
")",
":",
"match",
"=",
"list",
"(",
")",
"if",
"name",
"in",
"self",
".",
"obj_dict",
"[",
"'subgraphs'",
"]",
":",
"sgraphs_obj_dict",
"=",
"self",
".",
"obj_dict",
"[",
"'subgraphs'",
"]",
".",
"get",... | Retrieved a subgraph from the graph.
Given a subgraph's name the corresponding
Subgraph instance will be returned.
If one or more subgraphs exist with the same name, a list of
Subgraph instances is returned.
An empty list is returned otherwise. | [
"Retrieved",
"a",
"subgraph",
"from",
"the",
"graph",
"."
] | 48ba231b36012c5e13611807c9aac7d8ae8c15c4 | https://github.com/pydot/pydot/blob/48ba231b36012c5e13611807c9aac7d8ae8c15c4/pydot.py#L1401-L1423 |
227,461 | pydot/pydot | pydot.py | Graph.get_subgraph_list | def get_subgraph_list(self):
"""Get the list of Subgraph instances.
This method returns the list of Subgraph instances
in the graph.
"""
sgraph_objs = list()
for sgraph in self.obj_dict['subgraphs']:
obj_dict_list = self.obj_dict['subgraphs'][sgraph]
sgraph_objs.extend(
[Subgraph(obj_dict=obj_d)
for obj_d in obj_dict_list])
return sgraph_objs | python | def get_subgraph_list(self):
sgraph_objs = list()
for sgraph in self.obj_dict['subgraphs']:
obj_dict_list = self.obj_dict['subgraphs'][sgraph]
sgraph_objs.extend(
[Subgraph(obj_dict=obj_d)
for obj_d in obj_dict_list])
return sgraph_objs | [
"def",
"get_subgraph_list",
"(",
"self",
")",
":",
"sgraph_objs",
"=",
"list",
"(",
")",
"for",
"sgraph",
"in",
"self",
".",
"obj_dict",
"[",
"'subgraphs'",
"]",
":",
"obj_dict_list",
"=",
"self",
".",
"obj_dict",
"[",
"'subgraphs'",
"]",
"[",
"sgraph",
... | Get the list of Subgraph instances.
This method returns the list of Subgraph instances
in the graph. | [
"Get",
"the",
"list",
"of",
"Subgraph",
"instances",
"."
] | 48ba231b36012c5e13611807c9aac7d8ae8c15c4 | https://github.com/pydot/pydot/blob/48ba231b36012c5e13611807c9aac7d8ae8c15c4/pydot.py#L1431-L1446 |
227,462 | pydot/pydot | pydot.py | Dot.create | def create(self, prog=None, format='ps', encoding=None):
"""Creates and returns a binary image for the graph.
create will write the graph to a temporary dot file in the
encoding specified by `encoding` and process it with the
program given by 'prog' (which defaults to 'twopi'), reading
the binary image output and return it as:
- `str` of bytes in Python 2
- `bytes` in Python 3
There's also the preferred possibility of using:
create_'format'(prog='program')
which are automatically defined for all the supported formats,
for example:
- `create_ps()`
- `create_gif()`
- `create_dia()`
If 'prog' is a list, instead of a string,
then the fist item is expected to be the program name,
followed by any optional command-line arguments for it:
[ 'twopi', '-Tdot', '-s10' ]
@param prog: either:
- name of GraphViz executable that
can be found in the `$PATH`, or
- absolute path to GraphViz executable.
If you have added GraphViz to the `$PATH` and
use its executables as installed
(without renaming any of them)
then their names are:
- `'dot'`
- `'twopi'`
- `'neato'`
- `'circo'`
- `'fdp'`
- `'sfdp'`
On Windows, these have the notorious ".exe" extension that,
only for the above strings, will be added automatically.
The `$PATH` is inherited from `os.env['PATH']` and
passed to `subprocess.Popen` using the `env` argument.
If you haven't added GraphViz to your `$PATH` on Windows,
then you may want to give the absolute path to the
executable (for example, to `dot.exe`) in `prog`.
"""
if prog is None:
prog = self.prog
assert prog is not None
if isinstance(prog, (list, tuple)):
prog, args = prog[0], prog[1:]
else:
args = []
# temp file
tmp_fd, tmp_name = tempfile.mkstemp()
os.close(tmp_fd)
self.write(tmp_name, encoding=encoding)
tmp_dir = os.path.dirname(tmp_name)
# For each of the image files...
for img in self.shape_files:
# Get its data
f = open(img, 'rb')
f_data = f.read()
f.close()
# And copy it under a file with the same name in
# the temporary directory
f = open(os.path.join(tmp_dir, os.path.basename(img)), 'wb')
f.write(f_data)
f.close()
arguments = ['-T{}'.format(format), ] + args + [tmp_name]
try:
stdout_data, stderr_data, process = call_graphviz(
program=prog,
arguments=arguments,
working_dir=tmp_dir,
)
except OSError as e:
if e.errno == errno.ENOENT:
args = list(e.args)
args[1] = '"{prog}" not found in path.'.format(
prog=prog)
raise OSError(*args)
else:
raise
# clean file litter
for img in self.shape_files:
os.unlink(os.path.join(tmp_dir, os.path.basename(img)))
os.unlink(tmp_name)
if process.returncode != 0:
message = (
'"{prog}" with args {arguments} returned code: {code}\n\n'
'stdout, stderr:\n {out}\n{err}\n'
).format(
prog=prog,
arguments=arguments,
code=process.returncode,
out=stdout_data,
err=stderr_data,
)
print(message)
assert process.returncode == 0, process.returncode
return stdout_data | python | def create(self, prog=None, format='ps', encoding=None):
if prog is None:
prog = self.prog
assert prog is not None
if isinstance(prog, (list, tuple)):
prog, args = prog[0], prog[1:]
else:
args = []
# temp file
tmp_fd, tmp_name = tempfile.mkstemp()
os.close(tmp_fd)
self.write(tmp_name, encoding=encoding)
tmp_dir = os.path.dirname(tmp_name)
# For each of the image files...
for img in self.shape_files:
# Get its data
f = open(img, 'rb')
f_data = f.read()
f.close()
# And copy it under a file with the same name in
# the temporary directory
f = open(os.path.join(tmp_dir, os.path.basename(img)), 'wb')
f.write(f_data)
f.close()
arguments = ['-T{}'.format(format), ] + args + [tmp_name]
try:
stdout_data, stderr_data, process = call_graphviz(
program=prog,
arguments=arguments,
working_dir=tmp_dir,
)
except OSError as e:
if e.errno == errno.ENOENT:
args = list(e.args)
args[1] = '"{prog}" not found in path.'.format(
prog=prog)
raise OSError(*args)
else:
raise
# clean file litter
for img in self.shape_files:
os.unlink(os.path.join(tmp_dir, os.path.basename(img)))
os.unlink(tmp_name)
if process.returncode != 0:
message = (
'"{prog}" with args {arguments} returned code: {code}\n\n'
'stdout, stderr:\n {out}\n{err}\n'
).format(
prog=prog,
arguments=arguments,
code=process.returncode,
out=stdout_data,
err=stderr_data,
)
print(message)
assert process.returncode == 0, process.returncode
return stdout_data | [
"def",
"create",
"(",
"self",
",",
"prog",
"=",
"None",
",",
"format",
"=",
"'ps'",
",",
"encoding",
"=",
"None",
")",
":",
"if",
"prog",
"is",
"None",
":",
"prog",
"=",
"self",
".",
"prog",
"assert",
"prog",
"is",
"not",
"None",
"if",
"isinstance"... | Creates and returns a binary image for the graph.
create will write the graph to a temporary dot file in the
encoding specified by `encoding` and process it with the
program given by 'prog' (which defaults to 'twopi'), reading
the binary image output and return it as:
- `str` of bytes in Python 2
- `bytes` in Python 3
There's also the preferred possibility of using:
create_'format'(prog='program')
which are automatically defined for all the supported formats,
for example:
- `create_ps()`
- `create_gif()`
- `create_dia()`
If 'prog' is a list, instead of a string,
then the fist item is expected to be the program name,
followed by any optional command-line arguments for it:
[ 'twopi', '-Tdot', '-s10' ]
@param prog: either:
- name of GraphViz executable that
can be found in the `$PATH`, or
- absolute path to GraphViz executable.
If you have added GraphViz to the `$PATH` and
use its executables as installed
(without renaming any of them)
then their names are:
- `'dot'`
- `'twopi'`
- `'neato'`
- `'circo'`
- `'fdp'`
- `'sfdp'`
On Windows, these have the notorious ".exe" extension that,
only for the above strings, will be added automatically.
The `$PATH` is inherited from `os.env['PATH']` and
passed to `subprocess.Popen` using the `env` argument.
If you haven't added GraphViz to your `$PATH` on Windows,
then you may want to give the absolute path to the
executable (for example, to `dot.exe`) in `prog`. | [
"Creates",
"and",
"returns",
"a",
"binary",
"image",
"for",
"the",
"graph",
"."
] | 48ba231b36012c5e13611807c9aac7d8ae8c15c4 | https://github.com/pydot/pydot/blob/48ba231b36012c5e13611807c9aac7d8ae8c15c4/pydot.py#L1822-L1947 |
227,463 | keleshev/schema | schema.py | SchemaError.code | def code(self):
"""
Removes duplicates values in auto and error list.
parameters.
"""
def uniq(seq):
"""
Utility function that removes duplicate.
"""
seen = set()
seen_add = seen.add
# This way removes duplicates while preserving the order.
return [x for x in seq if x not in seen and not seen_add(x)]
data_set = uniq(i for i in self.autos if i is not None)
error_list = uniq(i for i in self.errors if i is not None)
if error_list:
return "\n".join(error_list)
return "\n".join(data_set) | python | def code(self):
def uniq(seq):
"""
Utility function that removes duplicate.
"""
seen = set()
seen_add = seen.add
# This way removes duplicates while preserving the order.
return [x for x in seq if x not in seen and not seen_add(x)]
data_set = uniq(i for i in self.autos if i is not None)
error_list = uniq(i for i in self.errors if i is not None)
if error_list:
return "\n".join(error_list)
return "\n".join(data_set) | [
"def",
"code",
"(",
"self",
")",
":",
"def",
"uniq",
"(",
"seq",
")",
":",
"\"\"\"\n Utility function that removes duplicate.\n \"\"\"",
"seen",
"=",
"set",
"(",
")",
"seen_add",
"=",
"seen",
".",
"add",
"# This way removes duplicates while preserv... | Removes duplicates values in auto and error list.
parameters. | [
"Removes",
"duplicates",
"values",
"in",
"auto",
"and",
"error",
"list",
".",
"parameters",
"."
] | 4a0bf6f509e6b69956a8f2fd4e1c3873fc419be8 | https://github.com/keleshev/schema/blob/4a0bf6f509e6b69956a8f2fd4e1c3873fc419be8/schema.py#L40-L59 |
227,464 | keleshev/schema | schema.py | Schema._dict_key_priority | def _dict_key_priority(s):
"""Return priority for a given key object."""
if isinstance(s, Hook):
return _priority(s._schema) - 0.5
if isinstance(s, Optional):
return _priority(s._schema) + 0.5
return _priority(s) | python | def _dict_key_priority(s):
if isinstance(s, Hook):
return _priority(s._schema) - 0.5
if isinstance(s, Optional):
return _priority(s._schema) + 0.5
return _priority(s) | [
"def",
"_dict_key_priority",
"(",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"Hook",
")",
":",
"return",
"_priority",
"(",
"s",
".",
"_schema",
")",
"-",
"0.5",
"if",
"isinstance",
"(",
"s",
",",
"Optional",
")",
":",
"return",
"_priority",
"(... | Return priority for a given key object. | [
"Return",
"priority",
"for",
"a",
"given",
"key",
"object",
"."
] | 4a0bf6f509e6b69956a8f2fd4e1c3873fc419be8 | https://github.com/keleshev/schema/blob/4a0bf6f509e6b69956a8f2fd4e1c3873fc419be8/schema.py#L274-L280 |
227,465 | keleshev/schema | schema.py | Schema._prepend_schema_name | def _prepend_schema_name(self, message):
"""
If a custom schema name has been defined, prepends it to the error
message that gets raised when a schema error occurs.
"""
if self._name:
message = "{0!r} {1!s}".format(self._name, message)
return message | python | def _prepend_schema_name(self, message):
if self._name:
message = "{0!r} {1!s}".format(self._name, message)
return message | [
"def",
"_prepend_schema_name",
"(",
"self",
",",
"message",
")",
":",
"if",
"self",
".",
"_name",
":",
"message",
"=",
"\"{0!r} {1!s}\"",
".",
"format",
"(",
"self",
".",
"_name",
",",
"message",
")",
"return",
"message"
] | If a custom schema name has been defined, prepends it to the error
message that gets raised when a schema error occurs. | [
"If",
"a",
"custom",
"schema",
"name",
"has",
"been",
"defined",
"prepends",
"it",
"to",
"the",
"error",
"message",
"that",
"gets",
"raised",
"when",
"a",
"schema",
"error",
"occurs",
"."
] | 4a0bf6f509e6b69956a8f2fd4e1c3873fc419be8 | https://github.com/keleshev/schema/blob/4a0bf6f509e6b69956a8f2fd4e1c3873fc419be8/schema.py#L298-L305 |
227,466 | keleshev/schema | schema.py | Schema.json_schema | def json_schema(self, schema_id=None, is_main_schema=True):
"""Generate a draft-07 JSON schema dict representing the Schema.
This method can only be called when the Schema's value is a dict.
This method must be called with a schema_id. Calling it without one
is used in a recursive context for sub schemas."""
Schema = self.__class__
s = self._schema
i = self._ignore_extra_keys
flavor = _priority(s)
if flavor != DICT and is_main_schema:
raise ValueError("The main schema must be a dict.")
if flavor == TYPE:
# Handle type
return {"type": {int: "integer", float: "number", bool: "boolean"}.get(s, "string")}
elif flavor == ITERABLE and len(s) == 1:
# Handle arrays of a single type or dict schema
return {"type": "array", "items": Schema(s[0]).json_schema(is_main_schema=False)}
elif isinstance(s, Or):
# Handle Or values
values = [Schema(or_key).json_schema(is_main_schema=False) for or_key in s._args]
any_of = []
for value in values:
if value not in any_of:
any_of.append(value)
return {"anyOf": any_of}
if flavor != DICT:
# If not handled, do not check
return {}
if is_main_schema and not schema_id:
raise ValueError("schema_id is required.")
# Handle dict
required_keys = []
expanded_schema = {}
for key in s:
if isinstance(key, Hook):
continue
if isinstance(s[key], Schema):
sub_schema = s[key]
else:
sub_schema = Schema(s[key], ignore_extra_keys=i)
sub_schema_json = sub_schema.json_schema(is_main_schema=False)
is_optional = False
if isinstance(key, Optional):
key = key._schema
is_optional = True
if isinstance(key, str):
if not is_optional:
required_keys.append(key)
expanded_schema[key] = sub_schema_json
elif isinstance(key, Or):
for or_key in key._args:
expanded_schema[or_key] = sub_schema_json
schema_dict = {
"type": "object",
"properties": expanded_schema,
"required": required_keys,
"additionalProperties": i,
}
if is_main_schema:
schema_dict.update({"id": schema_id, "$schema": "http://json-schema.org/draft-07/schema#"})
return schema_dict | python | def json_schema(self, schema_id=None, is_main_schema=True):
Schema = self.__class__
s = self._schema
i = self._ignore_extra_keys
flavor = _priority(s)
if flavor != DICT and is_main_schema:
raise ValueError("The main schema must be a dict.")
if flavor == TYPE:
# Handle type
return {"type": {int: "integer", float: "number", bool: "boolean"}.get(s, "string")}
elif flavor == ITERABLE and len(s) == 1:
# Handle arrays of a single type or dict schema
return {"type": "array", "items": Schema(s[0]).json_schema(is_main_schema=False)}
elif isinstance(s, Or):
# Handle Or values
values = [Schema(or_key).json_schema(is_main_schema=False) for or_key in s._args]
any_of = []
for value in values:
if value not in any_of:
any_of.append(value)
return {"anyOf": any_of}
if flavor != DICT:
# If not handled, do not check
return {}
if is_main_schema and not schema_id:
raise ValueError("schema_id is required.")
# Handle dict
required_keys = []
expanded_schema = {}
for key in s:
if isinstance(key, Hook):
continue
if isinstance(s[key], Schema):
sub_schema = s[key]
else:
sub_schema = Schema(s[key], ignore_extra_keys=i)
sub_schema_json = sub_schema.json_schema(is_main_schema=False)
is_optional = False
if isinstance(key, Optional):
key = key._schema
is_optional = True
if isinstance(key, str):
if not is_optional:
required_keys.append(key)
expanded_schema[key] = sub_schema_json
elif isinstance(key, Or):
for or_key in key._args:
expanded_schema[or_key] = sub_schema_json
schema_dict = {
"type": "object",
"properties": expanded_schema,
"required": required_keys,
"additionalProperties": i,
}
if is_main_schema:
schema_dict.update({"id": schema_id, "$schema": "http://json-schema.org/draft-07/schema#"})
return schema_dict | [
"def",
"json_schema",
"(",
"self",
",",
"schema_id",
"=",
"None",
",",
"is_main_schema",
"=",
"True",
")",
":",
"Schema",
"=",
"self",
".",
"__class__",
"s",
"=",
"self",
".",
"_schema",
"i",
"=",
"self",
".",
"_ignore_extra_keys",
"flavor",
"=",
"_prior... | Generate a draft-07 JSON schema dict representing the Schema.
This method can only be called when the Schema's value is a dict.
This method must be called with a schema_id. Calling it without one
is used in a recursive context for sub schemas. | [
"Generate",
"a",
"draft",
"-",
"07",
"JSON",
"schema",
"dict",
"representing",
"the",
"Schema",
".",
"This",
"method",
"can",
"only",
"be",
"called",
"when",
"the",
"Schema",
"s",
"value",
"is",
"a",
"dict",
".",
"This",
"method",
"must",
"be",
"called",... | 4a0bf6f509e6b69956a8f2fd4e1c3873fc419be8 | https://github.com/keleshev/schema/blob/4a0bf6f509e6b69956a8f2fd4e1c3873fc419be8/schema.py#L421-L489 |
227,467 | pycampers/ampy | ampy/files.py | Files.put | def put(self, filename, data):
"""Create or update the specified file with the provided data.
"""
# Open the file for writing on the board and write chunks of data.
self._pyboard.enter_raw_repl()
self._pyboard.exec_("f = open('{0}', 'wb')".format(filename))
size = len(data)
# Loop through and write a buffer size chunk of data at a time.
for i in range(0, size, BUFFER_SIZE):
chunk_size = min(BUFFER_SIZE, size - i)
chunk = repr(data[i : i + chunk_size])
# Make sure to send explicit byte strings (handles python 2 compatibility).
if not chunk.startswith("b"):
chunk = "b" + chunk
self._pyboard.exec_("f.write({0})".format(chunk))
self._pyboard.exec_("f.close()")
self._pyboard.exit_raw_repl() | python | def put(self, filename, data):
# Open the file for writing on the board and write chunks of data.
self._pyboard.enter_raw_repl()
self._pyboard.exec_("f = open('{0}', 'wb')".format(filename))
size = len(data)
# Loop through and write a buffer size chunk of data at a time.
for i in range(0, size, BUFFER_SIZE):
chunk_size = min(BUFFER_SIZE, size - i)
chunk = repr(data[i : i + chunk_size])
# Make sure to send explicit byte strings (handles python 2 compatibility).
if not chunk.startswith("b"):
chunk = "b" + chunk
self._pyboard.exec_("f.write({0})".format(chunk))
self._pyboard.exec_("f.close()")
self._pyboard.exit_raw_repl() | [
"def",
"put",
"(",
"self",
",",
"filename",
",",
"data",
")",
":",
"# Open the file for writing on the board and write chunks of data.",
"self",
".",
"_pyboard",
".",
"enter_raw_repl",
"(",
")",
"self",
".",
"_pyboard",
".",
"exec_",
"(",
"\"f = open('{0}', 'wb')\"",
... | Create or update the specified file with the provided data. | [
"Create",
"or",
"update",
"the",
"specified",
"file",
"with",
"the",
"provided",
"data",
"."
] | 6851f8b177c334f5ff7bd43bf07307a437433ba2 | https://github.com/pycampers/ampy/blob/6851f8b177c334f5ff7bd43bf07307a437433ba2/ampy/files.py#L204-L220 |
227,468 | pycampers/ampy | ampy/cli.py | cli | def cli(port, baud, delay):
"""ampy - Adafruit MicroPython Tool
Ampy is a tool to control MicroPython boards over a serial connection. Using
ampy you can manipulate files on the board's internal filesystem and even run
scripts.
"""
global _board
# On Windows fix the COM port path name for ports above 9 (see comment in
# windows_full_port_name function).
if platform.system() == "Windows":
port = windows_full_port_name(port)
_board = pyboard.Pyboard(port, baudrate=baud, rawdelay=delay) | python | def cli(port, baud, delay):
global _board
# On Windows fix the COM port path name for ports above 9 (see comment in
# windows_full_port_name function).
if platform.system() == "Windows":
port = windows_full_port_name(port)
_board = pyboard.Pyboard(port, baudrate=baud, rawdelay=delay) | [
"def",
"cli",
"(",
"port",
",",
"baud",
",",
"delay",
")",
":",
"global",
"_board",
"# On Windows fix the COM port path name for ports above 9 (see comment in",
"# windows_full_port_name function).",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"\"Windows\"",
":",
"... | ampy - Adafruit MicroPython Tool
Ampy is a tool to control MicroPython boards over a serial connection. Using
ampy you can manipulate files on the board's internal filesystem and even run
scripts. | [
"ampy",
"-",
"Adafruit",
"MicroPython",
"Tool"
] | 6851f8b177c334f5ff7bd43bf07307a437433ba2 | https://github.com/pycampers/ampy/blob/6851f8b177c334f5ff7bd43bf07307a437433ba2/ampy/cli.py#L87-L99 |
227,469 | pycampers/ampy | ampy/cli.py | get | def get(remote_file, local_file):
"""
Retrieve a file from the board.
Get will download a file from the board and print its contents or save it
locally. You must pass at least one argument which is the path to the file
to download from the board. If you don't specify a second argument then
the file contents will be printed to standard output. However if you pass
a file name as the second argument then the contents of the downloaded file
will be saved to that file (overwriting anything inside it!).
For example to retrieve the boot.py and print it out run:
ampy --port /board/serial/port get boot.py
Or to get main.py and save it as main.py locally run:
ampy --port /board/serial/port get main.py main.py
"""
# Get the file contents.
board_files = files.Files(_board)
contents = board_files.get(remote_file)
# Print the file out if no local file was provided, otherwise save it.
if local_file is None:
print(contents.decode("utf-8"))
else:
local_file.write(contents) | python | def get(remote_file, local_file):
# Get the file contents.
board_files = files.Files(_board)
contents = board_files.get(remote_file)
# Print the file out if no local file was provided, otherwise save it.
if local_file is None:
print(contents.decode("utf-8"))
else:
local_file.write(contents) | [
"def",
"get",
"(",
"remote_file",
",",
"local_file",
")",
":",
"# Get the file contents.",
"board_files",
"=",
"files",
".",
"Files",
"(",
"_board",
")",
"contents",
"=",
"board_files",
".",
"get",
"(",
"remote_file",
")",
"# Print the file out if no local file was ... | Retrieve a file from the board.
Get will download a file from the board and print its contents or save it
locally. You must pass at least one argument which is the path to the file
to download from the board. If you don't specify a second argument then
the file contents will be printed to standard output. However if you pass
a file name as the second argument then the contents of the downloaded file
will be saved to that file (overwriting anything inside it!).
For example to retrieve the boot.py and print it out run:
ampy --port /board/serial/port get boot.py
Or to get main.py and save it as main.py locally run:
ampy --port /board/serial/port get main.py main.py | [
"Retrieve",
"a",
"file",
"from",
"the",
"board",
"."
] | 6851f8b177c334f5ff7bd43bf07307a437433ba2 | https://github.com/pycampers/ampy/blob/6851f8b177c334f5ff7bd43bf07307a437433ba2/ampy/cli.py#L105-L131 |
227,470 | pycampers/ampy | ampy/cli.py | mkdir | def mkdir(directory, exists_okay):
"""
Create a directory on the board.
Mkdir will create the specified directory on the board. One argument is
required, the full path of the directory to create.
Note that you cannot recursively create a hierarchy of directories with one
mkdir command, instead you must create each parent directory with separate
mkdir command calls.
For example to make a directory under the root called 'code':
ampy --port /board/serial/port mkdir /code
"""
# Run the mkdir command.
board_files = files.Files(_board)
board_files.mkdir(directory, exists_okay=exists_okay) | python | def mkdir(directory, exists_okay):
# Run the mkdir command.
board_files = files.Files(_board)
board_files.mkdir(directory, exists_okay=exists_okay) | [
"def",
"mkdir",
"(",
"directory",
",",
"exists_okay",
")",
":",
"# Run the mkdir command.",
"board_files",
"=",
"files",
".",
"Files",
"(",
"_board",
")",
"board_files",
".",
"mkdir",
"(",
"directory",
",",
"exists_okay",
"=",
"exists_okay",
")"
] | Create a directory on the board.
Mkdir will create the specified directory on the board. One argument is
required, the full path of the directory to create.
Note that you cannot recursively create a hierarchy of directories with one
mkdir command, instead you must create each parent directory with separate
mkdir command calls.
For example to make a directory under the root called 'code':
ampy --port /board/serial/port mkdir /code | [
"Create",
"a",
"directory",
"on",
"the",
"board",
"."
] | 6851f8b177c334f5ff7bd43bf07307a437433ba2 | https://github.com/pycampers/ampy/blob/6851f8b177c334f5ff7bd43bf07307a437433ba2/ampy/cli.py#L139-L156 |
227,471 | pycampers/ampy | ampy/cli.py | ls | def ls(directory, long_format, recursive):
"""List contents of a directory on the board.
Can pass an optional argument which is the path to the directory. The
default is to list the contents of the root, /, path.
For example to list the contents of the root run:
ampy --port /board/serial/port ls
Or to list the contents of the /foo/bar directory on the board run:
ampy --port /board/serial/port ls /foo/bar
Add the -l or --long_format flag to print the size of files (however note
MicroPython does not calculate the size of folders and will show 0 bytes):
ampy --port /board/serial/port ls -l /foo/bar
"""
# List each file/directory on a separate line.
board_files = files.Files(_board)
for f in board_files.ls(directory, long_format=long_format, recursive=recursive):
print(f) | python | def ls(directory, long_format, recursive):
# List each file/directory on a separate line.
board_files = files.Files(_board)
for f in board_files.ls(directory, long_format=long_format, recursive=recursive):
print(f) | [
"def",
"ls",
"(",
"directory",
",",
"long_format",
",",
"recursive",
")",
":",
"# List each file/directory on a separate line.",
"board_files",
"=",
"files",
".",
"Files",
"(",
"_board",
")",
"for",
"f",
"in",
"board_files",
".",
"ls",
"(",
"directory",
",",
"... | List contents of a directory on the board.
Can pass an optional argument which is the path to the directory. The
default is to list the contents of the root, /, path.
For example to list the contents of the root run:
ampy --port /board/serial/port ls
Or to list the contents of the /foo/bar directory on the board run:
ampy --port /board/serial/port ls /foo/bar
Add the -l or --long_format flag to print the size of files (however note
MicroPython does not calculate the size of folders and will show 0 bytes):
ampy --port /board/serial/port ls -l /foo/bar | [
"List",
"contents",
"of",
"a",
"directory",
"on",
"the",
"board",
"."
] | 6851f8b177c334f5ff7bd43bf07307a437433ba2 | https://github.com/pycampers/ampy/blob/6851f8b177c334f5ff7bd43bf07307a437433ba2/ampy/cli.py#L173-L195 |
227,472 | pycampers/ampy | ampy/cli.py | put | def put(local, remote):
"""Put a file or folder and its contents on the board.
Put will upload a local file or folder to the board. If the file already
exists on the board it will be overwritten with no warning! You must pass
at least one argument which is the path to the local file/folder to
upload. If the item to upload is a folder then it will be copied to the
board recursively with its entire child structure. You can pass a second
optional argument which is the path and name of the file/folder to put to
on the connected board.
For example to upload a main.py from the current directory to the board's
root run:
ampy --port /board/serial/port put main.py
Or to upload a board_boot.py from a ./foo subdirectory and save it as boot.py
in the board's root run:
ampy --port /board/serial/port put ./foo/board_boot.py boot.py
To upload a local folder adafruit_library and all of its child files/folders
as an item under the board's root run:
ampy --port /board/serial/port put adafruit_library
Or to put a local folder adafruit_library on the board under the path
/lib/adafruit_library on the board run:
ampy --port /board/serial/port put adafruit_library /lib/adafruit_library
"""
# Use the local filename if no remote filename is provided.
if remote is None:
remote = os.path.basename(os.path.abspath(local))
# Check if path is a folder and do recursive copy of everything inside it.
# Otherwise it's a file and should simply be copied over.
if os.path.isdir(local):
# Directory copy, create the directory and walk all children to copy
# over the files.
board_files = files.Files(_board)
for parent, child_dirs, child_files in os.walk(local):
# Create board filesystem absolute path to parent directory.
remote_parent = posixpath.normpath(
posixpath.join(remote, os.path.relpath(parent, local))
)
try:
# Create remote parent directory.
board_files.mkdir(remote_parent)
# Loop through all the files and put them on the board too.
for filename in child_files:
with open(os.path.join(parent, filename), "rb") as infile:
remote_filename = posixpath.join(remote_parent, filename)
board_files.put(remote_filename, infile.read())
except files.DirectoryExistsError:
# Ignore errors for directories that already exist.
pass
else:
# File copy, open the file and copy its contents to the board.
# Put the file on the board.
with open(local, "rb") as infile:
board_files = files.Files(_board)
board_files.put(remote, infile.read()) | python | def put(local, remote):
# Use the local filename if no remote filename is provided.
if remote is None:
remote = os.path.basename(os.path.abspath(local))
# Check if path is a folder and do recursive copy of everything inside it.
# Otherwise it's a file and should simply be copied over.
if os.path.isdir(local):
# Directory copy, create the directory and walk all children to copy
# over the files.
board_files = files.Files(_board)
for parent, child_dirs, child_files in os.walk(local):
# Create board filesystem absolute path to parent directory.
remote_parent = posixpath.normpath(
posixpath.join(remote, os.path.relpath(parent, local))
)
try:
# Create remote parent directory.
board_files.mkdir(remote_parent)
# Loop through all the files and put them on the board too.
for filename in child_files:
with open(os.path.join(parent, filename), "rb") as infile:
remote_filename = posixpath.join(remote_parent, filename)
board_files.put(remote_filename, infile.read())
except files.DirectoryExistsError:
# Ignore errors for directories that already exist.
pass
else:
# File copy, open the file and copy its contents to the board.
# Put the file on the board.
with open(local, "rb") as infile:
board_files = files.Files(_board)
board_files.put(remote, infile.read()) | [
"def",
"put",
"(",
"local",
",",
"remote",
")",
":",
"# Use the local filename if no remote filename is provided.",
"if",
"remote",
"is",
"None",
":",
"remote",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"local",
")... | Put a file or folder and its contents on the board.
Put will upload a local file or folder to the board. If the file already
exists on the board it will be overwritten with no warning! You must pass
at least one argument which is the path to the local file/folder to
upload. If the item to upload is a folder then it will be copied to the
board recursively with its entire child structure. You can pass a second
optional argument which is the path and name of the file/folder to put to
on the connected board.
For example to upload a main.py from the current directory to the board's
root run:
ampy --port /board/serial/port put main.py
Or to upload a board_boot.py from a ./foo subdirectory and save it as boot.py
in the board's root run:
ampy --port /board/serial/port put ./foo/board_boot.py boot.py
To upload a local folder adafruit_library and all of its child files/folders
as an item under the board's root run:
ampy --port /board/serial/port put adafruit_library
Or to put a local folder adafruit_library on the board under the path
/lib/adafruit_library on the board run:
ampy --port /board/serial/port put adafruit_library /lib/adafruit_library | [
"Put",
"a",
"file",
"or",
"folder",
"and",
"its",
"contents",
"on",
"the",
"board",
"."
] | 6851f8b177c334f5ff7bd43bf07307a437433ba2 | https://github.com/pycampers/ampy/blob/6851f8b177c334f5ff7bd43bf07307a437433ba2/ampy/cli.py#L201-L263 |
227,473 | pycampers/ampy | ampy/cli.py | rmdir | def rmdir(remote_folder, missing_okay):
"""Forcefully remove a folder and all its children from the board.
Remove the specified folder from the board's filesystem. Must specify one
argument which is the path to the folder to delete. This will delete the
directory and ALL of its children recursively, use with caution!
For example to delete everything under /adafruit_library from the root of a
board run:
ampy --port /board/serial/port rmdir adafruit_library
"""
# Delete the provided file/directory on the board.
board_files = files.Files(_board)
board_files.rmdir(remote_folder, missing_okay=missing_okay) | python | def rmdir(remote_folder, missing_okay):
# Delete the provided file/directory on the board.
board_files = files.Files(_board)
board_files.rmdir(remote_folder, missing_okay=missing_okay) | [
"def",
"rmdir",
"(",
"remote_folder",
",",
"missing_okay",
")",
":",
"# Delete the provided file/directory on the board.",
"board_files",
"=",
"files",
".",
"Files",
"(",
"_board",
")",
"board_files",
".",
"rmdir",
"(",
"remote_folder",
",",
"missing_okay",
"=",
"mi... | Forcefully remove a folder and all its children from the board.
Remove the specified folder from the board's filesystem. Must specify one
argument which is the path to the folder to delete. This will delete the
directory and ALL of its children recursively, use with caution!
For example to delete everything under /adafruit_library from the root of a
board run:
ampy --port /board/serial/port rmdir adafruit_library | [
"Forcefully",
"remove",
"a",
"folder",
"and",
"all",
"its",
"children",
"from",
"the",
"board",
"."
] | 6851f8b177c334f5ff7bd43bf07307a437433ba2 | https://github.com/pycampers/ampy/blob/6851f8b177c334f5ff7bd43bf07307a437433ba2/ampy/cli.py#L290-L304 |
227,474 | pycampers/ampy | ampy/cli.py | run | def run(local_file, no_output):
"""Run a script and print its output.
Run will send the specified file to the board and execute it immediately.
Any output from the board will be printed to the console (note that this is
not a 'shell' and you can't send input to the program).
Note that if your code has a main or infinite loop you should add the --no-output
option. This will run the script and immediately exit without waiting for
the script to finish and print output.
For example to run a test.py script and print any output after it finishes:
ampy --port /board/serial/port run test.py
Or to run test.py and not wait for it to finish:
ampy --port /board/serial/port run --no-output test.py
"""
# Run the provided file and print its output.
board_files = files.Files(_board)
try:
output = board_files.run(local_file, not no_output)
if output is not None:
print(output.decode("utf-8"), end="")
except IOError:
click.echo(
"Failed to find or read input file: {0}".format(local_file), err=True
) | python | def run(local_file, no_output):
# Run the provided file and print its output.
board_files = files.Files(_board)
try:
output = board_files.run(local_file, not no_output)
if output is not None:
print(output.decode("utf-8"), end="")
except IOError:
click.echo(
"Failed to find or read input file: {0}".format(local_file), err=True
) | [
"def",
"run",
"(",
"local_file",
",",
"no_output",
")",
":",
"# Run the provided file and print its output.",
"board_files",
"=",
"files",
".",
"Files",
"(",
"_board",
")",
"try",
":",
"output",
"=",
"board_files",
".",
"run",
"(",
"local_file",
",",
"not",
"n... | Run a script and print its output.
Run will send the specified file to the board and execute it immediately.
Any output from the board will be printed to the console (note that this is
not a 'shell' and you can't send input to the program).
Note that if your code has a main or infinite loop you should add the --no-output
option. This will run the script and immediately exit without waiting for
the script to finish and print output.
For example to run a test.py script and print any output after it finishes:
ampy --port /board/serial/port run test.py
Or to run test.py and not wait for it to finish:
ampy --port /board/serial/port run --no-output test.py | [
"Run",
"a",
"script",
"and",
"print",
"its",
"output",
"."
] | 6851f8b177c334f5ff7bd43bf07307a437433ba2 | https://github.com/pycampers/ampy/blob/6851f8b177c334f5ff7bd43bf07307a437433ba2/ampy/cli.py#L315-L343 |
227,475 | base4sistemas/pyescpos | escpos/impl/epson.py | GenericESCPOS.kick_drawer | def kick_drawer(self, port=0, **kwargs):
"""Kick drawer connected to the given port.
In this implementation, cash drawers are identified according to the
port in which they are connected. This relation between drawers and
ports does not exists in the ESC/POS specification and it is just a
design decision to normalize cash drawers handling. From the user
application perspective, drawers are simply connected to port 0, 1, 2,
and so on.
If printer does not have this feature then no exception should be
raised.
:param int number: The port number to kick drawer (default is ``0``).
:raises CashDrawerException: If given port does not exists.
"""
if self.hardware_features.get(feature.CASHDRAWER_PORTS, False):
# if feature is available assume at least one port is available
max_ports = self.hardware_features.get(
feature.CASHDRAWER_AVAILABLE_PORTS, 1)
if port not in range(max_ports):
raise CashDrawerException('invalid cash drawer port: {!r} '
'(available ports are {!r})'.format(
port, range(max_ports)))
return self._kick_drawer_impl(port=port, **kwargs) | python | def kick_drawer(self, port=0, **kwargs):
if self.hardware_features.get(feature.CASHDRAWER_PORTS, False):
# if feature is available assume at least one port is available
max_ports = self.hardware_features.get(
feature.CASHDRAWER_AVAILABLE_PORTS, 1)
if port not in range(max_ports):
raise CashDrawerException('invalid cash drawer port: {!r} '
'(available ports are {!r})'.format(
port, range(max_ports)))
return self._kick_drawer_impl(port=port, **kwargs) | [
"def",
"kick_drawer",
"(",
"self",
",",
"port",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"hardware_features",
".",
"get",
"(",
"feature",
".",
"CASHDRAWER_PORTS",
",",
"False",
")",
":",
"# if feature is available assume at least one por... | Kick drawer connected to the given port.
In this implementation, cash drawers are identified according to the
port in which they are connected. This relation between drawers and
ports does not exists in the ESC/POS specification and it is just a
design decision to normalize cash drawers handling. From the user
application perspective, drawers are simply connected to port 0, 1, 2,
and so on.
If printer does not have this feature then no exception should be
raised.
:param int number: The port number to kick drawer (default is ``0``).
:raises CashDrawerException: If given port does not exists. | [
"Kick",
"drawer",
"connected",
"to",
"the",
"given",
"port",
"."
] | 621bd00f1499aff700f37d8d36d04e0d761708f1 | https://github.com/base4sistemas/pyescpos/blob/621bd00f1499aff700f37d8d36d04e0d761708f1/escpos/impl/epson.py#L363-L390 |
227,476 | base4sistemas/pyescpos | escpos/conn/serial.py | get_baudrates | def get_baudrates():
"""
Returns supported baud rates in a Django-like choices tuples.
"""
baudrates = []
s = pyserial.Serial()
for name, value in s.getSupportedBaudrates():
baudrates.append((value, name,))
return tuple(baudrates) | python | def get_baudrates():
baudrates = []
s = pyserial.Serial()
for name, value in s.getSupportedBaudrates():
baudrates.append((value, name,))
return tuple(baudrates) | [
"def",
"get_baudrates",
"(",
")",
":",
"baudrates",
"=",
"[",
"]",
"s",
"=",
"pyserial",
".",
"Serial",
"(",
")",
"for",
"name",
",",
"value",
"in",
"s",
".",
"getSupportedBaudrates",
"(",
")",
":",
"baudrates",
".",
"append",
"(",
"(",
"value",
",",... | Returns supported baud rates in a Django-like choices tuples. | [
"Returns",
"supported",
"baud",
"rates",
"in",
"a",
"Django",
"-",
"like",
"choices",
"tuples",
"."
] | 621bd00f1499aff700f37d8d36d04e0d761708f1 | https://github.com/base4sistemas/pyescpos/blob/621bd00f1499aff700f37d8d36d04e0d761708f1/escpos/conn/serial.py#L98-L106 |
227,477 | base4sistemas/pyescpos | escpos/conn/serial.py | get_databits | def get_databits():
"""
Returns supported byte sizes in a Django-like choices tuples.
"""
databits = []
s = pyserial.Serial()
for name, value in s.getSupportedByteSizes():
databits.append((value, name,))
return tuple(databits) | python | def get_databits():
databits = []
s = pyserial.Serial()
for name, value in s.getSupportedByteSizes():
databits.append((value, name,))
return tuple(databits) | [
"def",
"get_databits",
"(",
")",
":",
"databits",
"=",
"[",
"]",
"s",
"=",
"pyserial",
".",
"Serial",
"(",
")",
"for",
"name",
",",
"value",
"in",
"s",
".",
"getSupportedByteSizes",
"(",
")",
":",
"databits",
".",
"append",
"(",
"(",
"value",
",",
... | Returns supported byte sizes in a Django-like choices tuples. | [
"Returns",
"supported",
"byte",
"sizes",
"in",
"a",
"Django",
"-",
"like",
"choices",
"tuples",
"."
] | 621bd00f1499aff700f37d8d36d04e0d761708f1 | https://github.com/base4sistemas/pyescpos/blob/621bd00f1499aff700f37d8d36d04e0d761708f1/escpos/conn/serial.py#L109-L117 |
227,478 | base4sistemas/pyescpos | escpos/conn/serial.py | get_stopbits | def get_stopbits():
"""
Returns supported stop bit lengths in a Django-like choices tuples.
"""
stopbits = []
s = pyserial.Serial()
for name, value in s.getSupportedStopbits():
stopbits.append((value, name,))
return tuple(stopbits) | python | def get_stopbits():
stopbits = []
s = pyserial.Serial()
for name, value in s.getSupportedStopbits():
stopbits.append((value, name,))
return tuple(stopbits) | [
"def",
"get_stopbits",
"(",
")",
":",
"stopbits",
"=",
"[",
"]",
"s",
"=",
"pyserial",
".",
"Serial",
"(",
")",
"for",
"name",
",",
"value",
"in",
"s",
".",
"getSupportedStopbits",
"(",
")",
":",
"stopbits",
".",
"append",
"(",
"(",
"value",
",",
"... | Returns supported stop bit lengths in a Django-like choices tuples. | [
"Returns",
"supported",
"stop",
"bit",
"lengths",
"in",
"a",
"Django",
"-",
"like",
"choices",
"tuples",
"."
] | 621bd00f1499aff700f37d8d36d04e0d761708f1 | https://github.com/base4sistemas/pyescpos/blob/621bd00f1499aff700f37d8d36d04e0d761708f1/escpos/conn/serial.py#L120-L128 |
227,479 | base4sistemas/pyescpos | escpos/conn/serial.py | get_parities | def get_parities():
"""
Returns supported parities in a Django-like choices tuples.
"""
parities = []
s = pyserial.Serial()
for name, value in s.getSupportedParities():
parities.append((value, name,))
return tuple(parities) | python | def get_parities():
parities = []
s = pyserial.Serial()
for name, value in s.getSupportedParities():
parities.append((value, name,))
return tuple(parities) | [
"def",
"get_parities",
"(",
")",
":",
"parities",
"=",
"[",
"]",
"s",
"=",
"pyserial",
".",
"Serial",
"(",
")",
"for",
"name",
",",
"value",
"in",
"s",
".",
"getSupportedParities",
"(",
")",
":",
"parities",
".",
"append",
"(",
"(",
"value",
",",
"... | Returns supported parities in a Django-like choices tuples. | [
"Returns",
"supported",
"parities",
"in",
"a",
"Django",
"-",
"like",
"choices",
"tuples",
"."
] | 621bd00f1499aff700f37d8d36d04e0d761708f1 | https://github.com/base4sistemas/pyescpos/blob/621bd00f1499aff700f37d8d36d04e0d761708f1/escpos/conn/serial.py#L131-L139 |
227,480 | base4sistemas/pyescpos | escpos/conn/serial.py | SerialSettings.get_connection | def get_connection(self, **kwargs):
"""Return a serial connection implementation suitable for the specified
protocol. Raises ``RuntimeError`` if there is no implementation for
the given protocol.
.. warn::
This may be a little bit confusing since there is no effective
connection but an implementation of a connection pattern.
"""
if self.is_rtscts():
return RTSCTSConnection(self, **kwargs)
if self.is_dsrdtr():
return DSRDTRConnection(self, **kwargs)
else:
raise RuntimeError('Serial protocol "%s" is not available.' % (
self.protocol)) | python | def get_connection(self, **kwargs):
if self.is_rtscts():
return RTSCTSConnection(self, **kwargs)
if self.is_dsrdtr():
return DSRDTRConnection(self, **kwargs)
else:
raise RuntimeError('Serial protocol "%s" is not available.' % (
self.protocol)) | [
"def",
"get_connection",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"is_rtscts",
"(",
")",
":",
"return",
"RTSCTSConnection",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
"if",
"self",
".",
"is_dsrdtr",
"(",
")",
":",
"return",
... | Return a serial connection implementation suitable for the specified
protocol. Raises ``RuntimeError`` if there is no implementation for
the given protocol.
.. warn::
This may be a little bit confusing since there is no effective
connection but an implementation of a connection pattern. | [
"Return",
"a",
"serial",
"connection",
"implementation",
"suitable",
"for",
"the",
"specified",
"protocol",
".",
"Raises",
"RuntimeError",
"if",
"there",
"is",
"no",
"implementation",
"for",
"the",
"given",
"protocol",
"."
] | 621bd00f1499aff700f37d8d36d04e0d761708f1 | https://github.com/base4sistemas/pyescpos/blob/621bd00f1499aff700f37d8d36d04e0d761708f1/escpos/conn/serial.py#L301-L320 |
227,481 | base4sistemas/pyescpos | escpos/conn/serial.py | SerialConnection.write | def write(self, data):
"""Write data to serial port."""
for chunk in chunks(data, 512):
self.wait_to_write()
self.comport.write(chunk)
self.comport.flush() | python | def write(self, data):
for chunk in chunks(data, 512):
self.wait_to_write()
self.comport.write(chunk)
self.comport.flush() | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"for",
"chunk",
"in",
"chunks",
"(",
"data",
",",
"512",
")",
":",
"self",
".",
"wait_to_write",
"(",
")",
"self",
".",
"comport",
".",
"write",
"(",
"chunk",
")",
"self",
".",
"comport",
".",
"... | Write data to serial port. | [
"Write",
"data",
"to",
"serial",
"port",
"."
] | 621bd00f1499aff700f37d8d36d04e0d761708f1 | https://github.com/base4sistemas/pyescpos/blob/621bd00f1499aff700f37d8d36d04e0d761708f1/escpos/conn/serial.py#L444-L449 |
227,482 | base4sistemas/pyescpos | escpos/conn/serial.py | SerialConnection.read | def read(self):
"""Read data from serial port and returns a ``bytearray``."""
data = bytearray()
while True:
incoming_bytes = self.comport.inWaiting()
if incoming_bytes == 0:
break
else:
content = self.comport.read(size=incoming_bytes)
data.extend(bytearray(content))
return data | python | def read(self):
data = bytearray()
while True:
incoming_bytes = self.comport.inWaiting()
if incoming_bytes == 0:
break
else:
content = self.comport.read(size=incoming_bytes)
data.extend(bytearray(content))
return data | [
"def",
"read",
"(",
"self",
")",
":",
"data",
"=",
"bytearray",
"(",
")",
"while",
"True",
":",
"incoming_bytes",
"=",
"self",
".",
"comport",
".",
"inWaiting",
"(",
")",
"if",
"incoming_bytes",
"==",
"0",
":",
"break",
"else",
":",
"content",
"=",
"... | Read data from serial port and returns a ``bytearray``. | [
"Read",
"data",
"from",
"serial",
"port",
"and",
"returns",
"a",
"bytearray",
"."
] | 621bd00f1499aff700f37d8d36d04e0d761708f1 | https://github.com/base4sistemas/pyescpos/blob/621bd00f1499aff700f37d8d36d04e0d761708f1/escpos/conn/serial.py#L452-L462 |
227,483 | base4sistemas/pyescpos | escpos/conn/file.py | FileConnection.write | def write(self, data):
"""Print any command sent in raw format.
:param bytes data: arbitrary code to be printed.
"""
self.device.write(data)
if self.auto_flush:
self.flush() | python | def write(self, data):
self.device.write(data)
if self.auto_flush:
self.flush() | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"device",
".",
"write",
"(",
"data",
")",
"if",
"self",
".",
"auto_flush",
":",
"self",
".",
"flush",
"(",
")"
] | Print any command sent in raw format.
:param bytes data: arbitrary code to be printed. | [
"Print",
"any",
"command",
"sent",
"in",
"raw",
"format",
"."
] | 621bd00f1499aff700f37d8d36d04e0d761708f1 | https://github.com/base4sistemas/pyescpos/blob/621bd00f1499aff700f37d8d36d04e0d761708f1/escpos/conn/file.py#L53-L60 |
227,484 | base4sistemas/pyescpos | escpos/helpers.py | is_value_in | def is_value_in(constants_group, value):
"""
Checks whether value can be found in the given constants group, which in
turn, should be a Django-like choices tuple.
"""
for const_value, label in constants_group:
if const_value == value:
return True
return False | python | def is_value_in(constants_group, value):
for const_value, label in constants_group:
if const_value == value:
return True
return False | [
"def",
"is_value_in",
"(",
"constants_group",
",",
"value",
")",
":",
"for",
"const_value",
",",
"label",
"in",
"constants_group",
":",
"if",
"const_value",
"==",
"value",
":",
"return",
"True",
"return",
"False"
] | Checks whether value can be found in the given constants group, which in
turn, should be a Django-like choices tuple. | [
"Checks",
"whether",
"value",
"can",
"be",
"found",
"in",
"the",
"given",
"constants",
"group",
"which",
"in",
"turn",
"should",
"be",
"a",
"Django",
"-",
"like",
"choices",
"tuple",
"."
] | 621bd00f1499aff700f37d8d36d04e0d761708f1 | https://github.com/base4sistemas/pyescpos/blob/621bd00f1499aff700f37d8d36d04e0d761708f1/escpos/helpers.py#L104-L112 |
227,485 | facebook/codemod | codemod/base.py | run_interactive | def run_interactive(query, editor=None, just_count=False, default_no=False):
"""
Asks the user about each patch suggested by the result of the query.
@param query An instance of the Query class.
@param editor Name of editor to use for manual intervention, e.g.
'vim'
or 'emacs'. If omitted/None, defaults to $EDITOR
environment variable.
@param just_count If true: don't run normally. Just print out number of
places in the codebase where the query matches.
"""
global yes_to_all
# Load start from bookmark, if appropriate.
bookmark = _load_bookmark()
if bookmark:
print('Resume where you left off, at %s (y/n)? '
% str(bookmark), end=' ')
sys.stdout.flush()
if (_prompt(default='y') == 'y'):
query.start_position = bookmark
# Okay, enough of this foolishness of computing start and end.
# Let's ask the user about some one line diffs!
print('Searching for first instance...')
suggestions = query.generate_patches()
if just_count:
for count, _ in enumerate(suggestions):
terminal.terminal_move_to_beginning_of_line()
print(count, end=" ")
sys.stdout.flush() # since print statement ends in comma
print()
return
for patch in suggestions:
_save_bookmark(patch.start_position)
_ask_about_patch(patch, editor, default_no)
print('Searching...')
_delete_bookmark()
if yes_to_all:
terminal.terminal_clear()
print(
"You MUST indicate in your code review:"
" \"codemod with 'Yes to all'\"."
"Make sure you and other people review the changes.\n\n"
"With great power, comes great responsibility."
) | python | def run_interactive(query, editor=None, just_count=False, default_no=False):
global yes_to_all
# Load start from bookmark, if appropriate.
bookmark = _load_bookmark()
if bookmark:
print('Resume where you left off, at %s (y/n)? '
% str(bookmark), end=' ')
sys.stdout.flush()
if (_prompt(default='y') == 'y'):
query.start_position = bookmark
# Okay, enough of this foolishness of computing start and end.
# Let's ask the user about some one line diffs!
print('Searching for first instance...')
suggestions = query.generate_patches()
if just_count:
for count, _ in enumerate(suggestions):
terminal.terminal_move_to_beginning_of_line()
print(count, end=" ")
sys.stdout.flush() # since print statement ends in comma
print()
return
for patch in suggestions:
_save_bookmark(patch.start_position)
_ask_about_patch(patch, editor, default_no)
print('Searching...')
_delete_bookmark()
if yes_to_all:
terminal.terminal_clear()
print(
"You MUST indicate in your code review:"
" \"codemod with 'Yes to all'\"."
"Make sure you and other people review the changes.\n\n"
"With great power, comes great responsibility."
) | [
"def",
"run_interactive",
"(",
"query",
",",
"editor",
"=",
"None",
",",
"just_count",
"=",
"False",
",",
"default_no",
"=",
"False",
")",
":",
"global",
"yes_to_all",
"# Load start from bookmark, if appropriate.",
"bookmark",
"=",
"_load_bookmark",
"(",
")",
"if"... | Asks the user about each patch suggested by the result of the query.
@param query An instance of the Query class.
@param editor Name of editor to use for manual intervention, e.g.
'vim'
or 'emacs'. If omitted/None, defaults to $EDITOR
environment variable.
@param just_count If true: don't run normally. Just print out number of
places in the codebase where the query matches. | [
"Asks",
"the",
"user",
"about",
"each",
"patch",
"suggested",
"by",
"the",
"result",
"of",
"the",
"query",
"."
] | 78bb627792fc8a5253baa9cd9d8160533b16fd85 | https://github.com/facebook/codemod/blob/78bb627792fc8a5253baa9cd9d8160533b16fd85/codemod/base.py#L41-L89 |
227,486 | facebook/codemod | codemod/query.py | Query.get_all_patches | def get_all_patches(self, dont_use_cache=False):
"""
Computes a list of all patches matching this query, though ignoreing
self.start_position and self.end_position.
@param dont_use_cache If False, and get_all_patches has been called
before, compute the list computed last time.
"""
if not dont_use_cache and self._all_patches_cache is not None:
return self._all_patches_cache
print(
'Computing full change list (since you specified a percentage)...'
),
sys.stdout.flush() # since print statement ends in comma
endless_query = self.clone()
endless_query.start_position = endless_query.end_position = None
self._all_patches_cache = list(endless_query.generate_patches())
return self._all_patches_cache | python | def get_all_patches(self, dont_use_cache=False):
if not dont_use_cache and self._all_patches_cache is not None:
return self._all_patches_cache
print(
'Computing full change list (since you specified a percentage)...'
),
sys.stdout.flush() # since print statement ends in comma
endless_query = self.clone()
endless_query.start_position = endless_query.end_position = None
self._all_patches_cache = list(endless_query.generate_patches())
return self._all_patches_cache | [
"def",
"get_all_patches",
"(",
"self",
",",
"dont_use_cache",
"=",
"False",
")",
":",
"if",
"not",
"dont_use_cache",
"and",
"self",
".",
"_all_patches_cache",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_all_patches_cache",
"print",
"(",
"'Computing full c... | Computes a list of all patches matching this query, though ignoreing
self.start_position and self.end_position.
@param dont_use_cache If False, and get_all_patches has been called
before, compute the list computed last time. | [
"Computes",
"a",
"list",
"of",
"all",
"patches",
"matching",
"this",
"query",
"though",
"ignoreing",
"self",
".",
"start_position",
"and",
"self",
".",
"end_position",
"."
] | 78bb627792fc8a5253baa9cd9d8160533b16fd85 | https://github.com/facebook/codemod/blob/78bb627792fc8a5253baa9cd9d8160533b16fd85/codemod/query.py#L93-L112 |
227,487 | facebook/codemod | codemod/query.py | Query.compute_percentile | def compute_percentile(self, percentage):
"""
Returns a Position object that represents percentage%-far-of-the-way
through the larger task, as specified by this query.
@param percentage a number between 0 and 100.
"""
all_patches = self.get_all_patches()
return all_patches[
int(len(all_patches) * percentage / 100)
].start_position | python | def compute_percentile(self, percentage):
all_patches = self.get_all_patches()
return all_patches[
int(len(all_patches) * percentage / 100)
].start_position | [
"def",
"compute_percentile",
"(",
"self",
",",
"percentage",
")",
":",
"all_patches",
"=",
"self",
".",
"get_all_patches",
"(",
")",
"return",
"all_patches",
"[",
"int",
"(",
"len",
"(",
"all_patches",
")",
"*",
"percentage",
"/",
"100",
")",
"]",
".",
"... | Returns a Position object that represents percentage%-far-of-the-way
through the larger task, as specified by this query.
@param percentage a number between 0 and 100. | [
"Returns",
"a",
"Position",
"object",
"that",
"represents",
"percentage%",
"-",
"far",
"-",
"of",
"-",
"the",
"-",
"way",
"through",
"the",
"larger",
"task",
"as",
"specified",
"by",
"this",
"query",
"."
] | 78bb627792fc8a5253baa9cd9d8160533b16fd85 | https://github.com/facebook/codemod/blob/78bb627792fc8a5253baa9cd9d8160533b16fd85/codemod/query.py#L114-L124 |
227,488 | facebook/codemod | codemod/query.py | Query.generate_patches | def generate_patches(self):
"""
Generates a list of patches for each file underneath
self.root_directory
that satisfy the given conditions given
query conditions, where patches for
each file are suggested by self.suggestor.
"""
start_pos = self.start_position or Position(None, None)
end_pos = self.end_position or Position(None, None)
path_list = Query._walk_directory(self.root_directory)
path_list = Query._sublist(path_list, start_pos.path, end_pos.path)
path_list = (
path for path in path_list if
Query._path_looks_like_code(path) and
(self.path_filter(path)) or
(self.inc_extensionless and helpers.is_extensionless(path))
)
for path in path_list:
try:
lines = list(open(path))
except (IOError, UnicodeDecodeError):
# If we can't open the file--perhaps it's a symlink whose
# destination no loner exists--then short-circuit.
continue
for patch in self.suggestor(lines):
if path == start_pos.path:
if patch.start_line_number < start_pos.line_number:
continue # suggestion is pre-start_pos
if path == end_pos.path:
if patch.end_line_number >= end_pos.line_number:
break # suggestion is post-end_pos
old_lines = lines[
patch.start_line_number:patch.end_line_number]
if patch.new_lines is None or patch.new_lines != old_lines:
patch.path = path
yield patch
# re-open file, in case contents changed
lines[:] = list(open(path)) | python | def generate_patches(self):
start_pos = self.start_position or Position(None, None)
end_pos = self.end_position or Position(None, None)
path_list = Query._walk_directory(self.root_directory)
path_list = Query._sublist(path_list, start_pos.path, end_pos.path)
path_list = (
path for path in path_list if
Query._path_looks_like_code(path) and
(self.path_filter(path)) or
(self.inc_extensionless and helpers.is_extensionless(path))
)
for path in path_list:
try:
lines = list(open(path))
except (IOError, UnicodeDecodeError):
# If we can't open the file--perhaps it's a symlink whose
# destination no loner exists--then short-circuit.
continue
for patch in self.suggestor(lines):
if path == start_pos.path:
if patch.start_line_number < start_pos.line_number:
continue # suggestion is pre-start_pos
if path == end_pos.path:
if patch.end_line_number >= end_pos.line_number:
break # suggestion is post-end_pos
old_lines = lines[
patch.start_line_number:patch.end_line_number]
if patch.new_lines is None or patch.new_lines != old_lines:
patch.path = path
yield patch
# re-open file, in case contents changed
lines[:] = list(open(path)) | [
"def",
"generate_patches",
"(",
"self",
")",
":",
"start_pos",
"=",
"self",
".",
"start_position",
"or",
"Position",
"(",
"None",
",",
"None",
")",
"end_pos",
"=",
"self",
".",
"end_position",
"or",
"Position",
"(",
"None",
",",
"None",
")",
"path_list",
... | Generates a list of patches for each file underneath
self.root_directory
that satisfy the given conditions given
query conditions, where patches for
each file are suggested by self.suggestor. | [
"Generates",
"a",
"list",
"of",
"patches",
"for",
"each",
"file",
"underneath",
"self",
".",
"root_directory",
"that",
"satisfy",
"the",
"given",
"conditions",
"given",
"query",
"conditions",
"where",
"patches",
"for",
"each",
"file",
"are",
"suggested",
"by",
... | 78bb627792fc8a5253baa9cd9d8160533b16fd85 | https://github.com/facebook/codemod/blob/78bb627792fc8a5253baa9cd9d8160533b16fd85/codemod/query.py#L126-L167 |
227,489 | facebook/codemod | codemod/query.py | Query._walk_directory | def _walk_directory(root_directory):
"""
Generates the paths of all files that are ancestors
of `root_directory`.
"""
paths = [os.path.join(root, name)
for root, dirs, files in os.walk(root_directory) # noqa
for name in files]
paths.sort()
return paths | python | def _walk_directory(root_directory):
paths = [os.path.join(root, name)
for root, dirs, files in os.walk(root_directory) # noqa
for name in files]
paths.sort()
return paths | [
"def",
"_walk_directory",
"(",
"root_directory",
")",
":",
"paths",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"name",
")",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"root_directory",
")",
"# noqa",
"for... | Generates the paths of all files that are ancestors
of `root_directory`. | [
"Generates",
"the",
"paths",
"of",
"all",
"files",
"that",
"are",
"ancestors",
"of",
"root_directory",
"."
] | 78bb627792fc8a5253baa9cd9d8160533b16fd85 | https://github.com/facebook/codemod/blob/78bb627792fc8a5253baa9cd9d8160533b16fd85/codemod/query.py#L170-L180 |
227,490 | facebook/codemod | codemod/helpers.py | matches_extension | def matches_extension(path, extension):
"""
Returns True if path has the given extension, or if
the last path component matches the extension. Supports
Unix glob matching.
>>> matches_extension("./www/profile.php", "php")
True
>>> matches_extension("./scripts/menu.js", "html")
False
>>> matches_extension("./LICENSE", "LICENSE")
True
"""
_, ext = os.path.splitext(path)
if ext == '':
# If there is no extension, grab the file name and
# compare it to the given extension.
return os.path.basename(path) == extension
else:
# If the is an extension, drop the leading period and
# compare it to the extension.
return fnmatch.fnmatch(ext[1:], extension) | python | def matches_extension(path, extension):
_, ext = os.path.splitext(path)
if ext == '':
# If there is no extension, grab the file name and
# compare it to the given extension.
return os.path.basename(path) == extension
else:
# If the is an extension, drop the leading period and
# compare it to the extension.
return fnmatch.fnmatch(ext[1:], extension) | [
"def",
"matches_extension",
"(",
"path",
",",
"extension",
")",
":",
"_",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"path",
")",
"if",
"ext",
"==",
"''",
":",
"# If there is no extension, grab the file name and",
"# compare it to the given extensio... | Returns True if path has the given extension, or if
the last path component matches the extension. Supports
Unix glob matching.
>>> matches_extension("./www/profile.php", "php")
True
>>> matches_extension("./scripts/menu.js", "html")
False
>>> matches_extension("./LICENSE", "LICENSE")
True | [
"Returns",
"True",
"if",
"path",
"has",
"the",
"given",
"extension",
"or",
"if",
"the",
"last",
"path",
"component",
"matches",
"the",
"extension",
".",
"Supports",
"Unix",
"glob",
"matching",
"."
] | 78bb627792fc8a5253baa9cd9d8160533b16fd85 | https://github.com/facebook/codemod/blob/78bb627792fc8a5253baa9cd9d8160533b16fd85/codemod/helpers.py#L24-L45 |
227,491 | facebook/codemod | codemod/helpers.py | path_filter | def path_filter(extensions, exclude_paths=None):
"""
Returns a function that returns True if a filepath is acceptable.
@param extensions An array of strings. Specifies what file
extensions should be accepted by the
filter. If None, we default to the Unix glob
`*` and match every file extension.
@param exclude_paths An array of strings which represents filepaths
that should never be accepted by the filter. Unix
shell-style wildcards are supported.
@return function A filter function that will only return True
when a filepath is acceptable under the above
conditions.
>>> list(map(path_filter(extensions=['js', 'php']),
... ['./profile.php', './q.jjs']))
[True, False]
>>> list(map(path_filter(extensions=['*'],
... exclude_paths=['html']),
... ['./html/x.php', './lib/y.js']))
[False, True]
>>> list(map(path_filter(extensions=['js', 'BUILD']),
... ['./a.js', './BUILD', './profile.php']))
[True, True, False]
>>> list(map(path_filter(extensions=['js'],
... exclude_paths=['*/node_modules/*']),
... ['./a.js', './tools/node_modules/dep.js']))
[True, False]
"""
exclude_paths = exclude_paths or []
def the_filter(path):
if not any(matches_extension(path, extension)
for extension in extensions):
return False
if exclude_paths:
for excluded in exclude_paths:
if (path.startswith(excluded) or
path.startswith('./' + excluded) or
fnmatch.fnmatch(path, excluded)):
return False
return True
return the_filter | python | def path_filter(extensions, exclude_paths=None):
exclude_paths = exclude_paths or []
def the_filter(path):
if not any(matches_extension(path, extension)
for extension in extensions):
return False
if exclude_paths:
for excluded in exclude_paths:
if (path.startswith(excluded) or
path.startswith('./' + excluded) or
fnmatch.fnmatch(path, excluded)):
return False
return True
return the_filter | [
"def",
"path_filter",
"(",
"extensions",
",",
"exclude_paths",
"=",
"None",
")",
":",
"exclude_paths",
"=",
"exclude_paths",
"or",
"[",
"]",
"def",
"the_filter",
"(",
"path",
")",
":",
"if",
"not",
"any",
"(",
"matches_extension",
"(",
"path",
",",
"extens... | Returns a function that returns True if a filepath is acceptable.
@param extensions An array of strings. Specifies what file
extensions should be accepted by the
filter. If None, we default to the Unix glob
`*` and match every file extension.
@param exclude_paths An array of strings which represents filepaths
that should never be accepted by the filter. Unix
shell-style wildcards are supported.
@return function A filter function that will only return True
when a filepath is acceptable under the above
conditions.
>>> list(map(path_filter(extensions=['js', 'php']),
... ['./profile.php', './q.jjs']))
[True, False]
>>> list(map(path_filter(extensions=['*'],
... exclude_paths=['html']),
... ['./html/x.php', './lib/y.js']))
[False, True]
>>> list(map(path_filter(extensions=['js', 'BUILD']),
... ['./a.js', './BUILD', './profile.php']))
[True, True, False]
>>> list(map(path_filter(extensions=['js'],
... exclude_paths=['*/node_modules/*']),
... ['./a.js', './tools/node_modules/dep.js']))
[True, False] | [
"Returns",
"a",
"function",
"that",
"returns",
"True",
"if",
"a",
"filepath",
"is",
"acceptable",
"."
] | 78bb627792fc8a5253baa9cd9d8160533b16fd85 | https://github.com/facebook/codemod/blob/78bb627792fc8a5253baa9cd9d8160533b16fd85/codemod/helpers.py#L48-L92 |
227,492 | facebook/codemod | codemod/terminal_helper.py | _terminal_use_capability | def _terminal_use_capability(capability_name):
"""
If the terminal supports the given capability, output it. Return whether
it was output.
"""
curses.setupterm()
capability = curses.tigetstr(capability_name)
if capability:
sys.stdout.write(_unicode(capability))
return bool(capability) | python | def _terminal_use_capability(capability_name):
curses.setupterm()
capability = curses.tigetstr(capability_name)
if capability:
sys.stdout.write(_unicode(capability))
return bool(capability) | [
"def",
"_terminal_use_capability",
"(",
"capability_name",
")",
":",
"curses",
".",
"setupterm",
"(",
")",
"capability",
"=",
"curses",
".",
"tigetstr",
"(",
"capability_name",
")",
"if",
"capability",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"_unicode",
... | If the terminal supports the given capability, output it. Return whether
it was output. | [
"If",
"the",
"terminal",
"supports",
"the",
"given",
"capability",
"output",
"it",
".",
"Return",
"whether",
"it",
"was",
"output",
"."
] | 78bb627792fc8a5253baa9cd9d8160533b16fd85 | https://github.com/facebook/codemod/blob/78bb627792fc8a5253baa9cd9d8160533b16fd85/codemod/terminal_helper.py#L74-L83 |
227,493 | SmileyChris/django-countries | django_countries/__init__.py | Countries.get_option | def get_option(self, option):
"""
Get a configuration option, trying the options attribute first and
falling back to a Django project setting.
"""
value = getattr(self, option, None)
if value is not None:
return value
return getattr(settings, "COUNTRIES_{0}".format(option.upper())) | python | def get_option(self, option):
value = getattr(self, option, None)
if value is not None:
return value
return getattr(settings, "COUNTRIES_{0}".format(option.upper())) | [
"def",
"get_option",
"(",
"self",
",",
"option",
")",
":",
"value",
"=",
"getattr",
"(",
"self",
",",
"option",
",",
"None",
")",
"if",
"value",
"is",
"not",
"None",
":",
"return",
"value",
"return",
"getattr",
"(",
"settings",
",",
"\"COUNTRIES_{0}\"",
... | Get a configuration option, trying the options attribute first and
falling back to a Django project setting. | [
"Get",
"a",
"configuration",
"option",
"trying",
"the",
"options",
"attribute",
"first",
"and",
"falling",
"back",
"to",
"a",
"Django",
"project",
"setting",
"."
] | 68b0934e8180d47bc15eff2887b6887aaa6e0228 | https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/__init__.py#L56-L64 |
227,494 | SmileyChris/django-countries | django_countries/__init__.py | Countries.countries | def countries(self):
"""
Return the a dictionary of countries, modified by any overriding
options.
The result is cached so future lookups are less work intensive.
"""
if not hasattr(self, "_countries"):
only = self.get_option("only")
if only:
only_choices = True
if not isinstance(only, dict):
for item in only:
if isinstance(item, six.string_types):
only_choices = False
break
if only and only_choices:
self._countries = dict(only)
else:
# Local import so that countries aren't loaded into memory
# until first used.
from django_countries.data import COUNTRIES
self._countries = dict(COUNTRIES)
if self.get_option("common_names"):
self._countries.update(self.COMMON_NAMES)
override = self.get_option("override")
if override:
self._countries.update(override)
self._countries = dict(
(code, name)
for code, name in self._countries.items()
if name is not None
)
if only and not only_choices:
countries = {}
for item in only:
if isinstance(item, six.string_types):
countries[item] = self._countries[item]
else:
key, value = item
countries[key] = value
self._countries = countries
self.countries_first = []
first = self.get_option("first") or []
for code in first:
code = self.alpha2(code)
if code in self._countries:
self.countries_first.append(code)
return self._countries | python | def countries(self):
if not hasattr(self, "_countries"):
only = self.get_option("only")
if only:
only_choices = True
if not isinstance(only, dict):
for item in only:
if isinstance(item, six.string_types):
only_choices = False
break
if only and only_choices:
self._countries = dict(only)
else:
# Local import so that countries aren't loaded into memory
# until first used.
from django_countries.data import COUNTRIES
self._countries = dict(COUNTRIES)
if self.get_option("common_names"):
self._countries.update(self.COMMON_NAMES)
override = self.get_option("override")
if override:
self._countries.update(override)
self._countries = dict(
(code, name)
for code, name in self._countries.items()
if name is not None
)
if only and not only_choices:
countries = {}
for item in only:
if isinstance(item, six.string_types):
countries[item] = self._countries[item]
else:
key, value = item
countries[key] = value
self._countries = countries
self.countries_first = []
first = self.get_option("first") or []
for code in first:
code = self.alpha2(code)
if code in self._countries:
self.countries_first.append(code)
return self._countries | [
"def",
"countries",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_countries\"",
")",
":",
"only",
"=",
"self",
".",
"get_option",
"(",
"\"only\"",
")",
"if",
"only",
":",
"only_choices",
"=",
"True",
"if",
"not",
"isinstance",
"(... | Return the a dictionary of countries, modified by any overriding
options.
The result is cached so future lookups are less work intensive. | [
"Return",
"the",
"a",
"dictionary",
"of",
"countries",
"modified",
"by",
"any",
"overriding",
"options",
"."
] | 68b0934e8180d47bc15eff2887b6887aaa6e0228 | https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/__init__.py#L67-L116 |
227,495 | SmileyChris/django-countries | django_countries/__init__.py | Countries.translate_pair | def translate_pair(self, code):
"""
Force a country to the current activated translation.
:returns: ``CountryTuple(code, translated_country_name)`` namedtuple
"""
name = self.countries[code]
if code in self.OLD_NAMES:
# Check if there's an older translation available if there's no
# translation for the newest name.
with override(None):
source_name = force_text(name)
name = force_text(name)
if name == source_name:
for old_name in self.OLD_NAMES[code]:
with override(None):
source_old_name = force_text(old_name)
old_name = force_text(old_name)
if old_name != source_old_name:
name = old_name
break
else:
name = force_text(name)
return CountryTuple(code, name) | python | def translate_pair(self, code):
name = self.countries[code]
if code in self.OLD_NAMES:
# Check if there's an older translation available if there's no
# translation for the newest name.
with override(None):
source_name = force_text(name)
name = force_text(name)
if name == source_name:
for old_name in self.OLD_NAMES[code]:
with override(None):
source_old_name = force_text(old_name)
old_name = force_text(old_name)
if old_name != source_old_name:
name = old_name
break
else:
name = force_text(name)
return CountryTuple(code, name) | [
"def",
"translate_pair",
"(",
"self",
",",
"code",
")",
":",
"name",
"=",
"self",
".",
"countries",
"[",
"code",
"]",
"if",
"code",
"in",
"self",
".",
"OLD_NAMES",
":",
"# Check if there's an older translation available if there's no",
"# translation for the newest na... | Force a country to the current activated translation.
:returns: ``CountryTuple(code, translated_country_name)`` namedtuple | [
"Force",
"a",
"country",
"to",
"the",
"current",
"activated",
"translation",
"."
] | 68b0934e8180d47bc15eff2887b6887aaa6e0228 | https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/__init__.py#L137-L160 |
227,496 | SmileyChris/django-countries | django_countries/__init__.py | Countries.alpha2 | def alpha2(self, code):
"""
Return the two letter country code when passed any type of ISO 3166-1
country code.
If no match is found, returns an empty string.
"""
code = force_text(code).upper()
if code.isdigit():
lookup_code = int(code)
def find(alt_codes):
return alt_codes[1] == lookup_code
elif len(code) == 3:
lookup_code = code
def find(alt_codes):
return alt_codes[0] == lookup_code
else:
find = None
if find:
code = None
for alpha2, alt_codes in self.alt_codes.items():
if find(alt_codes):
code = alpha2
break
if code in self.countries:
return code
return "" | python | def alpha2(self, code):
code = force_text(code).upper()
if code.isdigit():
lookup_code = int(code)
def find(alt_codes):
return alt_codes[1] == lookup_code
elif len(code) == 3:
lookup_code = code
def find(alt_codes):
return alt_codes[0] == lookup_code
else:
find = None
if find:
code = None
for alpha2, alt_codes in self.alt_codes.items():
if find(alt_codes):
code = alpha2
break
if code in self.countries:
return code
return "" | [
"def",
"alpha2",
"(",
"self",
",",
"code",
")",
":",
"code",
"=",
"force_text",
"(",
"code",
")",
".",
"upper",
"(",
")",
"if",
"code",
".",
"isdigit",
"(",
")",
":",
"lookup_code",
"=",
"int",
"(",
"code",
")",
"def",
"find",
"(",
"alt_codes",
"... | Return the two letter country code when passed any type of ISO 3166-1
country code.
If no match is found, returns an empty string. | [
"Return",
"the",
"two",
"letter",
"country",
"code",
"when",
"passed",
"any",
"type",
"of",
"ISO",
"3166",
"-",
"1",
"country",
"code",
"."
] | 68b0934e8180d47bc15eff2887b6887aaa6e0228 | https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/__init__.py#L208-L238 |
227,497 | SmileyChris/django-countries | django_countries/__init__.py | Countries.name | def name(self, code):
"""
Return the name of a country, based on the code.
If no match is found, returns an empty string.
"""
code = self.alpha2(code)
if code not in self.countries:
return ""
return self.translate_pair(code)[1] | python | def name(self, code):
code = self.alpha2(code)
if code not in self.countries:
return ""
return self.translate_pair(code)[1] | [
"def",
"name",
"(",
"self",
",",
"code",
")",
":",
"code",
"=",
"self",
".",
"alpha2",
"(",
"code",
")",
"if",
"code",
"not",
"in",
"self",
".",
"countries",
":",
"return",
"\"\"",
"return",
"self",
".",
"translate_pair",
"(",
"code",
")",
"[",
"1"... | Return the name of a country, based on the code.
If no match is found, returns an empty string. | [
"Return",
"the",
"name",
"of",
"a",
"country",
"based",
"on",
"the",
"code",
"."
] | 68b0934e8180d47bc15eff2887b6887aaa6e0228 | https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/__init__.py#L240-L249 |
227,498 | SmileyChris/django-countries | django_countries/__init__.py | Countries.by_name | def by_name(self, country, language="en"):
"""
Fetch a country's ISO3166-1 two letter country code from its name.
An optional language parameter is also available.
Warning: This depends on the quality of the available translations.
If no match is found, returns an empty string.
..warning:: Be cautious about relying on this returning a country code
(especially with any hard-coded string) since the ISO names of
countries may change over time.
"""
with override(language):
for code, name in self:
if name.lower() == country.lower():
return code
if code in self.OLD_NAMES:
for old_name in self.OLD_NAMES[code]:
if old_name.lower() == country.lower():
return code
return "" | python | def by_name(self, country, language="en"):
with override(language):
for code, name in self:
if name.lower() == country.lower():
return code
if code in self.OLD_NAMES:
for old_name in self.OLD_NAMES[code]:
if old_name.lower() == country.lower():
return code
return "" | [
"def",
"by_name",
"(",
"self",
",",
"country",
",",
"language",
"=",
"\"en\"",
")",
":",
"with",
"override",
"(",
"language",
")",
":",
"for",
"code",
",",
"name",
"in",
"self",
":",
"if",
"name",
".",
"lower",
"(",
")",
"==",
"country",
".",
"lowe... | Fetch a country's ISO3166-1 two letter country code from its name.
An optional language parameter is also available.
Warning: This depends on the quality of the available translations.
If no match is found, returns an empty string.
..warning:: Be cautious about relying on this returning a country code
(especially with any hard-coded string) since the ISO names of
countries may change over time. | [
"Fetch",
"a",
"country",
"s",
"ISO3166",
"-",
"1",
"two",
"letter",
"country",
"code",
"from",
"its",
"name",
"."
] | 68b0934e8180d47bc15eff2887b6887aaa6e0228 | https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/__init__.py#L251-L272 |
227,499 | SmileyChris/django-countries | django_countries/__init__.py | Countries.alpha3 | def alpha3(self, code):
"""
Return the ISO 3166-1 three letter country code matching the provided
country code.
If no match is found, returns an empty string.
"""
code = self.alpha2(code)
try:
return self.alt_codes[code][0]
except KeyError:
return "" | python | def alpha3(self, code):
code = self.alpha2(code)
try:
return self.alt_codes[code][0]
except KeyError:
return "" | [
"def",
"alpha3",
"(",
"self",
",",
"code",
")",
":",
"code",
"=",
"self",
".",
"alpha2",
"(",
"code",
")",
"try",
":",
"return",
"self",
".",
"alt_codes",
"[",
"code",
"]",
"[",
"0",
"]",
"except",
"KeyError",
":",
"return",
"\"\""
] | Return the ISO 3166-1 three letter country code matching the provided
country code.
If no match is found, returns an empty string. | [
"Return",
"the",
"ISO",
"3166",
"-",
"1",
"three",
"letter",
"country",
"code",
"matching",
"the",
"provided",
"country",
"code",
"."
] | 68b0934e8180d47bc15eff2887b6887aaa6e0228 | https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/__init__.py#L274-L285 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.