code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
kinds = [
CursorKind.CLASS_DECL,
CursorKind.CLASS_TEMPLATE,
]
inner = [ PredMatcher(is_kind(k)) for k in kinds ]
return allOf(anyOf(*inner), *args) | def cxxRecordDecl(*args) | Matches C++ class declarations.
>>> from glud import *
>>> config = '''
... class W;
... template<typename T> class X {};
... struct Y {};
... union Z {};
... '''
>>> m = cxxRecordDecl()
>>> for c in walk(m, parse_string(config).cursor):
... print(c.spelling)
W
X | 10.202928 | 12.309161 | 0.828889 |
kinds = [
CursorKind.STRUCT_DECL,
CursorKind.UNION_DECL,
CursorKind.CLASS_DECL,
CursorKind.CLASS_TEMPLATE,
]
inner = [ PredMatcher(is_kind(k)) for k in kinds ]
return allOf(anyOf(*inner), *args) | def recordDecl(*args) | Matches class, struct, and union declarations.
>>> from glud import *
>>> config = '''
... class W;
... template<typename T> class X {};
... struct Y {};
... union Z {};
... '''
>>> m = recordDecl()
>>> for c in walk(m, parse_string(config).cursor):
... print(c.spelling)... | 5.809218 | 6.444841 | 0.901375 |
if isinstance(x, bool):
return x
if not x: # None, zero, blank string...
return default
try:
return int(x) != 0
except (TypeError, ValueError):
pass
try:
return float(x) != 0
except (TypeError, ValueError):
pass
if not isinstance(x, s... | def convert_to_bool(x: Any, default: bool = None) -> bool | Transforms its input to a ``bool`` (or returns ``default`` if ``x`` is
falsy but not itself a boolean). Accepts various common string versions. | 2.330612 | 2.290002 | 1.017734 |
try:
return int(x)
except (TypeError, ValueError):
return default | def convert_to_int(x: Any, default: int = None) -> int | Transforms its input into an integer, or returns ``default``. | 4.234102 | 2.908178 | 1.455929 |
for a in attrs:
setattr(obj, a, convert_to_bool(getattr(obj, a), default=default)) | def convert_attrs_to_bool(obj: Any,
attrs: Iterable[str],
default: bool = None) -> None | Applies :func:`convert_to_bool` to the specified attributes of an object,
modifying it in place. | 3.957619 | 2.543186 | 1.556166 |
for a in attrs:
value = getattr(obj, a)
if value is None:
continue
setattr(obj, a, value.upper()) | def convert_attrs_to_uppercase(obj: Any, attrs: Iterable[str]) -> None | Converts the specified attributes of an object to upper case, modifying
the object in place. | 3.146677 | 2.654335 | 1.185486 |
for a in attrs:
value = getattr(obj, a)
if value is None:
continue
setattr(obj, a, value.lower()) | def convert_attrs_to_lowercase(obj: Any, attrs: Iterable[str]) -> None | Converts the specified attributes of an object to lower case, modifying
the object in place. | 3.165682 | 2.683285 | 1.179779 |
for a in attrs:
value = convert_to_int(getattr(obj, a), default=default)
setattr(obj, a, value) | def convert_attrs_to_int(obj: Any,
attrs: Iterable[str],
default: int = None) -> None | Applies :func:`convert_to_int` to the specified attributes of an object,
modifying it in place. | 3.751765 | 2.827194 | 1.327028 |
if len(s) < 3 or not s.startswith("X'") or not s.endswith("'"):
return None
return binascii.unhexlify(s[2:-1]) | def hex_xformat_decode(s: str) -> Optional[bytes] | Reverse :func:`hex_xformat_encode`.
The parameter is a hex-encoded BLOB like
.. code-block:: none
"X'CDE7A24B1A9DBA3148BCB7A0B9DA5BB6A424486C'"
Original purpose and notes:
- SPECIAL HANDLING for BLOBs: a string like ``X'01FF'`` means a hex-encoded
BLOB. Titanium is rubbish at BLOBs, s... | 2.985608 | 3.090513 | 0.966056 |
if len(s) < 4 or not s.startswith("64'") or not s.endswith("'"):
return None
return base64.b64decode(s[3:-1]) | def base64_64format_decode(s: str) -> Optional[bytes] | Reverse :func:`base64_64format_encode`.
Original purpose and notes:
- THIS IS ANOTHER WAY OF DOING BLOBS: base64 encoding, e.g. a string like
``64'cGxlYXN1cmUu'`` is a base-64-encoded BLOB (the ``64'...'`` bit is my
representation).
- regex from http://stackoverflow.com/questions/475074
- ... | 2.702756 | 3.001829 | 0.90037 |
if name not in os.environ and default is None:
message = "The {0} ENVVAR is not set.".format(name)
if required:
raise ImproperlyConfigured(message)
else:
warnings.warn(ConfigurationMissing(message))
return os.environ.get(name, default) | def environ_setting(name, default=None, required=True) | Fetch setting from the environment. The bahavior of the setting if it
is not in environment is as follows:
1. If it is required and the default is None, raise Exception
2. If it is requried and a default exists, return default
3. If it is not required and default is None, return None
... | 3.288938 | 4.242279 | 0.775276 |
config = klass()
for path in klass.CONF_PATHS:
if os.path.exists(path):
with open(path, 'r') as conf:
config.configure(yaml.safe_load(conf))
return config | def load(klass) | Insantiates the configuration by attempting to load the
configuration from YAML files specified by the CONF_PATH module
variable. This should be the main entry point for configuration. | 3.48873 | 2.934839 | 1.188729 |
if not conf: return
if isinstance(conf, Configuration):
conf = dict(conf.options())
for key, value in conf.items():
opt = self.get(key, None)
if isinstance(opt, Configuration):
opt.configure(value)
else:
set... | def configure(self, conf={}) | Allows updating of the configuration via a dictionary of
configuration terms or a configuration object. Generally speaking,
this method is utilized to configure the object from a JSON or
YAML parsing. | 2.89498 | 2.876201 | 1.006529 |
keys = self.__class__.__dict__.copy()
keys.update(self.__dict__)
keys = sorted(keys.keys())
for opt in keys:
val = self.get(opt)
if val is not None:
yield opt, val | def options(self) | Returns an iterable of sorted option names in order to loop
through all the configuration directives specified in the class. | 3.717048 | 2.883797 | 1.288942 |
if include_time:
return date.strftime("%Y-%m-%dT%H:%M")
else:
return date.strftime("%Y-%m-%d") | def formatdt(date: datetime.date, include_time: bool = True) -> str | Formats a ``datetime.date`` to ISO-8601 basic format, to minute accuracy
with no timezone (or, if ``include_time`` is ``False``, omit the time). | 2.439626 | 2.037962 | 1.197091 |
if duration is None:
return None
s = duration.total_seconds()
if units in ['s', 'sec', 'seconds']:
return s
if units in ['m', 'min', 'minutes']:
return s / SECONDS_PER_MINUTE
if units in ['h', 'hr', 'hours']:
return s / SECONDS_PER_HOUR
if units in ['d', 'day... | def convert_duration(duration: datetime.timedelta,
units: str) -> Optional[float] | Convert a ``datetime.timedelta`` object -- a duration -- into other
units. Possible units:
``s``, ``sec``, ``seconds``
``m``, ``min``, ``minutes``
``h``, ``hr``, ``hours``
``d``, ``days``
``w``, ``weeks``
``y``, ``years`` | 1.536334 | 1.426446 | 1.077036 |
return not(self.end <= other.start or self.start >= other.end) | def overlaps(self, other: "Interval") -> bool | Does this interval overlap the other?
Overlap:
.. code-block:: none
S--------S S---S S---S
O---O O---O O---O
Simpler method of testing is for non-overlap!
.. code-block:: none
S---S S---S
... | 4.977365 | 4.800344 | 1.036877 |
return not(self.end < other.start or self.start > other.end) | def contiguous(self, other: "Interval") -> bool | Does this interval overlap or touch the other? | 4.663493 | 2.828808 | 1.648571 |
if inclusive:
return self.start <= time <= self.end
else:
return self.start < time < self.end | def contains(self, time: datetime.datetime,
inclusive: bool = True) -> bool | Does the interval contain a momentary time?
Args:
time: the ``datetime.datetime`` to check
inclusive: use inclusive rather than exclusive range checks? | 2.873145 | 2.975059 | 0.965744 |
if not other:
return False
if inclusive:
return self.start >= other.start and self.end <= other.end
else:
return self.start > other.start and self.end < other.end | def within(self, other: "Interval", inclusive: bool = True) -> bool | Is this interval contained within the other?
Args:
other: the :class:`Interval` to check
inclusive: use inclusive rather than exclusive range checks? | 2.261852 | 2.254015 | 1.003477 |
if not self.contiguous(other):
return None
return Interval(
max(self.start, other.start),
min(self.end, other.end)
) | def intersection(self, other: "Interval") -> Optional["Interval"] | Returns an :class:`Interval` representing the intersection of this and
the ``other``, or ``None`` if they don't overlap. | 2.752504 | 3.047461 | 0.903212 |
if not isinstance(times, list):
# Single time
time = times
if not self.contains(time):
return []
return [
Interval(self.start, time),
Interval(time, self.end)
]
else:
# Multip... | def cut(self, times: Union[datetime.datetime,
List[datetime.datetime]]) -> List["Interval"] | Returns a list of intervals produced by using times (a list of
``datetime.datetime`` objects, or a single such object) as a set of
knives to slice this interval. | 2.120459 | 2.126045 | 0.997372 |
start = datetime.datetime.combine(date, datetime.time())
return Interval(
start,
start + datetime.timedelta(days=1)
) | def wholeday(date: datetime.date) -> "Interval" | Returns an :class:`Interval` covering the date given (midnight at the
start of that day to midnight at the start of the next day). | 2.964755 | 3.132308 | 0.946508 |
return Interval(
datetime.datetime.combine(date, daybreak),
datetime.datetime.combine(date, nightfall),
) | def daytime(date: datetime.date,
daybreak: datetime.time = datetime.time(NORMAL_DAY_START_H),
nightfall: datetime.time = datetime.time(NORMAL_DAY_END_H)) \
-> "Interval" | Returns an :class:`Interval` representing daytime on the date given. | 2.65958 | 2.755317 | 0.965254 |
if enddate < startdate:
return None
if enddate == startdate and include_end:
return None
start_dt = datetime.datetime.combine(startdate, datetime.time())
end_dt = datetime.datetime.combine(enddate, datetime.time())
if include_end:
end_... | def dayspan(startdate: datetime.date,
enddate: datetime.date,
include_end: bool = True) -> Optional["Interval"] | Returns an :class:`Interval` representing the date range given, from
midnight at the start of the first day to midnight at the end of the
last (i.e. at the start of the next day after the last), or if
include_end is False, 24h before that.
If the parameters are invalid, returns ``None``... | 1.856277 | 1.876584 | 0.989179 |
return self.intersection(Interval.wholeday(date)) | def component_on_date(self, date: datetime.date) -> Optional["Interval"] | Returns the part of this interval that falls on the date given, or
``None`` if the interval doesn't have any part during that date. | 20.817833 | 22.254717 | 0.935435 |
daytotal = datetime.timedelta()
nighttotal = datetime.timedelta()
startdate = self.start.date()
enddate = self.end.date()
ndays = (enddate - startdate).days + 1
for i in range(ndays):
date = startdate + datetime.timedelta(days=i)
component... | def day_night_duration(
self,
daybreak: datetime.time = datetime.time(NORMAL_DAY_START_H),
nightfall: datetime.time = datetime.time(NORMAL_DAY_END_H)) \
-> Tuple[datetime.timedelta, datetime.timedelta] | Returns a ``(day, night)`` tuple of ``datetime.timedelta`` objects
giving the duration of this interval that falls into day and night
respectively. | 2.894039 | 2.840617 | 1.018807 |
if weekdays_only and weekends_only:
raise ValueError("Can't have weekdays_only and weekends_only")
ooh = datetime.timedelta() # ooh = out of (normal) hours
startdate = self.start.date()
enddate = self.end.date()
ndays = (enddate - startdate).days + 1
... | def duration_outside_nwh(
self,
starttime: datetime.time = datetime.time(NORMAL_DAY_START_H),
endtime: datetime.time = datetime.time(NORMAL_DAY_END_H),
weekdays_only: bool = False,
weekends_only: bool = False) -> datetime.timedelta | Returns a duration (a ``datetime.timedelta`` object) representing the
number of hours outside normal working hours.
This is not simply a subset of :meth:`day_night_duration`, because
weekends are treated differently (they are always out of hours).
The options allow the calculation of c... | 3.177386 | 3.138297 | 1.012456 |
startdate = self.start.date()
enddate = self.end.date()
ndays = (enddate - startdate).days + 1
in_weekend = False
n_weekends = 0
for i in range(ndays):
date = startdate + datetime.timedelta(days=i)
if not in_weekend and is_weekend(date):
... | def n_weekends(self) -> int | Returns the number of weekends that this interval covers. Includes
partial weekends. | 1.865841 | 1.81838 | 1.0261 |
startdate = self.start.date()
enddate = self.end.date()
ndays = (enddate - startdate).days + 1
saturdays = set()
for i in range(ndays):
date = startdate + datetime.timedelta(days=i)
if is_saturday(date):
saturdays.add(date)
... | def saturdays_of_weekends(self) -> Set[datetime.date] | Returns the dates of all Saturdays that are part of weekends that this
interval covers (each Saturday representing a unique identifier for
that weekend). The Saturday itself isn't necessarily the part of the
weekend that the interval covers! | 1.695061 | 1.797593 | 0.942962 |
if no_overlap is None:
no_overlap = self.no_overlap
if no_contiguous is None:
no_contiguous = self.no_contiguous
return IntervalList(self.intervals, no_overlap=no_overlap,
no_contiguous=no_contiguous) | def copy(self, no_overlap: bool = None,
no_contiguous: bool = None) -> "IntervalList" | Makes and returns a copy of the :class:`IntervalList`. The
``no_overlap``/``no_contiguous`` parameters can be changed.
Args:
no_overlap: merge intervals that overlap (now and on subsequent
addition)?
no_contiguous: if ``no_overlap`` is set, merge intervals that a... | 1.650578 | 2.001097 | 0.824836 |
if interval is None:
return
if not isinstance(interval, Interval):
raise TypeError(
"Attempt to insert non-Interval into IntervalList")
self.intervals.append(interval)
self._tidy() | def add(self, interval: Interval) -> None | Adds an interval to the list. If ``self.no_overlap`` is True, as is the
default, it will merge any overlapping intervals thus created. | 4.851703 | 4.200784 | 1.154952 |
if self.no_overlap:
self.remove_overlap(self.no_contiguous) # will sort
else:
self._sort() | def _tidy(self) -> None | Removes overlaps, etc., and sorts. | 17.433325 | 9.079472 | 1.920081 |
# Returns
for i in range(len(self.intervals)):
for j in range(i + 1, len(self.intervals)):
first = self.intervals[i]
second = self.intervals[j]
if also_remove_contiguous:
test = first.contiguous(second)
... | def _remove_overlap_sub(self, also_remove_contiguous: bool) -> bool | Called by :meth:`remove_overlap`. Removes the first overlap found.
Args:
also_remove_contiguous: treat contiguous (as well as overlapping)
intervals as worthy of merging?
Returns:
bool: ``True`` if an overlap was removed; ``False`` otherwise | 2.792324 | 2.69214 | 1.037214 |
overlap = True
while overlap:
overlap = self._remove_overlap_sub(also_remove_contiguous)
self._sort() | def remove_overlap(self, also_remove_contiguous: bool = False) -> None | Merges any overlapping intervals.
Args:
also_remove_contiguous: treat contiguous (as well as overlapping)
intervals as worthy of merging? | 6.802438 | 10.306265 | 0.660029 |
for i in range(len(self.intervals)):
for j in range(i + 1, len(self.intervals)):
first = self.intervals[i]
second = self.intervals[j]
if test_overlap:
test = first.overlaps(second)
else:
... | def _any_overlap_or_contiguous(self, test_overlap: bool) -> bool | Do any of the intervals overlap?
Args:
test_overlap: if ``True``, test for overlapping intervals; if
``False``, test for contiguous intervals. | 2.05795 | 1.992867 | 1.032658 |
if not self.intervals:
return None
return self.intervals[0].start | def start_datetime(self) -> Optional[datetime.datetime] | Returns the start date of the set of intervals, or ``None`` if empty. | 5.307113 | 3.013339 | 1.761207 |
if not self.intervals:
return None
return max([x.end for x in self.intervals]) | def end_datetime(self) -> Optional[datetime.datetime] | Returns the end date of the set of intervals, or ``None`` if empty. | 4.901557 | 3.106451 | 1.577864 |
if not self.intervals:
return None
return self.start_datetime().date() | def start_date(self) -> Optional[datetime.date] | Returns the start date of the set of intervals, or ``None`` if empty. | 8.20575 | 5.485109 | 1.496005 |
if not self.intervals:
return None
return self.end_datetime().date() | def end_date(self) -> Optional[datetime.date] | Returns the end date of the set of intervals, or ``None`` if empty. | 8.150902 | 5.302014 | 1.537322 |
if not self.intervals:
return None
return Interval(self.start_datetime(), self.end_datetime()) | def extent(self) -> Optional[Interval] | Returns an :class:`Interval` running from the earliest start of an
interval in this list to the latest end. Returns ``None`` if we are
empty. | 5.586315 | 4.787298 | 1.166903 |
total = datetime.timedelta()
for interval in self.intervals:
total += interval.duration()
return total | def total_duration(self) -> datetime.timedelta | Returns a ``datetime.timedelta`` object with the total sum of
durations. If there is overlap, time will be double-counted, so beware! | 4.594897 | 3.929499 | 1.169334 |
overlaps = IntervalList()
for i in range(len(self.intervals)):
for j in range(i + 1, len(self.intervals)):
first = self.intervals[i]
second = self.intervals[j]
ol = first.intersection(second)
if ol is not None:
... | def get_overlaps(self) -> "IntervalList" | Returns an :class:`IntervalList` containing intervals representing
periods of overlap between intervals in this one. | 1.98795 | 1.984752 | 1.001611 |
return [x.duration() for x in self.intervals] | def durations(self) -> List[datetime.timedelta] | Returns a list of ``datetime.timedelta`` objects representing the
durations of each interval in our list. | 7.607976 | 7.116992 | 1.068988 |
if not self.intervals:
return None
return max(self.durations()) | def longest_duration(self) -> Optional[datetime.timedelta] | Returns the duration of the longest interval, or None if none. | 6.902746 | 4.491586 | 1.536817 |
longest_duration = self.longest_duration()
for i in self.intervals:
if i.duration() == longest_duration:
return i
return None | def longest_interval(self) -> Optional[Interval] | Returns the longest interval, or ``None`` if none. | 3.66695 | 3.50341 | 1.04668 |
for i in self.intervals:
if i.start == start:
return i
return None | def first_interval_starting(self, start: datetime.datetime) -> \
Optional[Interval] | Returns our first interval that starts with the ``start`` parameter, or
``None``. | 3.048157 | 3.217925 | 0.947243 |
for i in self.intervals:
if i.end == end:
return i
return None | def first_interval_ending(self, end: datetime.datetime) \
-> Optional[Interval] | Returns our first interval that ends with the ``end`` parameter, or
``None``. | 3.465732 | 3.420538 | 1.013213 |
if len(self.intervals) < 2:
return IntervalList(None)
gaps = []
for i in range(len(self.intervals) - 1):
gap = Interval(
self.intervals[i].end,
self.intervals[i + 1].start
)
gaps.append(gap)
return I... | def gaps(self) -> "IntervalList" | Returns all the gaps between intervals, as an :class:`IntervalList`. | 1.952334 | 1.844341 | 1.058553 |
if flexibility not in [0, 1, 2]:
raise ValueError("subset: bad flexibility value")
permitted = []
for i in self.intervals:
if flexibility == 0:
ok = i.start > interval.start and i.end < interval.end
elif flexibility == 1:
... | def subset(self, interval: Interval,
flexibility: int = 2) -> "IntervalList" | Returns an IntervalList that's a subset of this one, only containing
intervals that meet the "interval" parameter criterion. What "meet"
means is defined by the ``flexibility`` parameter.
``flexibility == 0``: permits only wholly contained intervals:
.. code-block:: none
i... | 2.23339 | 2.289581 | 0.975458 |
return self.gaps().subset(interval, flexibility) | def gap_subset(self, interval: Interval,
flexibility: int = 2) -> "IntervalList" | Returns an IntervalList that's a subset of this one, only containing
*gaps* between intervals that meet the interval criterion.
See :meth:`subset` for the meaning of parameters. | 10.063817 | 13.787057 | 0.729947 |
saturdays = set()
for interval in self.intervals:
saturdays.update(interval.saturdays_of_weekends())
return len(saturdays) | def n_weekends(self) -> int | Returns the number of weekends that the intervals collectively touch
(where "touching a weekend" means "including time on a Saturday or a
Sunday"). | 5.338993 | 3.823122 | 1.396501 |
total = datetime.timedelta()
for interval in self.intervals:
total += interval.duration_outside_nwh(starttime, endtime)
return total | def duration_outside_nwh(
self,
starttime: datetime.time = datetime.time(NORMAL_DAY_START_H),
endtime: datetime.time = datetime.time(NORMAL_DAY_END_H)) \
-> datetime.timedelta | Returns the total duration outside normal working hours, i.e.
evenings/nights, weekends (and Bank Holidays). | 3.497292 | 3.14495 | 1.112034 |
if len(self.intervals) == 0:
return None
startdate = self.start_date()
enddate = self.end_date()
seq = ''
ndays = (enddate - startdate).days + 1
for i in range(ndays):
date = startdate + datetime.timedelta(days=i)
wholeday = In... | def max_consecutive_days(self) -> Optional[Tuple[int, Interval]] | The length of the longest sequence of days in which all days include
an interval.
Returns:
tuple:
``(longest_length, longest_interval)`` where
``longest_interval`` is a :class:`Interval` containing the
start and end date of the longest span -... | 2.635743 | 2.392472 | 1.101682 |
requiredgaps = list(requiredgaps) # make a copy
interval = Interval.dayspan(startdate, enddate, include_end=True)
# log.debug(">>> _sufficient_gaps")
gaps = self.gap_subset(interval, flexibility)
gapdurations = gaps.durations()
gaplist = gaps.list()
gapd... | def _sufficient_gaps(self,
startdate: datetime.date,
enddate: datetime.date,
requiredgaps: List[datetime.timedelta],
flexibility: int) -> Tuple[bool, Optional[Interval]] | Are there sufficient gaps (specified by ``requiredgaps``) in the date
range specified? This is a worker function for :meth:`sufficient_gaps`. | 3.045149 | 3.075683 | 0.990072 |
if len(self.intervals) < 2:
return False, None
startdate = self.start_date()
enddate = self.end_date()
ndays = (enddate - startdate).days + 1
if ndays <= every_n_days:
# Our interval is too short, or just right
return self._sufficient_... | def sufficient_gaps(self,
every_n_days: int,
requiredgaps: List[datetime.timedelta],
flexibility: int = 2) \
-> Tuple[bool, Optional[Interval]] | Are gaps present sufficiently often?
For example:
.. code-block:: python
every_n_days=21
requiredgaps=[
datetime.timedelta(hours=62),
datetime.timedelta(hours=48),
]
... means "is there at least one 62-hour gap and one (separ... | 2.42441 | 2.613262 | 0.927733 |
assert self.no_overlap, self._ONLY_FOR_NO_INTERVAL
cumulative = datetime.timedelta()
for interval in self.intervals:
if interval.start >= when:
break
elif interval.end <= when:
# complete interval precedes "when"
cu... | def cumulative_time_to(self,
when: datetime.datetime) -> datetime.timedelta | Returns the cumulative time contained in our intervals up to the
specified time point. | 5.860799 | 5.234229 | 1.119706 |
gaps = self.gaps()
return gaps.cumulative_time_to(when) | def cumulative_gaps_to(self,
when: datetime.datetime) -> datetime.timedelta | Return the cumulative time within our gaps, up to ``when``. | 7.683756 | 4.037481 | 1.903106 |
if self.is_empty():
return None
end_time = self.end_datetime()
if when <= end_time:
return datetime.timedelta()
else:
return when - end_time | def time_afterwards_preceding(
self, when: datetime.datetime) -> Optional[datetime.timedelta] | Returns the time after our last interval, but before ``when``.
If ``self`` is an empty list, returns ``None``. | 3.572689 | 3.091784 | 1.155543 |
assert self.no_overlap, (
"Only implemented for IntervalList objects with no_overlap == True"
)
no_time = datetime.timedelta()
earliest_interval_start = self.start_datetime()
# Easy special cases
if when <= start:
return no_time, no_time,... | def cumulative_before_during_after(self,
start: datetime.datetime,
when: datetime.datetime) -> \
Tuple[datetime.timedelta,
datetime.timedelta,
datetime.timedelta] | For a given time, ``when``, returns the cumulative time
- after ``start`` but before ``self`` begins, prior to ``when``;
- after ``start`` and during intervals represented by ``self``, prior
to ``when``;
- after ``start`` and after at least one interval represented by
... | 4.275549 | 4.5907 | 0.93135 |
return (
"Parameter(name={name}, annotation={annotation}, kind={kind}, "
"default={default}".format(
name=param.name, annotation=param.annotation, kind=param.kind,
default=param.default)
) | def repr_parameter(param: inspect.Parameter) -> str | Provides a ``repr``-style representation of a function parameter. | 2.828591 | 2.682588 | 1.054426 |
# noqa
# See hidden attributes with dir(fn)
# noinspection PyUnresolvedReferences
return "{module}:{name}{extra}".format(
module=fn.__module__,
name=fn.__qualname__, # __qualname__ includes class name, if present
extra="|{}".format(namespace) if namespace is not None else "",
... | def get_namespace(fn: Callable, namespace: Optional[str]) -> str | Returns a representation of a function's name (perhaps within a namespace),
like
.. code-block:: none
mymodule:MyClass.myclassfunc # with no namespace
mymodule:MyClass.myclassfunc|somenamespace # with a namespace
Args:
fn: a function
namespace: an optional namespace, whi... | 6.534224 | 5.560191 | 1.17518 |
namespace = get_namespace(fn, namespace)
sig = inspect.signature(fn)
argnames = [p.name for p in sig.parameters.values()
if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD]
has_self = bool(argnames and argnames[0] in ('self', 'cls'))
def generate_key(*args: Any, **kw: Any) ... | def fkg_allowing_type_hints(
namespace: Optional[str],
fn: Callable,
to_str: Callable[[Any], str] = repr) -> Callable[[Any], str] | Replacement for :func:`dogpile.cache.util.function_key_generator` that
handles type-hinted functions like
.. code-block:: python
def testfunc(param: str) -> str:
return param + "hello"
... at which :func:`inspect.getargspec` balks; plus
:func:`inspect.getargspec` is deprecated in ... | 4.13028 | 4.039226 | 1.022542 |
namespace = get_namespace(fn, namespace)
sig = inspect.signature(fn)
parameters = list(sig.parameters.values()) # convert from odict_values
argnames = [p.name for p in parameters
if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD]
has_self = bool(argnames and argnames[0] in... | def kw_fkg_allowing_type_hints(
namespace: Optional[str],
fn: Callable,
to_str: Callable[[Any], str] = repr) -> Callable[[Any], str] | As for :func:`fkg_allowing_type_hints`, but allowing keyword arguments.
For ``kwargs`` passed in, we will build a ``dict`` of all argname (key) to
argvalue (values) pairs, including default args from the argspec, and then
alphabetize the list before generating the key.
NOTE ALSO that once we have keyw... | 3.724588 | 3.591272 | 1.037122 |
cmd = flatten([gnupg_bin(), "--version"])
output = stderr_output(cmd)
output = output \
.split('\n')[0] \
.split(" ")[2] \
.split('.')
return tuple([int(x) for x in output]) | def gpg_version() | Returns the GPG version | 4.918376 | 4.893013 | 1.005184 |
if is_py3() and hasattr(a_string, 'decode'):
try:
return a_string.decode('utf-8')
except UnicodeDecodeError:
return a_string
return a_string | def polite_string(a_string) | Returns a "proper" string that should work in both Py3/Py2 | 2.766032 | 2.398979 | 1.153004 |
my_type = str(type(obj))
if is_py3():
is_str = my_type.find('bytes') < 0 and my_type.find('str') < 0
return is_str
return my_type.find('str') < 0 and \
my_type.find('unicode') < 0 | def not_a_string(obj) | It's probably not a string, in the sense
that Python2/3 get confused about these things | 3.316648 | 3.324237 | 0.997717 |
remainder = iter(iterable)
while True:
first = next(remainder) # pylint: disable=R1708
# Python 2/3 compat
is_iter = isinstance(first, collections.Iterable)
try:
basestring
except NameError:
basestring = str # pylint: disable=W0622
... | def actually_flatten(iterable) | Flatten iterables
This is super ugly. There must be a cleaner py2/3 way
of handling this. | 4.362101 | 4.295639 | 1.015472 |
cmd = []
pass_file = None
if not passphrase and 'CRYPTORITO_PASSPHRASE_FILE' in os.environ:
pass_file = os.environ['CRYPTORITO_PASSPHRASE_FILE']
if not os.path.isfile(pass_file):
raise CryptoritoError('CRYPTORITO_PASSPHRASE_FILE is invalid')
elif passphrase:
tmpd... | def passphrase_file(passphrase=None) | Read passphrase from a file. This should only ever be
used by our built in integration tests. At this time,
during normal operation, only pinentry is supported for
entry of passwords. | 2.902765 | 2.947904 | 0.984688 |
if 'GNUPGHOME' in os.environ:
gnupghome = os.environ['GNUPGHOME']
if not os.path.isdir(gnupghome):
raise CryptoritoError("Invalid GNUPGHOME directory")
return ["--homedir", gnupghome]
else:
return [] | def gnupg_home() | Returns appropriate arguments if GNUPGHOME is set | 3.290441 | 2.74557 | 1.198454 |
if 'public_keys' in kb_obj and \
'pgp_public_keys' in kb_obj['public_keys']:
for key in kb_obj['public_keys']['pgp_public_keys']:
keyprint = fingerprint_from_var(key).lower()
fingerprint = fingerprint.lower()
if fingerprint == keyprint or \
keyp... | def fingerprint_from_keybase(fingerprint, kb_obj) | Extracts a key matching a specific fingerprint from a
Keybase API response | 3.213305 | 3.632378 | 0.884628 |
url = keybase_lookup_url(username)
resp = requests.get(url)
if resp.status_code == 200:
j_resp = json.loads(polite_string(resp.content))
if 'them' in j_resp and len(j_resp['them']) == 1:
kb_obj = j_resp['them'][0]
if fingerprint:
return fingerprin... | def key_from_keybase(username, fingerprint=None) | Look up a public key from a username | 3.122844 | 3.178927 | 0.982358 |
if len(fingerprint) > 8:
fingerprint = fingerprint[-8:]
fingerprint = fingerprint.upper()
cmd = flatten([gnupg_bin(), gnupg_home(), "--list-public-keys"])
lines = stderr_output(cmd).split('\n')
return len([key for key in lines if key.find(fingerprint) > -1]) == 1 | def has_gpg_key(fingerprint) | Checks to see if we have this gpg fingerprint | 5.083167 | 5.087616 | 0.999125 |
vsn = gpg_version()
cmd = flatten([gnupg_bin(), gnupg_home()])
if vsn[0] >= 2 and vsn[1] < 1:
cmd.append("--with-fingerprint")
output = polite_string(stderr_with_input(cmd, var)).split('\n')
if not output[0].startswith('pub'):
raise CryptoritoError('probably an invalid gpg key'... | def fingerprint_from_var(var) | Extract a fingerprint from a GPG public key | 6.333416 | 5.97435 | 1.060101 |
cmd = flatten([gnupg_bin(), gnupg_home(), filename])
outp = stderr_output(cmd).split('\n')
if not outp[0].startswith('pub'):
raise CryptoritoError('probably an invalid gpg key')
return outp[1].strip() | def fingerprint_from_file(filename) | Extract a fingerprint from a GPG public key file | 11.104274 | 11.36884 | 0.976729 |
gpg_stderr = None
handle = None
if LOGGER.getEffectiveLevel() > logging.DEBUG:
handle = open(os.devnull, 'wb')
gpg_stderr = handle
return handle, gpg_stderr | def stderr_handle() | Generate debug-level appropriate stderr context for
executing things through subprocess. Normally stderr gets
sent to dev/null but when debugging it is sent to stdout. | 4.81106 | 4.551575 | 1.05701 |
handle, gpg_stderr = stderr_handle()
try:
output = subprocess.check_output(cmd, stderr=gpg_stderr) # nosec
if handle:
handle.close()
return str(polite_string(output))
except subprocess.CalledProcessError as exception:
LOGGER.debug("GPG Command %s", ' '.joi... | def stderr_output(cmd) | Wraps the execution of check_output in a way that
ignores stderr when not in debug mode | 5.80931 | 5.934482 | 0.978908 |
handle, gpg_stderr = stderr_handle()
LOGGER.debug("GPG command %s", ' '.join(cmd))
try:
gpg_proc = subprocess.Popen(cmd, # nosec
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=gpg... | def stderr_with_input(cmd, stdin) | Runs a command, passing something in stdin, and returning
whatever came out from stdout | 5.181735 | 5.452692 | 0.950308 |
if not key:
raise CryptoritoError('Invalid GPG Key')
key_fd, key_filename = mkstemp("cryptorito-gpg-import")
key_handle = os.fdopen(key_fd, 'w')
key_handle.write(polite_string(key))
key_handle.close()
cmd = flatten([gnupg_bin(), gnupg_home(), "--import", key_filename])
output ... | def import_gpg_key(key) | Imports a GPG key | 5.595818 | 5.789055 | 0.96662 |
cmd = flatten([gnupg_bin(), gnupg_verbose(), gnupg_home(),
"--export", key])
handle, gpg_stderr = stderr_handle()
try:
gpg_proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, # nosec
stderr=gpg_stderr)
output, _err = gpg_proc.comm... | def export_gpg_key(key) | Exports a GPG key and returns it | 5.422668 | 5.423839 | 0.999784 |
cmd = flatten([gnupg_bin(), "--armor", "--output", dest, gnupg_verbose(),
gnupg_home(), recipients_args(keys),
"--encrypt", source])
stderr_output(cmd)
return True | def encrypt(source, dest, keys) | Encrypts a file using the given keys | 15.371045 | 16.716671 | 0.919504 |
cmd = flatten([gnupg_bin(), "--armor", "--encrypt", gnupg_verbose(),
recipients_args(keys)])
output = stderr_with_input(cmd, source)
return output | def encrypt_var(source, keys) | Attempts to encrypt a variable | 18.943617 | 20.142979 | 0.940458 |
LOGGER.debug("GPG Command %s", ' '.join([str(x) for x in exception.cmd]))
LOGGER.debug("GPG Output %s", exception.output)
raise CryptoritoError(message) | def gpg_error(exception, message) | Handles the output of subprocess errors
in a way that is compatible with the log level | 5.507025 | 5.989295 | 0.919478 |
cmd = [gnupg_bin(), "--decrypt", gnupg_home(), gnupg_verbose(),
passphrase_file(passphrase)]
return stderr_with_input(flatten(cmd), source) | def decrypt_var(source, passphrase=None) | Attempts to decrypt a variable | 17.533175 | 18.810242 | 0.932108 |
if not os.path.exists(source):
raise CryptoritoError("Encrypted file %s not found" % source)
cmd = [gnupg_bin(), gnupg_verbose(), "--decrypt", gnupg_home(),
passphrase_file(passphrase)]
if dest:
cmd.append(["--output", dest])
cmd.append([source])
stderr_output(flat... | def decrypt(source, dest=None, passphrase=None) | Attempts to decrypt a file | 7.214074 | 7.518203 | 0.959548 |
return (not re.match('^[0-9]+$', string)) and \
(len(string) % 4 == 0) and \
re.match('^[A-Za-z0-9+/]+[=]{0,2}$', string) | def is_base64(string) | Determines whether or not a string is likely to
be base64 encoded binary nonsense | 2.397126 | 2.461088 | 0.97401 |
if is_py3():
try:
some_bits = bytes(thing, 'utf-8')
except TypeError:
some_bits = thing
return polite_string(b64encode(some_bits).decode('utf-8'))
return polite_string(b64encode(thing)) | def portable_b64encode(thing) | Wrap b64encode for Python 2 & 3 | 3.920632 | 3.542523 | 1.106734 |
# Uses eigenvectors of the covariance matrix
e = fit.hyperbolic_axes #singular_values
#e = sampling_covariance(fit) # not sure
e = e[2]**2/e
kappa = (e-e[2])[:-1]
kappa /= kappa[-1]
F = N.sqrt(N.pi)*confluent_hypergeometric_function(*kappa)
ax = fit.axes
Z = 1/e
M = ax
... | def bingham_pdf(fit) | From the *Encyclopedia of Paleomagnetism*
From Onstott, 1980:
Vector resultant: R is analogous to eigenvectors
of T.
Eigenvalues are analogous to |R|/N. | 9.437323 | 9.647634 | 0.978201 |
if os.path.isfile(filename):
log.info("No need to download, already have: {}", filename)
return
if mkdir:
directory, basename = os.path.split(os.path.abspath(filename))
mkdir_p(directory)
download(url=url,
filename=filename,
skip_cert_verify=ski... | def download_if_not_exists(url: str, filename: str,
skip_cert_verify: bool = True,
mkdir: bool = True) -> None | Downloads a URL to a file, unless the file already exists. | 3.326389 | 3.029023 | 1.098172 |
run_func = run_func or subprocess.check_call
clone_options = clone_options or [] # type: List[str]
if os.path.isdir(directory):
log.info("Not re-cloning {} Git repository: using existing source "
"in {}".format(prettyname, directory))
return False
log.info("Fetchin... | def git_clone(prettyname: str, url: str, directory: str,
branch: str = None,
commit: str = None,
clone_options: List[str] = None,
run_func: Callable[[List[str]], Any] = None) -> bool | Fetches a Git repository, unless we have it already.
Args:
prettyname: name to display to user
url: URL
directory: destination directory
branch: repository branch
commit: repository commit tag
clone_options: additional options to pass to ``git clone``
run_fun... | 3.599316 | 3.82543 | 0.940892 |
if skip_if_dir_exists and os.path.isdir(directory):
log.info("Skipping extraction of {} as directory {} exists",
tarfile, directory)
return
log.info("Extracting {} -> {}", tarfile, directory)
require_executable(TAR)
mkdir_p(directory)
args = [TAR, "-x"] # -x: e... | def untar_to_directory(tarfile: str,
directory: str,
verbose: bool = False,
gzipped: bool = False,
skip_if_dir_exists: bool = True,
run_func: Callable[[List[str]], Any] = None,
chdir... | Unpacks a TAR file into a specified directory.
Args:
tarfile: filename of the ``.tar`` file
directory: destination directory
verbose: be verbose?
gzipped: is the ``.tar`` also gzipped, e.g. a ``.tar.gz`` file?
skip_if_dir_exists: don't do anything if the destrination directo... | 3.363637 | 3.333151 | 1.009147 |
windows = platform.system() == "Windows"
cmd = "set" if windows else "export"
return (
"\n".join(
"{cmd} {k}={v}".format(
cmd=cmd,
k=k,
v=env[k] if windows else subprocess.list2cmdline([env[k]])
) for k in sorted(env.keys()... | def make_copy_paste_env(env: Dict[str, str]) -> str | Convert an environment into a set of commands that can be copied/pasted, on
the build platform, to recreate that environment. | 2.895584 | 2.653091 | 1.0914 |
cwd = os.getcwd()
# log.debug("External command Python form: {}", args)
copy_paste_cmd = subprocess.list2cmdline(args)
csep = "=" * 79
esep = "-" * 79
effective_env = env or os.environ
if debug_show_env:
log.debug(
"Environment for the command that follows:\n"
... | def run(args: List[str],
env: Dict[str, str] = None,
capture_stdout: bool = False,
echo_stdout: bool = True,
capture_stderr: bool = False,
echo_stderr: bool = True,
debug_show_env: bool = True,
encoding: str = sys.getdefaultencoding(),
allow_failure: bool ... | Runs an external process, announcing it.
Optionally, retrieves its ``stdout`` and/or ``stderr`` output (if not
retrieved, the output will be visible to the user).
Args:
args: list of command-line arguments (the first being the executable)
env: operating system environment to use (if ``Non... | 2.656808 | 2.614232 | 1.016286 |
stdout, _ = run(args, env=env, capture_stdout=True,
echo_stdout=False, encoding=encoding)
log.debug(stdout)
return stdout | def fetch(args: List[str], env: Dict[str, str] = None,
encoding: str = sys.getdefaultencoding()) -> str | Run a command and returns its stdout.
Args:
args: the command-line arguments
env: the operating system environment to use
encoding: the encoding to use for ``stdout``
Returns:
the command's ``stdout`` output | 5.844239 | 7.308296 | 0.799672 |
meta = MetaData(bind=engine)
writeline_nl(fileobj, sql_comment('Database info: {}'.format(meta))) | def dump_connection_info(engine: Engine, fileobj: TextIO = sys.stdout) -> None | Dumps some connection info, as an SQL comment. Obscures passwords.
Args:
engine: the SQLAlchemy :class:`Engine` to dump metadata information
from
fileobj: the file-like object (default ``sys.stdout``) to write
information to | 21.912977 | 21.613802 | 1.013842 |
# http://docs.sqlalchemy.org/en/rel_0_8/faq.html#how-can-i-get-the-create-table-drop-table-output-as-a-string # noqa
# http://stackoverflow.com/questions/870925/how-to-generate-a-file-with-ddl-in-the-engines-sql-dialect-in-sqlalchemy # noqa
# https://github.com/plq/scripts/blob/master/pg_dump.py
... | def dump_ddl(metadata: MetaData,
dialect_name: str,
fileobj: TextIO = sys.stdout,
checkfirst: bool = True) -> None | Sends schema-creating DDL from the metadata to the dump engine.
This makes ``CREATE TABLE`` statements.
Args:
metadata: SQLAlchemy :class:`MetaData`
dialect_name: string name of SQL dialect to generate DDL in
fileobj: file-like object to send DDL to
checkfirst: if ``True``, use ... | 4.728775 | 4.755869 | 0.994303 |
# noqa
# noinspection PyPep8Naming
Base = declarative_base()
class GenericMapper(Base):
__table__ = table
# noinspection PyTypeChecker
return GenericMapper | def quick_mapper(table: Table) -> Type[DeclarativeMeta] | Makes a new SQLAlchemy mapper for an existing table.
See
http://www.tylerlesmann.com/2009/apr/27/copying-databases-across-platforms-sqlalchemy/
Args:
table: SQLAlchemy :class:`Table` object
Returns:
a :class:`DeclarativeMeta` class | 3.563253 | 5.557616 | 0.641148 |
# noqa
# log.debug("statement: {!r}", statement)
# log.debug("statement.bind: {!r}", statement.bind)
if isinstance(statement, Query):
if bind is None:
bind = statement.session.get_bind(statement._mapper_zero_or_none())
statement = statement.statement
elif bind is None:
... | def get_literal_query(statement: Union[Query, Executable],
bind: Connectable = None) -> str | Takes an SQLAlchemy statement and produces a literal SQL version, with
values filled in.
As per
http://stackoverflow.com/questions/5631078/sqlalchemy-print-the-actual-query
Notes:
- for debugging purposes *only*
- insecure; you should always separate queries from their values
- ple... | 2.443507 | 2.461649 | 0.99263 |
# http://stackoverflow.com/questions/5631078/sqlalchemy-print-the-actual-query # noqa
# http://docs.sqlalchemy.org/en/latest/faq/sqlexpressions.html
# http://www.tylerlesmann.com/2009/apr/27/copying-databases-across-platforms-sqlalchemy/ # noqa
# https://github.com/plq/scripts/blob/master/pg_dump... | def dump_table_as_insert_sql(engine: Engine,
table_name: str,
fileobj: TextIO,
wheredict: Dict[str, Any] = None,
include_ddl: bool = False,
multirow: bool = False) -> None | Reads a table from the database, and writes SQL to replicate the table's
data to the output ``fileobj``.
Args:
engine: SQLAlchemy :class:`Engine`
table_name: name of the table
fileobj: file-like object to write to
wheredict: optional dictionary of ``{column_name: value}`` to use... | 2.968055 | 2.985782 | 0.994063 |
for tablename in get_table_names(engine):
dump_table_as_insert_sql(
engine=engine,
table_name=tablename,
fileobj=fileobj,
include_ddl=include_ddl,
multirow=multirow
) | def dump_database_as_insert_sql(engine: Engine,
fileobj: TextIO = sys.stdout,
include_ddl: bool = False,
multirow: bool = False) -> None | Reads an entire database and writes SQL to replicate it to the output
file-like object.
Args:
engine: SQLAlchemy :class:`Engine`
fileobj: file-like object to write to
include_ddl: if ``True``, include the DDL to create the table as well
multirow: write multi-row ``INSERT`` state... | 2.343093 | 2.46923 | 0.948916 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.