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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
25,400 | Cue/scales | src/greplin/scales/__init__.py | _Stats.reset | def reset(cls):
"""Resets the static state. Should only be called by tests."""
cls.stats = StatContainer()
cls.parentMap = {}
cls.containerMap = {}
cls.subId = 0
for stat in gc.get_objects():
if isinstance(stat, Stat):
stat._aggregators = {} | python | def reset(cls):
cls.stats = StatContainer()
cls.parentMap = {}
cls.containerMap = {}
cls.subId = 0
for stat in gc.get_objects():
if isinstance(stat, Stat):
stat._aggregators = {} | [
"def",
"reset",
"(",
"cls",
")",
":",
"cls",
".",
"stats",
"=",
"StatContainer",
"(",
")",
"cls",
".",
"parentMap",
"=",
"{",
"}",
"cls",
".",
"containerMap",
"=",
"{",
"}",
"cls",
".",
"subId",
"=",
"0",
"for",
"stat",
"in",
"gc",
".",
"get_obje... | Resets the static state. Should only be called by tests. | [
"Resets",
"the",
"static",
"state",
".",
"Should",
"only",
"be",
"called",
"by",
"tests",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/__init__.py#L111-L119 |
25,401 | Cue/scales | src/greplin/scales/__init__.py | _Stats.init | def init(cls, obj, context):
"""Implementation of init."""
addr = statsId(obj)
if addr not in cls.containerMap:
cls.containerMap[addr] = cls.__getStatContainer(context)
return cls.containerMap[addr] | python | def init(cls, obj, context):
addr = statsId(obj)
if addr not in cls.containerMap:
cls.containerMap[addr] = cls.__getStatContainer(context)
return cls.containerMap[addr] | [
"def",
"init",
"(",
"cls",
",",
"obj",
",",
"context",
")",
":",
"addr",
"=",
"statsId",
"(",
"obj",
")",
"if",
"addr",
"not",
"in",
"cls",
".",
"containerMap",
":",
"cls",
".",
"containerMap",
"[",
"addr",
"]",
"=",
"cls",
".",
"__getStatContainer",... | Implementation of init. | [
"Implementation",
"of",
"init",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/__init__.py#L123-L128 |
25,402 | Cue/scales | src/greplin/scales/__init__.py | _Stats.initChild | def initChild(cls, obj, name, subContext, parent = None):
"""Implementation of initChild."""
addr = statsId(obj)
if addr not in cls.containerMap:
if not parent:
# Find out the parent of the calling object by going back through the call stack until a self != this.
f = inspect.currentframe()
while not cls.__getSelf(f):
f = f.f_back
this = cls.__getSelf(f)
f = f.f_back
while cls.__getSelf(f) == this or not cls.__getSelf(f):
f = f.f_back
parent = cls.__getSelf(f)
# Default subcontext to an autoincrementing ID.
if subContext is None:
cls.subId += 1
subContext = cls.subId
if subContext is not '':
path = '%s/%s' % (name, subContext)
else:
path = name
# Now that we have the name, create an entry for this object.
cls.parentMap[addr] = parent
container = cls.getContainerForObject(statsId(parent))
if not container and isinstance(parent, unittest.TestCase):
cls.init(parent, '/test-case')
cls.containerMap[addr] = cls.__getStatContainer(path, cls.getContainerForObject(statsId(parent)))
return cls.containerMap[addr] | python | def initChild(cls, obj, name, subContext, parent = None):
addr = statsId(obj)
if addr not in cls.containerMap:
if not parent:
# Find out the parent of the calling object by going back through the call stack until a self != this.
f = inspect.currentframe()
while not cls.__getSelf(f):
f = f.f_back
this = cls.__getSelf(f)
f = f.f_back
while cls.__getSelf(f) == this or not cls.__getSelf(f):
f = f.f_back
parent = cls.__getSelf(f)
# Default subcontext to an autoincrementing ID.
if subContext is None:
cls.subId += 1
subContext = cls.subId
if subContext is not '':
path = '%s/%s' % (name, subContext)
else:
path = name
# Now that we have the name, create an entry for this object.
cls.parentMap[addr] = parent
container = cls.getContainerForObject(statsId(parent))
if not container and isinstance(parent, unittest.TestCase):
cls.init(parent, '/test-case')
cls.containerMap[addr] = cls.__getStatContainer(path, cls.getContainerForObject(statsId(parent)))
return cls.containerMap[addr] | [
"def",
"initChild",
"(",
"cls",
",",
"obj",
",",
"name",
",",
"subContext",
",",
"parent",
"=",
"None",
")",
":",
"addr",
"=",
"statsId",
"(",
"obj",
")",
"if",
"addr",
"not",
"in",
"cls",
".",
"containerMap",
":",
"if",
"not",
"parent",
":",
"# Fi... | Implementation of initChild. | [
"Implementation",
"of",
"initChild",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/__init__.py#L138-L169 |
25,403 | Cue/scales | src/greplin/scales/__init__.py | _Stats.__getStatContainer | def __getStatContainer(cls, context, parent=None):
"""Get the stat container for the given context under the given parent."""
container = parent
if container is None:
container = cls.stats
if context is not None:
context = str(context).lstrip('/')
for key in context.split('/'):
container.setdefault(key, StatContainer())
container = container[key]
return container | python | def __getStatContainer(cls, context, parent=None):
container = parent
if container is None:
container = cls.stats
if context is not None:
context = str(context).lstrip('/')
for key in context.split('/'):
container.setdefault(key, StatContainer())
container = container[key]
return container | [
"def",
"__getStatContainer",
"(",
"cls",
",",
"context",
",",
"parent",
"=",
"None",
")",
":",
"container",
"=",
"parent",
"if",
"container",
"is",
"None",
":",
"container",
"=",
"cls",
".",
"stats",
"if",
"context",
"is",
"not",
"None",
":",
"context",
... | Get the stat container for the given context under the given parent. | [
"Get",
"the",
"stat",
"container",
"for",
"the",
"given",
"context",
"under",
"the",
"given",
"parent",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/__init__.py#L173-L183 |
25,404 | Cue/scales | src/greplin/scales/__init__.py | _Stats.getStat | def getStat(cls, obj, name):
"""Gets the stat for the given object with the given name, or None if no such stat exists."""
objClass = type(obj)
for theClass in objClass.__mro__:
if theClass == object:
break
for value in theClass.__dict__.values():
if isinstance(value, Stat) and value.getName() == name:
return value | python | def getStat(cls, obj, name):
objClass = type(obj)
for theClass in objClass.__mro__:
if theClass == object:
break
for value in theClass.__dict__.values():
if isinstance(value, Stat) and value.getName() == name:
return value | [
"def",
"getStat",
"(",
"cls",
",",
"obj",
",",
"name",
")",
":",
"objClass",
"=",
"type",
"(",
"obj",
")",
"for",
"theClass",
"in",
"objClass",
".",
"__mro__",
":",
"if",
"theClass",
"==",
"object",
":",
"break",
"for",
"value",
"in",
"theClass",
"."... | Gets the stat for the given object with the given name, or None if no such stat exists. | [
"Gets",
"the",
"stat",
"for",
"the",
"given",
"object",
"with",
"the",
"given",
"name",
"or",
"None",
"if",
"no",
"such",
"stat",
"exists",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/__init__.py#L193-L201 |
25,405 | Cue/scales | src/greplin/scales/__init__.py | _Stats.getAggregator | def getAggregator(cls, instanceId, name):
"""Gets the aggregate stat for the given stat."""
parent = cls.parentMap.get(instanceId)
while parent:
stat = cls.getStat(parent, name)
if stat:
return stat, parent
parent = cls.parentMap.get(statsId(parent)) | python | def getAggregator(cls, instanceId, name):
parent = cls.parentMap.get(instanceId)
while parent:
stat = cls.getStat(parent, name)
if stat:
return stat, parent
parent = cls.parentMap.get(statsId(parent)) | [
"def",
"getAggregator",
"(",
"cls",
",",
"instanceId",
",",
"name",
")",
":",
"parent",
"=",
"cls",
".",
"parentMap",
".",
"get",
"(",
"instanceId",
")",
"while",
"parent",
":",
"stat",
"=",
"cls",
".",
"getStat",
"(",
"parent",
",",
"name",
")",
"if... | Gets the aggregate stat for the given stat. | [
"Gets",
"the",
"aggregate",
"stat",
"for",
"the",
"given",
"stat",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/__init__.py#L205-L212 |
25,406 | Cue/scales | src/greplin/scales/__init__.py | Stat._aggregate | def _aggregate(self, instanceId, container, value, subKey = None):
"""Performs stat aggregation."""
# Get the aggregator.
if instanceId not in self._aggregators:
self._aggregators[instanceId] = _Stats.getAggregator(instanceId, self.__name)
aggregator = self._aggregators[instanceId]
# If we are aggregating, get the old value.
if aggregator:
oldValue = container.get(self.__name)
if subKey:
oldValue = oldValue[subKey]
aggregator[0].update(aggregator[1], oldValue, value, subKey)
else:
aggregator[0].update(aggregator[1], oldValue, value) | python | def _aggregate(self, instanceId, container, value, subKey = None):
# Get the aggregator.
if instanceId not in self._aggregators:
self._aggregators[instanceId] = _Stats.getAggregator(instanceId, self.__name)
aggregator = self._aggregators[instanceId]
# If we are aggregating, get the old value.
if aggregator:
oldValue = container.get(self.__name)
if subKey:
oldValue = oldValue[subKey]
aggregator[0].update(aggregator[1], oldValue, value, subKey)
else:
aggregator[0].update(aggregator[1], oldValue, value) | [
"def",
"_aggregate",
"(",
"self",
",",
"instanceId",
",",
"container",
",",
"value",
",",
"subKey",
"=",
"None",
")",
":",
"# Get the aggregator.",
"if",
"instanceId",
"not",
"in",
"self",
".",
"_aggregators",
":",
"self",
".",
"_aggregators",
"[",
"instance... | Performs stat aggregation. | [
"Performs",
"stat",
"aggregation",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/__init__.py#L254-L269 |
25,407 | Cue/scales | src/greplin/scales/__init__.py | Stat.updateItem | def updateItem(self, instance, subKey, value):
"""Updates a child value. Must be called before the update has actually occurred."""
instanceId = statsId(instance)
container = _Stats.getContainerForObject(instanceId)
self._aggregate(instanceId, container, value, subKey) | python | def updateItem(self, instance, subKey, value):
instanceId = statsId(instance)
container = _Stats.getContainerForObject(instanceId)
self._aggregate(instanceId, container, value, subKey) | [
"def",
"updateItem",
"(",
"self",
",",
"instance",
",",
"subKey",
",",
"value",
")",
":",
"instanceId",
"=",
"statsId",
"(",
"instance",
")",
"container",
"=",
"_Stats",
".",
"getContainerForObject",
"(",
"instanceId",
")",
"self",
".",
"_aggregate",
"(",
... | Updates a child value. Must be called before the update has actually occurred. | [
"Updates",
"a",
"child",
"value",
".",
"Must",
"be",
"called",
"before",
"the",
"update",
"has",
"actually",
"occurred",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/__init__.py#L283-L288 |
25,408 | Cue/scales | src/greplin/scales/__init__.py | StateTimeStatDict.incr | def incr(self, item, value):
"""Increment a key by the given amount."""
if item in self:
old = UserDict.__getitem__(self, item)
else:
old = 0.0
self[item] = old + value | python | def incr(self, item, value):
if item in self:
old = UserDict.__getitem__(self, item)
else:
old = 0.0
self[item] = old + value | [
"def",
"incr",
"(",
"self",
",",
"item",
",",
"value",
")",
":",
"if",
"item",
"in",
"self",
":",
"old",
"=",
"UserDict",
".",
"__getitem__",
"(",
"self",
",",
"item",
")",
"else",
":",
"old",
"=",
"0.0",
"self",
"[",
"item",
"]",
"=",
"old",
"... | Increment a key by the given amount. | [
"Increment",
"a",
"key",
"by",
"the",
"given",
"amount",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/__init__.py#L617-L623 |
25,409 | Cue/scales | src/greplin/scales/aggregation.py | Aggregation.addSource | def addSource(self, source, data):
"""Adds the given source's stats."""
self._aggregate(source, self._aggregators, data, self._result) | python | def addSource(self, source, data):
self._aggregate(source, self._aggregators, data, self._result) | [
"def",
"addSource",
"(",
"self",
",",
"source",
",",
"data",
")",
":",
"self",
".",
"_aggregate",
"(",
"source",
",",
"self",
".",
"_aggregators",
",",
"data",
",",
"self",
".",
"_result",
")"
] | Adds the given source's stats. | [
"Adds",
"the",
"given",
"source",
"s",
"stats",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/aggregation.py#L332-L334 |
25,410 | Cue/scales | src/greplin/scales/aggregation.py | Aggregation.addJsonDirectory | def addJsonDirectory(self, directory, test=None):
"""Adds data from json files in the given directory."""
for filename in os.listdir(directory):
try:
fullPath = os.path.join(directory, filename)
if not test or test(filename, fullPath):
with open(fullPath) as f:
jsonData = json.load(f)
name, _ = os.path.splitext(filename)
self.addSource(name, jsonData)
except ValueError:
continue | python | def addJsonDirectory(self, directory, test=None):
for filename in os.listdir(directory):
try:
fullPath = os.path.join(directory, filename)
if not test or test(filename, fullPath):
with open(fullPath) as f:
jsonData = json.load(f)
name, _ = os.path.splitext(filename)
self.addSource(name, jsonData)
except ValueError:
continue | [
"def",
"addJsonDirectory",
"(",
"self",
",",
"directory",
",",
"test",
"=",
"None",
")",
":",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"directory",
")",
":",
"try",
":",
"fullPath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",... | Adds data from json files in the given directory. | [
"Adds",
"data",
"from",
"json",
"files",
"in",
"the",
"given",
"directory",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/aggregation.py#L337-L350 |
25,411 | Cue/scales | src/greplin/scales/samplestats.py | Sampler.mean | def mean(self):
"""Return the sample mean."""
if len(self) == 0:
return float('NaN')
arr = self.samples()
return sum(arr) / float(len(arr)) | python | def mean(self):
if len(self) == 0:
return float('NaN')
arr = self.samples()
return sum(arr) / float(len(arr)) | [
"def",
"mean",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
")",
"==",
"0",
":",
"return",
"float",
"(",
"'NaN'",
")",
"arr",
"=",
"self",
".",
"samples",
"(",
")",
"return",
"sum",
"(",
"arr",
")",
"/",
"float",
"(",
"len",
"(",
"arr",
"... | Return the sample mean. | [
"Return",
"the",
"sample",
"mean",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/samplestats.py#L46-L51 |
25,412 | Cue/scales | src/greplin/scales/samplestats.py | Sampler.stddev | def stddev(self):
"""Return the sample standard deviation."""
if len(self) < 2:
return float('NaN')
# The stupidest algorithm, but it works fine.
try:
arr = self.samples()
mean = sum(arr) / len(arr)
bigsum = 0.0
for x in arr:
bigsum += (x - mean)**2
return sqrt(bigsum / (len(arr) - 1))
except ZeroDivisionError:
return float('NaN') | python | def stddev(self):
if len(self) < 2:
return float('NaN')
# The stupidest algorithm, but it works fine.
try:
arr = self.samples()
mean = sum(arr) / len(arr)
bigsum = 0.0
for x in arr:
bigsum += (x - mean)**2
return sqrt(bigsum / (len(arr) - 1))
except ZeroDivisionError:
return float('NaN') | [
"def",
"stddev",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
")",
"<",
"2",
":",
"return",
"float",
"(",
"'NaN'",
")",
"# The stupidest algorithm, but it works fine.",
"try",
":",
"arr",
"=",
"self",
".",
"samples",
"(",
")",
"mean",
"=",
"sum",
"... | Return the sample standard deviation. | [
"Return",
"the",
"sample",
"standard",
"deviation",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/samplestats.py#L55-L68 |
25,413 | Cue/scales | src/greplin/scales/samplestats.py | ExponentiallyDecayingReservoir.clear | def clear(self):
""" Clear the samples. """
self.__init__(size=self.size, alpha=self.alpha, clock=self.clock) | python | def clear(self):
self.__init__(size=self.size, alpha=self.alpha, clock=self.clock) | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"__init__",
"(",
"size",
"=",
"self",
".",
"size",
",",
"alpha",
"=",
"self",
".",
"alpha",
",",
"clock",
"=",
"self",
".",
"clock",
")"
] | Clear the samples. | [
"Clear",
"the",
"samples",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/samplestats.py#L140-L142 |
25,414 | Cue/scales | src/greplin/scales/samplestats.py | ExponentiallyDecayingReservoir.update | def update(self, value):
"""
Adds an old value with a fixed timestamp to the reservoir.
@param value the value to be added
"""
super(ExponentiallyDecayingReservoir, self).update(value)
timestamp = self.clock.time()
self.__rescaleIfNeeded()
priority = self.__weight(timestamp - self.startTime) / random.random()
self.count += 1
if (self.count <= self.size):
self.values[priority] = value
else:
first = min(self.values)
if first < priority and priority not in self.values:
self.values[priority] = value
while first not in self.values:
first = min(self.values)
del self.values[first] | python | def update(self, value):
super(ExponentiallyDecayingReservoir, self).update(value)
timestamp = self.clock.time()
self.__rescaleIfNeeded()
priority = self.__weight(timestamp - self.startTime) / random.random()
self.count += 1
if (self.count <= self.size):
self.values[priority] = value
else:
first = min(self.values)
if first < priority and priority not in self.values:
self.values[priority] = value
while first not in self.values:
first = min(self.values)
del self.values[first] | [
"def",
"update",
"(",
"self",
",",
"value",
")",
":",
"super",
"(",
"ExponentiallyDecayingReservoir",
",",
"self",
")",
".",
"update",
"(",
"value",
")",
"timestamp",
"=",
"self",
".",
"clock",
".",
"time",
"(",
")",
"self",
".",
"__rescaleIfNeeded",
"("... | Adds an old value with a fixed timestamp to the reservoir.
@param value the value to be added | [
"Adds",
"an",
"old",
"value",
"with",
"a",
"fixed",
"timestamp",
"to",
"the",
"reservoir",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/samplestats.py#L144-L167 |
25,415 | Cue/scales | src/greplin/scales/samplestats.py | UniformSample.clear | def clear(self):
"""Clear the sample."""
for i in range(len(self.sample)):
self.sample[i] = 0.0
self.count = 0 | python | def clear(self):
for i in range(len(self.sample)):
self.sample[i] = 0.0
self.count = 0 | [
"def",
"clear",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"sample",
")",
")",
":",
"self",
".",
"sample",
"[",
"i",
"]",
"=",
"0.0",
"self",
".",
"count",
"=",
"0"
] | Clear the sample. | [
"Clear",
"the",
"sample",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/samplestats.py#L212-L216 |
25,416 | Cue/scales | src/greplin/scales/samplestats.py | UniformSample.update | def update(self, value):
"""Add a value to the sample."""
super(UniformSample, self).update(value)
self.count += 1
c = self.count
if c < len(self.sample):
self.sample[c-1] = value
else:
r = random.randint(0, c)
if r < len(self.sample):
self.sample[r] = value | python | def update(self, value):
super(UniformSample, self).update(value)
self.count += 1
c = self.count
if c < len(self.sample):
self.sample[c-1] = value
else:
r = random.randint(0, c)
if r < len(self.sample):
self.sample[r] = value | [
"def",
"update",
"(",
"self",
",",
"value",
")",
":",
"super",
"(",
"UniformSample",
",",
"self",
")",
".",
"update",
"(",
"value",
")",
"self",
".",
"count",
"+=",
"1",
"c",
"=",
"self",
".",
"count",
"if",
"c",
"<",
"len",
"(",
"self",
".",
"... | Add a value to the sample. | [
"Add",
"a",
"value",
"to",
"the",
"sample",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/samplestats.py#L222-L233 |
25,417 | Cue/scales | src/greplin/scales/graphite.py | GraphitePusher._forbidden | def _forbidden(self, path, value):
"""Is a stat forbidden? Goes through the rules to find one that
applies. Chronologically newer rules are higher-precedence than
older ones. If no rule applies, the stat is forbidden by default."""
if path[0] == '/':
path = path[1:]
for rule in reversed(self.rules):
if isinstance(rule[1], six.string_types):
if fnmatch(path, rule[1]):
return not rule[0]
elif rule[1](path, value):
return not rule[0]
return True | python | def _forbidden(self, path, value):
if path[0] == '/':
path = path[1:]
for rule in reversed(self.rules):
if isinstance(rule[1], six.string_types):
if fnmatch(path, rule[1]):
return not rule[0]
elif rule[1](path, value):
return not rule[0]
return True | [
"def",
"_forbidden",
"(",
"self",
",",
"path",
",",
"value",
")",
":",
"if",
"path",
"[",
"0",
"]",
"==",
"'/'",
":",
"path",
"=",
"path",
"[",
"1",
":",
"]",
"for",
"rule",
"in",
"reversed",
"(",
"self",
".",
"rules",
")",
":",
"if",
"isinstan... | Is a stat forbidden? Goes through the rules to find one that
applies. Chronologically newer rules are higher-precedence than
older ones. If no rule applies, the stat is forbidden by default. | [
"Is",
"a",
"stat",
"forbidden?",
"Goes",
"through",
"the",
"rules",
"to",
"find",
"one",
"that",
"applies",
".",
"Chronologically",
"newer",
"rules",
"are",
"higher",
"-",
"precedence",
"than",
"older",
"ones",
".",
"If",
"no",
"rule",
"applies",
"the",
"s... | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/graphite.py#L55-L67 |
25,418 | Cue/scales | src/greplin/scales/graphite.py | GraphitePusher._pruned | def _pruned(self, path):
"""Is a stat tree node pruned? Goes through the list of prune rules
to find one that applies. Chronologically newer rules are
higher-precedence than older ones. If no rule applies, the stat is
not pruned by default."""
if path[0] == '/':
path = path[1:]
for rule in reversed(self.pruneRules):
if isinstance(rule, six.string_types):
if fnmatch(path, rule):
return True
elif rule(path):
return True
return False | python | def _pruned(self, path):
if path[0] == '/':
path = path[1:]
for rule in reversed(self.pruneRules):
if isinstance(rule, six.string_types):
if fnmatch(path, rule):
return True
elif rule(path):
return True
return False | [
"def",
"_pruned",
"(",
"self",
",",
"path",
")",
":",
"if",
"path",
"[",
"0",
"]",
"==",
"'/'",
":",
"path",
"=",
"path",
"[",
"1",
":",
"]",
"for",
"rule",
"in",
"reversed",
"(",
"self",
".",
"pruneRules",
")",
":",
"if",
"isinstance",
"(",
"r... | Is a stat tree node pruned? Goes through the list of prune rules
to find one that applies. Chronologically newer rules are
higher-precedence than older ones. If no rule applies, the stat is
not pruned by default. | [
"Is",
"a",
"stat",
"tree",
"node",
"pruned?",
"Goes",
"through",
"the",
"list",
"of",
"prune",
"rules",
"to",
"find",
"one",
"that",
"applies",
".",
"Chronologically",
"newer",
"rules",
"are",
"higher",
"-",
"precedence",
"than",
"older",
"ones",
".",
"If"... | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/graphite.py#L70-L83 |
25,419 | Cue/scales | src/greplin/scales/graphite.py | GraphitePusher.push | def push(self, statsDict=None, prefix=None, path=None):
"""Push stat values out to Graphite."""
if statsDict is None:
statsDict = scales.getStats()
prefix = prefix or self.prefix
path = path or '/'
for name, value in list(statsDict.items()):
name = str(name)
subpath = os.path.join(path, name)
if self._pruned(subpath):
continue
if hasattr(value, '__call__'):
try:
value = value()
except: # pylint: disable=W0702
value = None
log.exception('Error when calling stat function for graphite push')
if hasattr(value, 'items'):
self.push(value, '%s%s.' % (prefix, self._sanitize(name)), subpath)
elif self._forbidden(subpath, value):
continue
if six.PY3:
type_values = (int, float)
else:
type_values = (int, long, float)
if type(value) in type_values and len(name) < 500:
self.graphite.log(prefix + self._sanitize(name), value) | python | def push(self, statsDict=None, prefix=None, path=None):
if statsDict is None:
statsDict = scales.getStats()
prefix = prefix or self.prefix
path = path or '/'
for name, value in list(statsDict.items()):
name = str(name)
subpath = os.path.join(path, name)
if self._pruned(subpath):
continue
if hasattr(value, '__call__'):
try:
value = value()
except: # pylint: disable=W0702
value = None
log.exception('Error when calling stat function for graphite push')
if hasattr(value, 'items'):
self.push(value, '%s%s.' % (prefix, self._sanitize(name)), subpath)
elif self._forbidden(subpath, value):
continue
if six.PY3:
type_values = (int, float)
else:
type_values = (int, long, float)
if type(value) in type_values and len(name) < 500:
self.graphite.log(prefix + self._sanitize(name), value) | [
"def",
"push",
"(",
"self",
",",
"statsDict",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"if",
"statsDict",
"is",
"None",
":",
"statsDict",
"=",
"scales",
".",
"getStats",
"(",
")",
"prefix",
"=",
"prefix",
"or",
"... | Push stat values out to Graphite. | [
"Push",
"stat",
"values",
"out",
"to",
"Graphite",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/graphite.py#L86-L118 |
25,420 | Cue/scales | src/greplin/scales/graphite.py | GraphitePeriodicPusher.run | def run(self):
"""Loop forever, pushing out stats."""
self.graphite.start()
while True:
log.debug('Graphite pusher is sleeping for %d seconds', self.period)
time.sleep(self.period)
log.debug('Pushing stats to Graphite')
try:
self.push()
log.debug('Done pushing stats to Graphite')
except:
log.exception('Exception while pushing stats to Graphite')
raise | python | def run(self):
self.graphite.start()
while True:
log.debug('Graphite pusher is sleeping for %d seconds', self.period)
time.sleep(self.period)
log.debug('Pushing stats to Graphite')
try:
self.push()
log.debug('Done pushing stats to Graphite')
except:
log.exception('Exception while pushing stats to Graphite')
raise | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"graphite",
".",
"start",
"(",
")",
"while",
"True",
":",
"log",
".",
"debug",
"(",
"'Graphite pusher is sleeping for %d seconds'",
",",
"self",
".",
"period",
")",
"time",
".",
"sleep",
"(",
"self",
".",... | Loop forever, pushing out stats. | [
"Loop",
"forever",
"pushing",
"out",
"stats",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/graphite.py#L163-L175 |
25,421 | Cue/scales | src/greplin/scales/loop.py | installStatsLoop | def installStatsLoop(statsFile, statsDelay):
"""Installs an interval loop that dumps stats to a file."""
def dumpStats():
"""Actual stats dump function."""
scales.dumpStatsTo(statsFile)
reactor.callLater(statsDelay, dumpStats)
def startStats():
"""Starts the stats dump in "statsDelay" seconds."""
reactor.callLater(statsDelay, dumpStats)
reactor.callWhenRunning(startStats) | python | def installStatsLoop(statsFile, statsDelay):
def dumpStats():
"""Actual stats dump function."""
scales.dumpStatsTo(statsFile)
reactor.callLater(statsDelay, dumpStats)
def startStats():
"""Starts the stats dump in "statsDelay" seconds."""
reactor.callLater(statsDelay, dumpStats)
reactor.callWhenRunning(startStats) | [
"def",
"installStatsLoop",
"(",
"statsFile",
",",
"statsDelay",
")",
":",
"def",
"dumpStats",
"(",
")",
":",
"\"\"\"Actual stats dump function.\"\"\"",
"scales",
".",
"dumpStatsTo",
"(",
"statsFile",
")",
"reactor",
".",
"callLater",
"(",
"statsDelay",
",",
"dumpS... | Installs an interval loop that dumps stats to a file. | [
"Installs",
"an",
"interval",
"loop",
"that",
"dumps",
"stats",
"to",
"a",
"file",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/loop.py#L22-L34 |
25,422 | Cue/scales | src/greplin/scales/formats.py | runQuery | def runQuery(statDict, query):
"""Filters for the given query."""
parts = [x.strip() for x in OPERATOR.split(query)]
assert len(parts) in (1, 3)
queryKey = parts[0]
result = {}
for key, value in six.iteritems(statDict):
if key == queryKey:
if len(parts) == 3:
op = OPERATORS[parts[1]]
try:
queryValue = type(value)(parts[2]) if value else parts[2]
except (TypeError, ValueError):
continue
if not op(value, queryValue):
continue
result[key] = value
elif isinstance(value, scales.StatContainer) or isinstance(value, dict):
child = runQuery(value, query)
if child:
result[key] = child
return result | python | def runQuery(statDict, query):
parts = [x.strip() for x in OPERATOR.split(query)]
assert len(parts) in (1, 3)
queryKey = parts[0]
result = {}
for key, value in six.iteritems(statDict):
if key == queryKey:
if len(parts) == 3:
op = OPERATORS[parts[1]]
try:
queryValue = type(value)(parts[2]) if value else parts[2]
except (TypeError, ValueError):
continue
if not op(value, queryValue):
continue
result[key] = value
elif isinstance(value, scales.StatContainer) or isinstance(value, dict):
child = runQuery(value, query)
if child:
result[key] = child
return result | [
"def",
"runQuery",
"(",
"statDict",
",",
"query",
")",
":",
"parts",
"=",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"OPERATOR",
".",
"split",
"(",
"query",
")",
"]",
"assert",
"len",
"(",
"parts",
")",
"in",
"(",
"1",
",",
"3",
")",
... | Filters for the given query. | [
"Filters",
"for",
"the",
"given",
"query",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/formats.py#L38-L60 |
25,423 | Cue/scales | src/greplin/scales/formats.py | htmlHeader | def htmlHeader(output, path, serverName, query = None):
"""Writes an HTML header."""
if path and path != '/':
output.write('<title>%s - Status: %s</title>' % (serverName, path))
else:
output.write('<title>%s - Status</title>' % serverName)
output.write('''
<style>
body,td { font-family: monospace }
.level div {
padding-bottom: 4px;
}
.level .level {
margin-left: 2em;
padding: 1px 0;
}
span { color: #090; vertical-align: top }
.key { color: black; font-weight: bold }
.int, .float { color: #00c }
</style>
''')
output.write('<h1 style="margin: 0">Stats</h1>')
output.write('<h3 style="margin: 3px 0 18px">%s</h3>' % serverName)
output.write(
'<p><form action="#" method="GET">Filter: <input type="text" name="query" size="20" value="%s"></form></p>' %
(query or '')) | python | def htmlHeader(output, path, serverName, query = None):
if path and path != '/':
output.write('<title>%s - Status: %s</title>' % (serverName, path))
else:
output.write('<title>%s - Status</title>' % serverName)
output.write('''
<style>
body,td { font-family: monospace }
.level div {
padding-bottom: 4px;
}
.level .level {
margin-left: 2em;
padding: 1px 0;
}
span { color: #090; vertical-align: top }
.key { color: black; font-weight: bold }
.int, .float { color: #00c }
</style>
''')
output.write('<h1 style="margin: 0">Stats</h1>')
output.write('<h3 style="margin: 3px 0 18px">%s</h3>' % serverName)
output.write(
'<p><form action="#" method="GET">Filter: <input type="text" name="query" size="20" value="%s"></form></p>' %
(query or '')) | [
"def",
"htmlHeader",
"(",
"output",
",",
"path",
",",
"serverName",
",",
"query",
"=",
"None",
")",
":",
"if",
"path",
"and",
"path",
"!=",
"'/'",
":",
"output",
".",
"write",
"(",
"'<title>%s - Status: %s</title>'",
"%",
"(",
"serverName",
",",
"path",
... | Writes an HTML header. | [
"Writes",
"an",
"HTML",
"header",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/formats.py#L63-L88 |
25,424 | Cue/scales | src/greplin/scales/formats.py | htmlFormat | def htmlFormat(output, pathParts = (), statDict = None, query = None):
"""Formats as HTML, writing to the given object."""
statDict = statDict or scales.getStats()
if query:
statDict = runQuery(statDict, query)
_htmlRenderDict(pathParts, statDict, output) | python | def htmlFormat(output, pathParts = (), statDict = None, query = None):
statDict = statDict or scales.getStats()
if query:
statDict = runQuery(statDict, query)
_htmlRenderDict(pathParts, statDict, output) | [
"def",
"htmlFormat",
"(",
"output",
",",
"pathParts",
"=",
"(",
")",
",",
"statDict",
"=",
"None",
",",
"query",
"=",
"None",
")",
":",
"statDict",
"=",
"statDict",
"or",
"scales",
".",
"getStats",
"(",
")",
"if",
"query",
":",
"statDict",
"=",
"runQ... | Formats as HTML, writing to the given object. | [
"Formats",
"as",
"HTML",
"writing",
"to",
"the",
"given",
"object",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/formats.py#L91-L96 |
25,425 | Cue/scales | src/greplin/scales/formats.py | _htmlRenderDict | def _htmlRenderDict(pathParts, statDict, output):
"""Render a dictionary as a table - recursing as necessary."""
keys = list(statDict.keys())
keys.sort()
links = []
output.write('<div class="level">')
for key in keys:
keyStr = cgi.escape(_utf8str(key))
value = statDict[key]
if hasattr(value, '__call__'):
value = value()
if hasattr(value, 'keys'):
valuePath = pathParts + (keyStr,)
if isinstance(value, scales.StatContainer) and value.isCollapsed():
link = '/status/' + '/'.join(valuePath)
links.append('<div class="key"><a href="%s">%s</a></div>' % (link, keyStr))
else:
output.write('<div class="key">%s</div>' % keyStr)
_htmlRenderDict(valuePath, value, output)
else:
output.write('<div><span class="key">%s</span> <span class="%s">%s</span></div>' %
(keyStr, type(value).__name__, cgi.escape(_utf8str(value)).replace('\n', '<br/>')))
if links:
for link in links:
output.write(link)
output.write('</div>') | python | def _htmlRenderDict(pathParts, statDict, output):
keys = list(statDict.keys())
keys.sort()
links = []
output.write('<div class="level">')
for key in keys:
keyStr = cgi.escape(_utf8str(key))
value = statDict[key]
if hasattr(value, '__call__'):
value = value()
if hasattr(value, 'keys'):
valuePath = pathParts + (keyStr,)
if isinstance(value, scales.StatContainer) and value.isCollapsed():
link = '/status/' + '/'.join(valuePath)
links.append('<div class="key"><a href="%s">%s</a></div>' % (link, keyStr))
else:
output.write('<div class="key">%s</div>' % keyStr)
_htmlRenderDict(valuePath, value, output)
else:
output.write('<div><span class="key">%s</span> <span class="%s">%s</span></div>' %
(keyStr, type(value).__name__, cgi.escape(_utf8str(value)).replace('\n', '<br/>')))
if links:
for link in links:
output.write(link)
output.write('</div>') | [
"def",
"_htmlRenderDict",
"(",
"pathParts",
",",
"statDict",
",",
"output",
")",
":",
"keys",
"=",
"list",
"(",
"statDict",
".",
"keys",
"(",
")",
")",
"keys",
".",
"sort",
"(",
")",
"links",
"=",
"[",
"]",
"output",
".",
"write",
"(",
"'<div class=\... | Render a dictionary as a table - recursing as necessary. | [
"Render",
"a",
"dictionary",
"as",
"a",
"table",
"-",
"recursing",
"as",
"necessary",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/formats.py#L99-L128 |
25,426 | Cue/scales | src/greplin/scales/formats.py | jsonFormat | def jsonFormat(output, statDict = None, query = None, pretty = False):
"""Formats as JSON, writing to the given object."""
statDict = statDict or scales.getStats()
if query:
statDict = runQuery(statDict, query)
indent = 2 if pretty else None
# At first, assume that strings are in UTF-8. If this fails -- if, for example, we have
# crazy binary data -- then in order to get *something* out, we assume ISO-8859-1,
# which maps each byte to a unicode code point.
try:
serialized = json.dumps(statDict, cls=scales.StatContainerEncoder, indent=indent)
except UnicodeDecodeError:
serialized = json.dumps(statDict, cls=scales.StatContainerEncoder, indent=indent, encoding='iso-8859-1')
output.write(serialized)
output.write('\n') | python | def jsonFormat(output, statDict = None, query = None, pretty = False):
statDict = statDict or scales.getStats()
if query:
statDict = runQuery(statDict, query)
indent = 2 if pretty else None
# At first, assume that strings are in UTF-8. If this fails -- if, for example, we have
# crazy binary data -- then in order to get *something* out, we assume ISO-8859-1,
# which maps each byte to a unicode code point.
try:
serialized = json.dumps(statDict, cls=scales.StatContainerEncoder, indent=indent)
except UnicodeDecodeError:
serialized = json.dumps(statDict, cls=scales.StatContainerEncoder, indent=indent, encoding='iso-8859-1')
output.write(serialized)
output.write('\n') | [
"def",
"jsonFormat",
"(",
"output",
",",
"statDict",
"=",
"None",
",",
"query",
"=",
"None",
",",
"pretty",
"=",
"False",
")",
":",
"statDict",
"=",
"statDict",
"or",
"scales",
".",
"getStats",
"(",
")",
"if",
"query",
":",
"statDict",
"=",
"runQuery",... | Formats as JSON, writing to the given object. | [
"Formats",
"as",
"JSON",
"writing",
"to",
"the",
"given",
"object",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/formats.py#L143-L158 |
25,427 | Cue/scales | src/greplin/scales/timer.py | RepeatTimer | def RepeatTimer(interval, function, iterations=0, *args, **kwargs):
"""Repeating timer. Returns a thread id."""
def __repeat_timer(interval, function, iterations, args, kwargs):
"""Inner function, run in background thread."""
count = 0
while iterations <= 0 or count < iterations:
sleep(interval)
function(*args, **kwargs)
count += 1
return start_new_thread(__repeat_timer, (interval, function, iterations, args, kwargs)) | python | def RepeatTimer(interval, function, iterations=0, *args, **kwargs):
def __repeat_timer(interval, function, iterations, args, kwargs):
"""Inner function, run in background thread."""
count = 0
while iterations <= 0 or count < iterations:
sleep(interval)
function(*args, **kwargs)
count += 1
return start_new_thread(__repeat_timer, (interval, function, iterations, args, kwargs)) | [
"def",
"RepeatTimer",
"(",
"interval",
",",
"function",
",",
"iterations",
"=",
"0",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"__repeat_timer",
"(",
"interval",
",",
"function",
",",
"iterations",
",",
"args",
",",
"kwargs",
")",
":"... | Repeating timer. Returns a thread id. | [
"Repeating",
"timer",
".",
"Returns",
"a",
"thread",
"id",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/timer.py#L39-L50 |
25,428 | arthurk/django-disqus | disqus/templatetags/disqus_tags.py | get_config | def get_config(context):
"""
Return the formatted javascript for any disqus config variables.
"""
conf_vars = ['disqus_developer',
'disqus_identifier',
'disqus_url',
'disqus_title',
'disqus_category_id'
]
js = '\tvar {} = "{}";'
output = [js.format(item, context[item]) for item in conf_vars \
if item in context]
return '\n'.join(output) | python | def get_config(context):
conf_vars = ['disqus_developer',
'disqus_identifier',
'disqus_url',
'disqus_title',
'disqus_category_id'
]
js = '\tvar {} = "{}";'
output = [js.format(item, context[item]) for item in conf_vars \
if item in context]
return '\n'.join(output) | [
"def",
"get_config",
"(",
"context",
")",
":",
"conf_vars",
"=",
"[",
"'disqus_developer'",
",",
"'disqus_identifier'",
",",
"'disqus_url'",
",",
"'disqus_title'",
",",
"'disqus_category_id'",
"]",
"js",
"=",
"'\\tvar {} = \"{}\";'",
"output",
"=",
"[",
"js",
".",... | Return the formatted javascript for any disqus config variables. | [
"Return",
"the",
"formatted",
"javascript",
"for",
"any",
"disqus",
"config",
"variables",
"."
] | 0db52c240906c6663189c0a7aca9979a0db004d1 | https://github.com/arthurk/django-disqus/blob/0db52c240906c6663189c0a7aca9979a0db004d1/disqus/templatetags/disqus_tags.py#L45-L62 |
25,429 | arthurk/django-disqus | disqus/templatetags/disqus_tags.py | disqus_show_comments | def disqus_show_comments(context, shortname=''):
"""
Return the HTML code to display DISQUS comments.
"""
shortname = getattr(settings, 'DISQUS_WEBSITE_SHORTNAME', shortname)
return {
'shortname': shortname,
'config': get_config(context),
} | python | def disqus_show_comments(context, shortname=''):
shortname = getattr(settings, 'DISQUS_WEBSITE_SHORTNAME', shortname)
return {
'shortname': shortname,
'config': get_config(context),
} | [
"def",
"disqus_show_comments",
"(",
"context",
",",
"shortname",
"=",
"''",
")",
":",
"shortname",
"=",
"getattr",
"(",
"settings",
",",
"'DISQUS_WEBSITE_SHORTNAME'",
",",
"shortname",
")",
"return",
"{",
"'shortname'",
":",
"shortname",
",",
"'config'",
":",
... | Return the HTML code to display DISQUS comments. | [
"Return",
"the",
"HTML",
"code",
"to",
"display",
"DISQUS",
"comments",
"."
] | 0db52c240906c6663189c0a7aca9979a0db004d1 | https://github.com/arthurk/django-disqus/blob/0db52c240906c6663189c0a7aca9979a0db004d1/disqus/templatetags/disqus_tags.py#L158-L167 |
25,430 | arthurk/django-disqus | disqus/wxr_feed.py | WxrFeedType.add_item | def add_item(self, title, link, description, author_email=None,
author_name=None, author_link=None, pubdate=None, comments=None,
unique_id=None, enclosure=None, categories=(), item_copyright=None,
ttl=None, **kwargs):
"""
Adds an item to the feed. All args are expected to be Python Unicode
objects except pubdate, which is a datetime.datetime object, and
enclosure, which is an instance of the Enclosure class.
"""
to_unicode = lambda s: force_text(s, strings_only=True)
if categories:
categories = [to_unicode(c) for c in categories]
if ttl is not None:
# Force ints to unicode
ttl = force_text(ttl)
item = {
'title': to_unicode(title),
'link': iri_to_uri(link),
'description': to_unicode(description),
'author_email': to_unicode(author_email),
'author_name': to_unicode(author_name),
'author_link': iri_to_uri(author_link),
'pubdate': pubdate,
'comments': comments,
'unique_id': to_unicode(unique_id),
'enclosure': enclosure,
'categories': categories or (),
'item_copyright': to_unicode(item_copyright),
'ttl': ttl,
}
item.update(kwargs)
self.items.append(item) | python | def add_item(self, title, link, description, author_email=None,
author_name=None, author_link=None, pubdate=None, comments=None,
unique_id=None, enclosure=None, categories=(), item_copyright=None,
ttl=None, **kwargs):
to_unicode = lambda s: force_text(s, strings_only=True)
if categories:
categories = [to_unicode(c) for c in categories]
if ttl is not None:
# Force ints to unicode
ttl = force_text(ttl)
item = {
'title': to_unicode(title),
'link': iri_to_uri(link),
'description': to_unicode(description),
'author_email': to_unicode(author_email),
'author_name': to_unicode(author_name),
'author_link': iri_to_uri(author_link),
'pubdate': pubdate,
'comments': comments,
'unique_id': to_unicode(unique_id),
'enclosure': enclosure,
'categories': categories or (),
'item_copyright': to_unicode(item_copyright),
'ttl': ttl,
}
item.update(kwargs)
self.items.append(item) | [
"def",
"add_item",
"(",
"self",
",",
"title",
",",
"link",
",",
"description",
",",
"author_email",
"=",
"None",
",",
"author_name",
"=",
"None",
",",
"author_link",
"=",
"None",
",",
"pubdate",
"=",
"None",
",",
"comments",
"=",
"None",
",",
"unique_id"... | Adds an item to the feed. All args are expected to be Python Unicode
objects except pubdate, which is a datetime.datetime object, and
enclosure, which is an instance of the Enclosure class. | [
"Adds",
"an",
"item",
"to",
"the",
"feed",
".",
"All",
"args",
"are",
"expected",
"to",
"be",
"Python",
"Unicode",
"objects",
"except",
"pubdate",
"which",
"is",
"a",
"datetime",
".",
"datetime",
"object",
"and",
"enclosure",
"which",
"is",
"an",
"instance... | 0db52c240906c6663189c0a7aca9979a0db004d1 | https://github.com/arthurk/django-disqus/blob/0db52c240906c6663189c0a7aca9979a0db004d1/disqus/wxr_feed.py#L31-L62 |
25,431 | arthurk/django-disqus | disqus/__init__.py | call | def call(method, data, post=False):
"""
Calls `method` from the DISQUS API with data either in POST or GET.
Returns deserialized JSON response.
"""
url = "%s%s" % ('http://disqus.com/api/', method)
if post:
# POST request
url += "/"
data = urlencode(data)
else:
# GET request
url += "?%s" % urlencode(data)
data = ''
res = json.load(urlopen(url, data))
if not res['succeeded']:
raise CommandError("'%s' failed: %s\nData: %s" % (method, res['code'], data))
return res['message'] | python | def call(method, data, post=False):
url = "%s%s" % ('http://disqus.com/api/', method)
if post:
# POST request
url += "/"
data = urlencode(data)
else:
# GET request
url += "?%s" % urlencode(data)
data = ''
res = json.load(urlopen(url, data))
if not res['succeeded']:
raise CommandError("'%s' failed: %s\nData: %s" % (method, res['code'], data))
return res['message'] | [
"def",
"call",
"(",
"method",
",",
"data",
",",
"post",
"=",
"False",
")",
":",
"url",
"=",
"\"%s%s\"",
"%",
"(",
"'http://disqus.com/api/'",
",",
"method",
")",
"if",
"post",
":",
"# POST request",
"url",
"+=",
"\"/\"",
"data",
"=",
"urlencode",
"(",
... | Calls `method` from the DISQUS API with data either in POST or GET.
Returns deserialized JSON response. | [
"Calls",
"method",
"from",
"the",
"DISQUS",
"API",
"with",
"data",
"either",
"in",
"POST",
"or",
"GET",
".",
"Returns",
"deserialized",
"JSON",
"response",
"."
] | 0db52c240906c6663189c0a7aca9979a0db004d1 | https://github.com/arthurk/django-disqus/blob/0db52c240906c6663189c0a7aca9979a0db004d1/disqus/__init__.py#L8-L25 |
25,432 | arthurk/django-disqus | disqus/management/commands/disqus_export.py | Command._get_comments_to_export | def _get_comments_to_export(self, last_export_id=None):
"""Return comments which should be exported."""
qs = comments.get_model().objects.order_by('pk')\
.filter(is_public=True, is_removed=False)
if last_export_id is not None:
print("Resuming after comment %s" % str(last_export_id))
qs = qs.filter(id__gt=last_export_id)
return qs | python | def _get_comments_to_export(self, last_export_id=None):
qs = comments.get_model().objects.order_by('pk')\
.filter(is_public=True, is_removed=False)
if last_export_id is not None:
print("Resuming after comment %s" % str(last_export_id))
qs = qs.filter(id__gt=last_export_id)
return qs | [
"def",
"_get_comments_to_export",
"(",
"self",
",",
"last_export_id",
"=",
"None",
")",
":",
"qs",
"=",
"comments",
".",
"get_model",
"(",
")",
".",
"objects",
".",
"order_by",
"(",
"'pk'",
")",
".",
"filter",
"(",
"is_public",
"=",
"True",
",",
"is_remo... | Return comments which should be exported. | [
"Return",
"comments",
"which",
"should",
"be",
"exported",
"."
] | 0db52c240906c6663189c0a7aca9979a0db004d1 | https://github.com/arthurk/django-disqus/blob/0db52c240906c6663189c0a7aca9979a0db004d1/disqus/management/commands/disqus_export.py#L32-L39 |
25,433 | arthurk/django-disqus | disqus/management/commands/disqus_export.py | Command._get_last_state | def _get_last_state(self, state_file):
"""Checks the given path for the last exported comment's id"""
state = None
fp = open(state_file)
try:
state = int(fp.read())
print("Found previous state: %d" % (state,))
finally:
fp.close()
return state | python | def _get_last_state(self, state_file):
state = None
fp = open(state_file)
try:
state = int(fp.read())
print("Found previous state: %d" % (state,))
finally:
fp.close()
return state | [
"def",
"_get_last_state",
"(",
"self",
",",
"state_file",
")",
":",
"state",
"=",
"None",
"fp",
"=",
"open",
"(",
"state_file",
")",
"try",
":",
"state",
"=",
"int",
"(",
"fp",
".",
"read",
"(",
")",
")",
"print",
"(",
"\"Found previous state: %d\"",
"... | Checks the given path for the last exported comment's id | [
"Checks",
"the",
"given",
"path",
"for",
"the",
"last",
"exported",
"comment",
"s",
"id"
] | 0db52c240906c6663189c0a7aca9979a0db004d1 | https://github.com/arthurk/django-disqus/blob/0db52c240906c6663189c0a7aca9979a0db004d1/disqus/management/commands/disqus_export.py#L41-L50 |
25,434 | arthurk/django-disqus | disqus/management/commands/disqus_export.py | Command._save_state | def _save_state(self, state_file, last_pk):
"""Saves the last_pk into the given state_file"""
fp = open(state_file, 'w+')
try:
fp.write(str(last_pk))
finally:
fp.close() | python | def _save_state(self, state_file, last_pk):
fp = open(state_file, 'w+')
try:
fp.write(str(last_pk))
finally:
fp.close() | [
"def",
"_save_state",
"(",
"self",
",",
"state_file",
",",
"last_pk",
")",
":",
"fp",
"=",
"open",
"(",
"state_file",
",",
"'w+'",
")",
"try",
":",
"fp",
".",
"write",
"(",
"str",
"(",
"last_pk",
")",
")",
"finally",
":",
"fp",
".",
"close",
"(",
... | Saves the last_pk into the given state_file | [
"Saves",
"the",
"last_pk",
"into",
"the",
"given",
"state_file"
] | 0db52c240906c6663189c0a7aca9979a0db004d1 | https://github.com/arthurk/django-disqus/blob/0db52c240906c6663189c0a7aca9979a0db004d1/disqus/management/commands/disqus_export.py#L52-L58 |
25,435 | arthurk/django-disqus | disqus/api.py | DisqusClient._get_request | def _get_request(self, request_url, request_method, **params):
"""
Return a Request object that has the GET parameters
attached to the url or the POST data attached to the object.
"""
if request_method == 'GET':
if params:
request_url += '&%s' % urlencode(params)
request = Request(request_url)
elif request_method == 'POST':
request = Request(request_url, urlencode(params, doseq=1))
return request | python | def _get_request(self, request_url, request_method, **params):
if request_method == 'GET':
if params:
request_url += '&%s' % urlencode(params)
request = Request(request_url)
elif request_method == 'POST':
request = Request(request_url, urlencode(params, doseq=1))
return request | [
"def",
"_get_request",
"(",
"self",
",",
"request_url",
",",
"request_method",
",",
"*",
"*",
"params",
")",
":",
"if",
"request_method",
"==",
"'GET'",
":",
"if",
"params",
":",
"request_url",
"+=",
"'&%s'",
"%",
"urlencode",
"(",
"params",
")",
"request"... | Return a Request object that has the GET parameters
attached to the url or the POST data attached to the object. | [
"Return",
"a",
"Request",
"object",
"that",
"has",
"the",
"GET",
"parameters",
"attached",
"to",
"the",
"url",
"or",
"the",
"POST",
"data",
"attached",
"to",
"the",
"object",
"."
] | 0db52c240906c6663189c0a7aca9979a0db004d1 | https://github.com/arthurk/django-disqus/blob/0db52c240906c6663189c0a7aca9979a0db004d1/disqus/api.py#L65-L76 |
25,436 | arthurk/django-disqus | disqus/api.py | DisqusClient.call | def call(self, method, **params):
"""
Call the DISQUS API and return the json response.
URLError is raised when the request failed.
DisqusException is raised when the query didn't succeed.
"""
url = self.api_url % method
request = self._get_request(url, self.METHODS[method], **params)
try:
response = urlopen(request)
except URLError:
raise
else:
response_json = json.loads(response.read())
if not response_json['succeeded']:
raise DisqusException(response_json['message'])
return response_json['message'] | python | def call(self, method, **params):
url = self.api_url % method
request = self._get_request(url, self.METHODS[method], **params)
try:
response = urlopen(request)
except URLError:
raise
else:
response_json = json.loads(response.read())
if not response_json['succeeded']:
raise DisqusException(response_json['message'])
return response_json['message'] | [
"def",
"call",
"(",
"self",
",",
"method",
",",
"*",
"*",
"params",
")",
":",
"url",
"=",
"self",
".",
"api_url",
"%",
"method",
"request",
"=",
"self",
".",
"_get_request",
"(",
"url",
",",
"self",
".",
"METHODS",
"[",
"method",
"]",
",",
"*",
"... | Call the DISQUS API and return the json response.
URLError is raised when the request failed.
DisqusException is raised when the query didn't succeed. | [
"Call",
"the",
"DISQUS",
"API",
"and",
"return",
"the",
"json",
"response",
".",
"URLError",
"is",
"raised",
"when",
"the",
"request",
"failed",
".",
"DisqusException",
"is",
"raised",
"when",
"the",
"query",
"didn",
"t",
"succeed",
"."
] | 0db52c240906c6663189c0a7aca9979a0db004d1 | https://github.com/arthurk/django-disqus/blob/0db52c240906c6663189c0a7aca9979a0db004d1/disqus/api.py#L78-L94 |
25,437 | lavr/flask-emails | flask_emails/message.py | init_app | def init_app(app):
"""
'Initialize' flask application.
It creates EmailsConfig object and saves it in app.extensions.
You don't have to call this method directly.
:param app: Flask application object
:return: Just created :meth:`~EmailsConfig` object
"""
config = EmailsConfig(app)
# register extension with app
app.extensions = getattr(app, 'extensions', {})
app.extensions['emails'] = config
return config | python | def init_app(app):
config = EmailsConfig(app)
# register extension with app
app.extensions = getattr(app, 'extensions', {})
app.extensions['emails'] = config
return config | [
"def",
"init_app",
"(",
"app",
")",
":",
"config",
"=",
"EmailsConfig",
"(",
"app",
")",
"# register extension with app",
"app",
".",
"extensions",
"=",
"getattr",
"(",
"app",
",",
"'extensions'",
",",
"{",
"}",
")",
"app",
".",
"extensions",
"[",
"'emails... | 'Initialize' flask application.
It creates EmailsConfig object and saves it in app.extensions.
You don't have to call this method directly.
:param app: Flask application object
:return: Just created :meth:`~EmailsConfig` object | [
"Initialize",
"flask",
"application",
".",
"It",
"creates",
"EmailsConfig",
"object",
"and",
"saves",
"it",
"in",
"app",
".",
"extensions",
"."
] | a1a47108ce7d109fe6c32b6f967445e62f7e5ef6 | https://github.com/lavr/flask-emails/blob/a1a47108ce7d109fe6c32b6f967445e62f7e5ef6/flask_emails/message.py#L9-L23 |
25,438 | lavr/flask-emails | flask_emails/message.py | Message.send | def send(self, smtp=None, **kw):
"""
Sends message.
:param smtp: When set, parameters from this dictionary overwrite
options from config. See `emails.Message.send` for more information.
:param kwargs: Parameters for `emails.Message.send`
:return: Response objects from emails backend.
For default `emails.backend.smtp.STMPBackend` returns an `emails.backend.smtp.SMTPResponse` object.
"""
smtp_options = {}
smtp_options.update(self.config.smtp_options)
if smtp:
smtp_options.update(smtp)
return super(Message, self).send(smtp=smtp_options, **kw) | python | def send(self, smtp=None, **kw):
smtp_options = {}
smtp_options.update(self.config.smtp_options)
if smtp:
smtp_options.update(smtp)
return super(Message, self).send(smtp=smtp_options, **kw) | [
"def",
"send",
"(",
"self",
",",
"smtp",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"smtp_options",
"=",
"{",
"}",
"smtp_options",
".",
"update",
"(",
"self",
".",
"config",
".",
"smtp_options",
")",
"if",
"smtp",
":",
"smtp_options",
".",
"update",... | Sends message.
:param smtp: When set, parameters from this dictionary overwrite
options from config. See `emails.Message.send` for more information.
:param kwargs: Parameters for `emails.Message.send`
:return: Response objects from emails backend.
For default `emails.backend.smtp.STMPBackend` returns an `emails.backend.smtp.SMTPResponse` object. | [
"Sends",
"message",
"."
] | a1a47108ce7d109fe6c32b6f967445e62f7e5ef6 | https://github.com/lavr/flask-emails/blob/a1a47108ce7d109fe6c32b6f967445e62f7e5ef6/flask_emails/message.py#L47-L63 |
25,439 | lavr/flask-emails | flask_emails/config.py | EmailsConfig.options | def options(self):
"""
Reads all EMAIL_ options and set default values.
"""
config = self._config
o = {}
o.update(self._default_smtp_options)
o.update(self._default_message_options)
o.update(self._default_backend_options)
o.update(get_namespace(config, 'EMAIL_', valid_keys=o.keys()))
o['port'] = int(o['port'])
o['timeout'] = float(o['timeout'])
return o | python | def options(self):
config = self._config
o = {}
o.update(self._default_smtp_options)
o.update(self._default_message_options)
o.update(self._default_backend_options)
o.update(get_namespace(config, 'EMAIL_', valid_keys=o.keys()))
o['port'] = int(o['port'])
o['timeout'] = float(o['timeout'])
return o | [
"def",
"options",
"(",
"self",
")",
":",
"config",
"=",
"self",
".",
"_config",
"o",
"=",
"{",
"}",
"o",
".",
"update",
"(",
"self",
".",
"_default_smtp_options",
")",
"o",
".",
"update",
"(",
"self",
".",
"_default_message_options",
")",
"o",
".",
"... | Reads all EMAIL_ options and set default values. | [
"Reads",
"all",
"EMAIL_",
"options",
"and",
"set",
"default",
"values",
"."
] | a1a47108ce7d109fe6c32b6f967445e62f7e5ef6 | https://github.com/lavr/flask-emails/blob/a1a47108ce7d109fe6c32b6f967445e62f7e5ef6/flask_emails/config.py#L109-L121 |
25,440 | lavr/flask-emails | flask_emails/config.py | EmailsConfig.smtp_options | def smtp_options(self):
"""
Convert config namespace to emails.backend.SMTPBackend namespace
Returns dict for SMTPFactory
"""
o = {}
options = self.options
for key in self._default_smtp_options:
if key in options:
o[key] = options[key]
o['user'] = o.pop('host_user', None)
o['password'] = o.pop('host_password', None)
o['tls'] = o.pop('use_tls', False)
o['ssl'] = o.pop('use_ssl', False)
o['debug'] = o.pop('smtp_debug', 0)
for k in ('certfile', 'keyfile'):
v = o.pop('ssl_'+k, None)
if v:
o[k] = v
return o | python | def smtp_options(self):
o = {}
options = self.options
for key in self._default_smtp_options:
if key in options:
o[key] = options[key]
o['user'] = o.pop('host_user', None)
o['password'] = o.pop('host_password', None)
o['tls'] = o.pop('use_tls', False)
o['ssl'] = o.pop('use_ssl', False)
o['debug'] = o.pop('smtp_debug', 0)
for k in ('certfile', 'keyfile'):
v = o.pop('ssl_'+k, None)
if v:
o[k] = v
return o | [
"def",
"smtp_options",
"(",
"self",
")",
":",
"o",
"=",
"{",
"}",
"options",
"=",
"self",
".",
"options",
"for",
"key",
"in",
"self",
".",
"_default_smtp_options",
":",
"if",
"key",
"in",
"options",
":",
"o",
"[",
"key",
"]",
"=",
"options",
"[",
"... | Convert config namespace to emails.backend.SMTPBackend namespace
Returns dict for SMTPFactory | [
"Convert",
"config",
"namespace",
"to",
"emails",
".",
"backend",
".",
"SMTPBackend",
"namespace",
"Returns",
"dict",
"for",
"SMTPFactory"
] | a1a47108ce7d109fe6c32b6f967445e62f7e5ef6 | https://github.com/lavr/flask-emails/blob/a1a47108ce7d109fe6c32b6f967445e62f7e5ef6/flask_emails/config.py#L124-L144 |
25,441 | lavr/flask-emails | flask_emails/config.py | EmailsConfig.message_options | def message_options(self):
"""
Convert config namespace to emails.Message namespace
"""
o = {}
options = self.options
for key in self._default_message_options:
if key in options:
o[key] = options[key]
return o | python | def message_options(self):
o = {}
options = self.options
for key in self._default_message_options:
if key in options:
o[key] = options[key]
return o | [
"def",
"message_options",
"(",
"self",
")",
":",
"o",
"=",
"{",
"}",
"options",
"=",
"self",
".",
"options",
"for",
"key",
"in",
"self",
".",
"_default_message_options",
":",
"if",
"key",
"in",
"options",
":",
"o",
"[",
"key",
"]",
"=",
"options",
"[... | Convert config namespace to emails.Message namespace | [
"Convert",
"config",
"namespace",
"to",
"emails",
".",
"Message",
"namespace"
] | a1a47108ce7d109fe6c32b6f967445e62f7e5ef6 | https://github.com/lavr/flask-emails/blob/a1a47108ce7d109fe6c32b6f967445e62f7e5ef6/flask_emails/config.py#L147-L156 |
25,442 | acroz/pylivy | livy/session.py | LivySession.start | def start(self) -> None:
"""Create the remote Spark session and wait for it to be ready."""
session = self.client.create_session(
self.kind,
self.proxy_user,
self.jars,
self.py_files,
self.files,
self.driver_memory,
self.driver_cores,
self.executor_memory,
self.executor_cores,
self.num_executors,
self.archives,
self.queue,
self.name,
self.spark_conf,
)
self.session_id = session.session_id
not_ready = {SessionState.NOT_STARTED, SessionState.STARTING}
intervals = polling_intervals([0.1, 0.2, 0.3, 0.5], 1.0)
while self.state in not_ready:
time.sleep(next(intervals)) | python | def start(self) -> None:
session = self.client.create_session(
self.kind,
self.proxy_user,
self.jars,
self.py_files,
self.files,
self.driver_memory,
self.driver_cores,
self.executor_memory,
self.executor_cores,
self.num_executors,
self.archives,
self.queue,
self.name,
self.spark_conf,
)
self.session_id = session.session_id
not_ready = {SessionState.NOT_STARTED, SessionState.STARTING}
intervals = polling_intervals([0.1, 0.2, 0.3, 0.5], 1.0)
while self.state in not_ready:
time.sleep(next(intervals)) | [
"def",
"start",
"(",
"self",
")",
"->",
"None",
":",
"session",
"=",
"self",
".",
"client",
".",
"create_session",
"(",
"self",
".",
"kind",
",",
"self",
".",
"proxy_user",
",",
"self",
".",
"jars",
",",
"self",
".",
"py_files",
",",
"self",
".",
"... | Create the remote Spark session and wait for it to be ready. | [
"Create",
"the",
"remote",
"Spark",
"session",
"and",
"wait",
"for",
"it",
"to",
"be",
"ready",
"."
] | 14fc65e19434c51ec959c92acb0925b87a6e3569 | https://github.com/acroz/pylivy/blob/14fc65e19434c51ec959c92acb0925b87a6e3569/livy/session.py#L165-L190 |
25,443 | acroz/pylivy | livy/session.py | LivySession.state | def state(self) -> SessionState:
"""The state of the managed Spark session."""
if self.session_id is None:
raise ValueError("session not yet started")
session = self.client.get_session(self.session_id)
if session is None:
raise ValueError("session not found - it may have been shut down")
return session.state | python | def state(self) -> SessionState:
if self.session_id is None:
raise ValueError("session not yet started")
session = self.client.get_session(self.session_id)
if session is None:
raise ValueError("session not found - it may have been shut down")
return session.state | [
"def",
"state",
"(",
"self",
")",
"->",
"SessionState",
":",
"if",
"self",
".",
"session_id",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"session not yet started\"",
")",
"session",
"=",
"self",
".",
"client",
".",
"get_session",
"(",
"self",
".",
"s... | The state of the managed Spark session. | [
"The",
"state",
"of",
"the",
"managed",
"Spark",
"session",
"."
] | 14fc65e19434c51ec959c92acb0925b87a6e3569 | https://github.com/acroz/pylivy/blob/14fc65e19434c51ec959c92acb0925b87a6e3569/livy/session.py#L193-L200 |
25,444 | acroz/pylivy | livy/session.py | LivySession.close | def close(self) -> None:
"""Kill the managed Spark session."""
if self.session_id is not None:
self.client.delete_session(self.session_id)
self.client.close() | python | def close(self) -> None:
if self.session_id is not None:
self.client.delete_session(self.session_id)
self.client.close() | [
"def",
"close",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"session_id",
"is",
"not",
"None",
":",
"self",
".",
"client",
".",
"delete_session",
"(",
"self",
".",
"session_id",
")",
"self",
".",
"client",
".",
"close",
"(",
")"
] | Kill the managed Spark session. | [
"Kill",
"the",
"managed",
"Spark",
"session",
"."
] | 14fc65e19434c51ec959c92acb0925b87a6e3569 | https://github.com/acroz/pylivy/blob/14fc65e19434c51ec959c92acb0925b87a6e3569/livy/session.py#L202-L206 |
25,445 | acroz/pylivy | livy/session.py | LivySession.run | def run(self, code: str) -> Output:
"""Run some code in the managed Spark session.
:param code: The code to run.
"""
output = self._execute(code)
if self.echo and output.text:
print(output.text)
if self.check:
output.raise_for_status()
return output | python | def run(self, code: str) -> Output:
output = self._execute(code)
if self.echo and output.text:
print(output.text)
if self.check:
output.raise_for_status()
return output | [
"def",
"run",
"(",
"self",
",",
"code",
":",
"str",
")",
"->",
"Output",
":",
"output",
"=",
"self",
".",
"_execute",
"(",
"code",
")",
"if",
"self",
".",
"echo",
"and",
"output",
".",
"text",
":",
"print",
"(",
"output",
".",
"text",
")",
"if",
... | Run some code in the managed Spark session.
:param code: The code to run. | [
"Run",
"some",
"code",
"in",
"the",
"managed",
"Spark",
"session",
"."
] | 14fc65e19434c51ec959c92acb0925b87a6e3569 | https://github.com/acroz/pylivy/blob/14fc65e19434c51ec959c92acb0925b87a6e3569/livy/session.py#L208-L218 |
25,446 | acroz/pylivy | livy/session.py | LivySession.read | def read(self, dataframe_name: str) -> pandas.DataFrame:
"""Evaluate and retrieve a Spark dataframe in the managed session.
:param dataframe_name: The name of the Spark dataframe to read.
"""
code = serialise_dataframe_code(dataframe_name, self.kind)
output = self._execute(code)
output.raise_for_status()
if output.text is None:
raise RuntimeError("statement had no text output")
return deserialise_dataframe(output.text) | python | def read(self, dataframe_name: str) -> pandas.DataFrame:
code = serialise_dataframe_code(dataframe_name, self.kind)
output = self._execute(code)
output.raise_for_status()
if output.text is None:
raise RuntimeError("statement had no text output")
return deserialise_dataframe(output.text) | [
"def",
"read",
"(",
"self",
",",
"dataframe_name",
":",
"str",
")",
"->",
"pandas",
".",
"DataFrame",
":",
"code",
"=",
"serialise_dataframe_code",
"(",
"dataframe_name",
",",
"self",
".",
"kind",
")",
"output",
"=",
"self",
".",
"_execute",
"(",
"code",
... | Evaluate and retrieve a Spark dataframe in the managed session.
:param dataframe_name: The name of the Spark dataframe to read. | [
"Evaluate",
"and",
"retrieve",
"a",
"Spark",
"dataframe",
"in",
"the",
"managed",
"session",
"."
] | 14fc65e19434c51ec959c92acb0925b87a6e3569 | https://github.com/acroz/pylivy/blob/14fc65e19434c51ec959c92acb0925b87a6e3569/livy/session.py#L220-L230 |
25,447 | acroz/pylivy | livy/session.py | LivySession.read_sql | def read_sql(self, code: str) -> pandas.DataFrame:
"""Evaluate a Spark SQL satatement and retrieve the result.
:param code: The Spark SQL statement to evaluate.
"""
if self.kind != SessionKind.SQL:
raise ValueError("not a SQL session")
output = self._execute(code)
output.raise_for_status()
if output.json is None:
raise RuntimeError("statement had no JSON output")
return dataframe_from_json_output(output.json) | python | def read_sql(self, code: str) -> pandas.DataFrame:
if self.kind != SessionKind.SQL:
raise ValueError("not a SQL session")
output = self._execute(code)
output.raise_for_status()
if output.json is None:
raise RuntimeError("statement had no JSON output")
return dataframe_from_json_output(output.json) | [
"def",
"read_sql",
"(",
"self",
",",
"code",
":",
"str",
")",
"->",
"pandas",
".",
"DataFrame",
":",
"if",
"self",
".",
"kind",
"!=",
"SessionKind",
".",
"SQL",
":",
"raise",
"ValueError",
"(",
"\"not a SQL session\"",
")",
"output",
"=",
"self",
".",
... | Evaluate a Spark SQL satatement and retrieve the result.
:param code: The Spark SQL statement to evaluate. | [
"Evaluate",
"a",
"Spark",
"SQL",
"satatement",
"and",
"retrieve",
"the",
"result",
"."
] | 14fc65e19434c51ec959c92acb0925b87a6e3569 | https://github.com/acroz/pylivy/blob/14fc65e19434c51ec959c92acb0925b87a6e3569/livy/session.py#L232-L243 |
25,448 | acroz/pylivy | livy/client.py | LivyClient.server_version | def server_version(self) -> Version:
"""Get the version of Livy running on the server."""
if self._server_version_cache is None:
data = self._client.get("/version")
self._server_version_cache = Version(data["version"])
return self._server_version_cache | python | def server_version(self) -> Version:
if self._server_version_cache is None:
data = self._client.get("/version")
self._server_version_cache = Version(data["version"])
return self._server_version_cache | [
"def",
"server_version",
"(",
"self",
")",
"->",
"Version",
":",
"if",
"self",
".",
"_server_version_cache",
"is",
"None",
":",
"data",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"\"/version\"",
")",
"self",
".",
"_server_version_cache",
"=",
"Version",
... | Get the version of Livy running on the server. | [
"Get",
"the",
"version",
"of",
"Livy",
"running",
"on",
"the",
"server",
"."
] | 14fc65e19434c51ec959c92acb0925b87a6e3569 | https://github.com/acroz/pylivy/blob/14fc65e19434c51ec959c92acb0925b87a6e3569/livy/client.py#L78-L83 |
25,449 | acroz/pylivy | livy/client.py | LivyClient.list_sessions | def list_sessions(self) -> List[Session]:
"""List all the active sessions in Livy."""
data = self._client.get("/sessions")
return [Session.from_json(item) for item in data["sessions"]] | python | def list_sessions(self) -> List[Session]:
data = self._client.get("/sessions")
return [Session.from_json(item) for item in data["sessions"]] | [
"def",
"list_sessions",
"(",
"self",
")",
"->",
"List",
"[",
"Session",
"]",
":",
"data",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"\"/sessions\"",
")",
"return",
"[",
"Session",
".",
"from_json",
"(",
"item",
")",
"for",
"item",
"in",
"data",
"... | List all the active sessions in Livy. | [
"List",
"all",
"the",
"active",
"sessions",
"in",
"Livy",
"."
] | 14fc65e19434c51ec959c92acb0925b87a6e3569 | https://github.com/acroz/pylivy/blob/14fc65e19434c51ec959c92acb0925b87a6e3569/livy/client.py#L94-L97 |
25,450 | acroz/pylivy | livy/client.py | LivyClient.create_session | def create_session(
self,
kind: SessionKind,
proxy_user: str = None,
jars: List[str] = None,
py_files: List[str] = None,
files: List[str] = None,
driver_memory: str = None,
driver_cores: int = None,
executor_memory: str = None,
executor_cores: int = None,
num_executors: int = None,
archives: List[str] = None,
queue: str = None,
name: str = None,
spark_conf: Dict[str, Any] = None,
) -> Session:
"""Create a new session in Livy.
The py_files, files, jars and archives arguments are lists of URLs,
e.g. ["s3://bucket/object", "hdfs://path/to/file", ...] and must be
reachable by the Spark driver process. If the provided URL has no
scheme, it's considered to be relative to the default file system
configured in the Livy server.
URLs in the py_files argument are copied to a temporary staging area
and inserted into Python's sys.path ahead of the standard library
paths. This allows you to import .py, .zip and .egg files in Python.
URLs for jars, py_files, files and archives arguments are all copied
to the same working directory on the Spark cluster.
The driver_memory and executor_memory arguments have the same format
as JVM memory strings with a size unit suffix ("k", "m", "g" or "t")
(e.g. 512m, 2g).
See https://spark.apache.org/docs/latest/configuration.html for more
information on Spark configuration properties.
:param kind: The kind of session to create.
:param proxy_user: User to impersonate when starting the session.
:param jars: URLs of jars to be used in this session.
:param py_files: URLs of Python files to be used in this session.
:param files: URLs of files to be used in this session.
:param driver_memory: Amount of memory to use for the driver process
(e.g. '512m').
:param driver_cores: Number of cores to use for the driver process.
:param executor_memory: Amount of memory to use per executor process
(e.g. '512m').
:param executor_cores: Number of cores to use for each executor.
:param num_executors: Number of executors to launch for this session.
:param archives: URLs of archives to be used in this session.
:param queue: The name of the YARN queue to which submitted.
:param name: The name of this session.
:param spark_conf: Spark configuration properties.
"""
if self.legacy_server():
valid_kinds = VALID_LEGACY_SESSION_KINDS
else:
valid_kinds = VALID_SESSION_KINDS
if kind not in valid_kinds:
raise ValueError(
f"{kind} is not a valid session kind for a Livy server of "
f"this version (should be one of {valid_kinds})"
)
body = {"kind": kind.value}
if proxy_user is not None:
body["proxyUser"] = proxy_user
if jars is not None:
body["jars"] = jars
if py_files is not None:
body["pyFiles"] = py_files
if files is not None:
body["files"] = files
if driver_memory is not None:
body["driverMemory"] = driver_memory
if driver_cores is not None:
body["driverCores"] = driver_cores
if executor_memory is not None:
body["executorMemory"] = executor_memory
if executor_cores is not None:
body["executorCores"] = executor_cores
if num_executors is not None:
body["numExecutors"] = num_executors
if archives is not None:
body["archives"] = archives
if queue is not None:
body["queue"] = queue
if name is not None:
body["name"] = name
if spark_conf is not None:
body["conf"] = spark_conf
data = self._client.post("/sessions", data=body)
return Session.from_json(data) | python | def create_session(
self,
kind: SessionKind,
proxy_user: str = None,
jars: List[str] = None,
py_files: List[str] = None,
files: List[str] = None,
driver_memory: str = None,
driver_cores: int = None,
executor_memory: str = None,
executor_cores: int = None,
num_executors: int = None,
archives: List[str] = None,
queue: str = None,
name: str = None,
spark_conf: Dict[str, Any] = None,
) -> Session:
if self.legacy_server():
valid_kinds = VALID_LEGACY_SESSION_KINDS
else:
valid_kinds = VALID_SESSION_KINDS
if kind not in valid_kinds:
raise ValueError(
f"{kind} is not a valid session kind for a Livy server of "
f"this version (should be one of {valid_kinds})"
)
body = {"kind": kind.value}
if proxy_user is not None:
body["proxyUser"] = proxy_user
if jars is not None:
body["jars"] = jars
if py_files is not None:
body["pyFiles"] = py_files
if files is not None:
body["files"] = files
if driver_memory is not None:
body["driverMemory"] = driver_memory
if driver_cores is not None:
body["driverCores"] = driver_cores
if executor_memory is not None:
body["executorMemory"] = executor_memory
if executor_cores is not None:
body["executorCores"] = executor_cores
if num_executors is not None:
body["numExecutors"] = num_executors
if archives is not None:
body["archives"] = archives
if queue is not None:
body["queue"] = queue
if name is not None:
body["name"] = name
if spark_conf is not None:
body["conf"] = spark_conf
data = self._client.post("/sessions", data=body)
return Session.from_json(data) | [
"def",
"create_session",
"(",
"self",
",",
"kind",
":",
"SessionKind",
",",
"proxy_user",
":",
"str",
"=",
"None",
",",
"jars",
":",
"List",
"[",
"str",
"]",
"=",
"None",
",",
"py_files",
":",
"List",
"[",
"str",
"]",
"=",
"None",
",",
"files",
":"... | Create a new session in Livy.
The py_files, files, jars and archives arguments are lists of URLs,
e.g. ["s3://bucket/object", "hdfs://path/to/file", ...] and must be
reachable by the Spark driver process. If the provided URL has no
scheme, it's considered to be relative to the default file system
configured in the Livy server.
URLs in the py_files argument are copied to a temporary staging area
and inserted into Python's sys.path ahead of the standard library
paths. This allows you to import .py, .zip and .egg files in Python.
URLs for jars, py_files, files and archives arguments are all copied
to the same working directory on the Spark cluster.
The driver_memory and executor_memory arguments have the same format
as JVM memory strings with a size unit suffix ("k", "m", "g" or "t")
(e.g. 512m, 2g).
See https://spark.apache.org/docs/latest/configuration.html for more
information on Spark configuration properties.
:param kind: The kind of session to create.
:param proxy_user: User to impersonate when starting the session.
:param jars: URLs of jars to be used in this session.
:param py_files: URLs of Python files to be used in this session.
:param files: URLs of files to be used in this session.
:param driver_memory: Amount of memory to use for the driver process
(e.g. '512m').
:param driver_cores: Number of cores to use for the driver process.
:param executor_memory: Amount of memory to use per executor process
(e.g. '512m').
:param executor_cores: Number of cores to use for each executor.
:param num_executors: Number of executors to launch for this session.
:param archives: URLs of archives to be used in this session.
:param queue: The name of the YARN queue to which submitted.
:param name: The name of this session.
:param spark_conf: Spark configuration properties. | [
"Create",
"a",
"new",
"session",
"in",
"Livy",
"."
] | 14fc65e19434c51ec959c92acb0925b87a6e3569 | https://github.com/acroz/pylivy/blob/14fc65e19434c51ec959c92acb0925b87a6e3569/livy/client.py#L99-L195 |
25,451 | acroz/pylivy | livy/client.py | LivyClient.list_statements | def list_statements(self, session_id: int) -> List[Statement]:
"""Get all the statements in a session.
:param session_id: The ID of the session.
"""
response = self._client.get(f"/sessions/{session_id}/statements")
return [
Statement.from_json(session_id, data)
for data in response["statements"]
] | python | def list_statements(self, session_id: int) -> List[Statement]:
response = self._client.get(f"/sessions/{session_id}/statements")
return [
Statement.from_json(session_id, data)
for data in response["statements"]
] | [
"def",
"list_statements",
"(",
"self",
",",
"session_id",
":",
"int",
")",
"->",
"List",
"[",
"Statement",
"]",
":",
"response",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"f\"/sessions/{session_id}/statements\"",
")",
"return",
"[",
"Statement",
".",
"fr... | Get all the statements in a session.
:param session_id: The ID of the session. | [
"Get",
"all",
"the",
"statements",
"in",
"a",
"session",
"."
] | 14fc65e19434c51ec959c92acb0925b87a6e3569 | https://github.com/acroz/pylivy/blob/14fc65e19434c51ec959c92acb0925b87a6e3569/livy/client.py#L218-L227 |
25,452 | acroz/pylivy | livy/client.py | LivyClient.create_statement | def create_statement(
self, session_id: int, code: str, kind: StatementKind = None
) -> Statement:
"""Run a statement in a session.
:param session_id: The ID of the session.
:param code: The code to execute.
:param kind: The kind of code to execute.
"""
data = {"code": code}
if kind is not None:
if self.legacy_server():
LOGGER.warning("statement kind ignored on Livy<0.5.0")
data["kind"] = kind.value
response = self._client.post(
f"/sessions/{session_id}/statements", data=data
)
return Statement.from_json(session_id, response) | python | def create_statement(
self, session_id: int, code: str, kind: StatementKind = None
) -> Statement:
data = {"code": code}
if kind is not None:
if self.legacy_server():
LOGGER.warning("statement kind ignored on Livy<0.5.0")
data["kind"] = kind.value
response = self._client.post(
f"/sessions/{session_id}/statements", data=data
)
return Statement.from_json(session_id, response) | [
"def",
"create_statement",
"(",
"self",
",",
"session_id",
":",
"int",
",",
"code",
":",
"str",
",",
"kind",
":",
"StatementKind",
"=",
"None",
")",
"->",
"Statement",
":",
"data",
"=",
"{",
"\"code\"",
":",
"code",
"}",
"if",
"kind",
"is",
"not",
"N... | Run a statement in a session.
:param session_id: The ID of the session.
:param code: The code to execute.
:param kind: The kind of code to execute. | [
"Run",
"a",
"statement",
"in",
"a",
"session",
"."
] | 14fc65e19434c51ec959c92acb0925b87a6e3569 | https://github.com/acroz/pylivy/blob/14fc65e19434c51ec959c92acb0925b87a6e3569/livy/client.py#L229-L249 |
25,453 | acroz/pylivy | livy/client.py | LivyClient.get_statement | def get_statement(self, session_id: int, statement_id: int) -> Statement:
"""Get information about a statement in a session.
:param session_id: The ID of the session.
:param statement_id: The ID of the statement.
"""
response = self._client.get(
f"/sessions/{session_id}/statements/{statement_id}"
)
return Statement.from_json(session_id, response) | python | def get_statement(self, session_id: int, statement_id: int) -> Statement:
response = self._client.get(
f"/sessions/{session_id}/statements/{statement_id}"
)
return Statement.from_json(session_id, response) | [
"def",
"get_statement",
"(",
"self",
",",
"session_id",
":",
"int",
",",
"statement_id",
":",
"int",
")",
"->",
"Statement",
":",
"response",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"f\"/sessions/{session_id}/statements/{statement_id}\"",
")",
"return",
"S... | Get information about a statement in a session.
:param session_id: The ID of the session.
:param statement_id: The ID of the statement. | [
"Get",
"information",
"about",
"a",
"statement",
"in",
"a",
"session",
"."
] | 14fc65e19434c51ec959c92acb0925b87a6e3569 | https://github.com/acroz/pylivy/blob/14fc65e19434c51ec959c92acb0925b87a6e3569/livy/client.py#L251-L260 |
25,454 | xflr6/concepts | concepts/visualize.py | lattice | def lattice(lattice, filename, directory, render, view, **kwargs):
"""Return graphviz source for visualizing the lattice graph."""
dot = graphviz.Digraph(
name=lattice.__class__.__name__,
comment=repr(lattice),
filename=filename,
directory=directory,
node_attr=dict(shape='circle', width='.25', style='filled', label=''),
edge_attr=dict(dir='none', labeldistance='1.5', minlen='2'),
**kwargs
)
sortkey = SORTKEYS[0]
node_name = NAME_GETTERS[0]
for concept in lattice._concepts:
name = node_name(concept)
dot.node(name)
if concept.objects:
dot.edge(name, name,
headlabel=' '.join(concept.objects),
labelangle='270', color='transparent')
if concept.properties:
dot.edge(name, name,
taillabel=' '.join(concept.properties),
labelangle='90', color='transparent')
dot.edges((name, node_name(c))
for c in sorted(concept.lower_neighbors, key=sortkey))
if render or view:
dot.render(view=view) # pragma: no cover
return dot | python | def lattice(lattice, filename, directory, render, view, **kwargs):
dot = graphviz.Digraph(
name=lattice.__class__.__name__,
comment=repr(lattice),
filename=filename,
directory=directory,
node_attr=dict(shape='circle', width='.25', style='filled', label=''),
edge_attr=dict(dir='none', labeldistance='1.5', minlen='2'),
**kwargs
)
sortkey = SORTKEYS[0]
node_name = NAME_GETTERS[0]
for concept in lattice._concepts:
name = node_name(concept)
dot.node(name)
if concept.objects:
dot.edge(name, name,
headlabel=' '.join(concept.objects),
labelangle='270', color='transparent')
if concept.properties:
dot.edge(name, name,
taillabel=' '.join(concept.properties),
labelangle='90', color='transparent')
dot.edges((name, node_name(c))
for c in sorted(concept.lower_neighbors, key=sortkey))
if render or view:
dot.render(view=view) # pragma: no cover
return dot | [
"def",
"lattice",
"(",
"lattice",
",",
"filename",
",",
"directory",
",",
"render",
",",
"view",
",",
"*",
"*",
"kwargs",
")",
":",
"dot",
"=",
"graphviz",
".",
"Digraph",
"(",
"name",
"=",
"lattice",
".",
"__class__",
".",
"__name__",
",",
"comment",
... | Return graphviz source for visualizing the lattice graph. | [
"Return",
"graphviz",
"source",
"for",
"visualizing",
"the",
"lattice",
"graph",
"."
] | 2801b27b05fa02cccee7d549451810ffcbf5c942 | https://github.com/xflr6/concepts/blob/2801b27b05fa02cccee7d549451810ffcbf5c942/concepts/visualize.py#L15-L50 |
25,455 | xflr6/concepts | concepts/formats.py | Format.load | def load(cls, filename, encoding):
"""Load and parse serialized objects, properties, bools from file."""
if encoding is None:
encoding = cls.encoding
with io.open(filename, 'r', encoding=encoding) as fd:
source = fd.read()
if cls.normalize_newlines:
source = source.replace('\r\n', '\n').replace('\r', '\n')
return cls.loads(source) | python | def load(cls, filename, encoding):
if encoding is None:
encoding = cls.encoding
with io.open(filename, 'r', encoding=encoding) as fd:
source = fd.read()
if cls.normalize_newlines:
source = source.replace('\r\n', '\n').replace('\r', '\n')
return cls.loads(source) | [
"def",
"load",
"(",
"cls",
",",
"filename",
",",
"encoding",
")",
":",
"if",
"encoding",
"is",
"None",
":",
"encoding",
"=",
"cls",
".",
"encoding",
"with",
"io",
".",
"open",
"(",
"filename",
",",
"'r'",
",",
"encoding",
"=",
"encoding",
")",
"as",
... | Load and parse serialized objects, properties, bools from file. | [
"Load",
"and",
"parse",
"serialized",
"objects",
"properties",
"bools",
"from",
"file",
"."
] | 2801b27b05fa02cccee7d549451810ffcbf5c942 | https://github.com/xflr6/concepts/blob/2801b27b05fa02cccee7d549451810ffcbf5c942/concepts/formats.py#L67-L77 |
25,456 | xflr6/concepts | concepts/formats.py | Format.dump | def dump(cls, filename, objects, properties, bools, encoding):
"""Write serialized objects, properties, bools to file."""
if encoding is None:
encoding = cls.encoding
source = cls.dumps(objects, properties, bools)
if PY2:
source = unicode(source)
with io.open(filename, 'w', encoding=encoding) as fd:
fd.write(source) | python | def dump(cls, filename, objects, properties, bools, encoding):
if encoding is None:
encoding = cls.encoding
source = cls.dumps(objects, properties, bools)
if PY2:
source = unicode(source)
with io.open(filename, 'w', encoding=encoding) as fd:
fd.write(source) | [
"def",
"dump",
"(",
"cls",
",",
"filename",
",",
"objects",
",",
"properties",
",",
"bools",
",",
"encoding",
")",
":",
"if",
"encoding",
"is",
"None",
":",
"encoding",
"=",
"cls",
".",
"encoding",
"source",
"=",
"cls",
".",
"dumps",
"(",
"objects",
... | Write serialized objects, properties, bools to file. | [
"Write",
"serialized",
"objects",
"properties",
"bools",
"to",
"file",
"."
] | 2801b27b05fa02cccee7d549451810ffcbf5c942 | https://github.com/xflr6/concepts/blob/2801b27b05fa02cccee7d549451810ffcbf5c942/concepts/formats.py#L80-L90 |
25,457 | xflr6/concepts | concepts/__init__.py | load_csv | def load_csv(filename, dialect='excel', encoding='utf-8'):
"""Load and return formal context from CSV file.
Args:
filename: Path to the CSV file to load the context from.
dialect: Syntax variant of the CSV file (``'excel'``, ``'excel-tab'``).
encoding (str): Encoding of the file (``'utf-8'``, ``'latin1'``, ``'ascii'``, ...).
Example:
>>> load_csv('examples/vowels.csv') # doctest: +ELLIPSIS
<Context object mapping 12 objects to 8 properties [a717eee4] at 0x...>
"""
return Context.fromfile(filename, 'csv', encoding, dialect=dialect) | python | def load_csv(filename, dialect='excel', encoding='utf-8'):
return Context.fromfile(filename, 'csv', encoding, dialect=dialect) | [
"def",
"load_csv",
"(",
"filename",
",",
"dialect",
"=",
"'excel'",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"return",
"Context",
".",
"fromfile",
"(",
"filename",
",",
"'csv'",
",",
"encoding",
",",
"dialect",
"=",
"dialect",
")"
] | Load and return formal context from CSV file.
Args:
filename: Path to the CSV file to load the context from.
dialect: Syntax variant of the CSV file (``'excel'``, ``'excel-tab'``).
encoding (str): Encoding of the file (``'utf-8'``, ``'latin1'``, ``'ascii'``, ...).
Example:
>>> load_csv('examples/vowels.csv') # doctest: +ELLIPSIS
<Context object mapping 12 objects to 8 properties [a717eee4] at 0x...> | [
"Load",
"and",
"return",
"formal",
"context",
"from",
"CSV",
"file",
"."
] | 2801b27b05fa02cccee7d549451810ffcbf5c942 | https://github.com/xflr6/concepts/blob/2801b27b05fa02cccee7d549451810ffcbf5c942/concepts/__init__.py#L61-L73 |
25,458 | xflr6/concepts | concepts/definitions.py | ensure_compatible | def ensure_compatible(left, right):
"""Raise an informative ``ValueError`` if the two definitions disagree."""
conflicts = list(conflicting_pairs(left, right))
if conflicts:
raise ValueError('conflicting values for object/property pairs: %r' % conflicts) | python | def ensure_compatible(left, right):
conflicts = list(conflicting_pairs(left, right))
if conflicts:
raise ValueError('conflicting values for object/property pairs: %r' % conflicts) | [
"def",
"ensure_compatible",
"(",
"left",
",",
"right",
")",
":",
"conflicts",
"=",
"list",
"(",
"conflicting_pairs",
"(",
"left",
",",
"right",
")",
")",
"if",
"conflicts",
":",
"raise",
"ValueError",
"(",
"'conflicting values for object/property pairs: %r'",
"%",... | Raise an informative ``ValueError`` if the two definitions disagree. | [
"Raise",
"an",
"informative",
"ValueError",
"if",
"the",
"two",
"definitions",
"disagree",
"."
] | 2801b27b05fa02cccee7d549451810ffcbf5c942 | https://github.com/xflr6/concepts/blob/2801b27b05fa02cccee7d549451810ffcbf5c942/concepts/definitions.py#L211-L215 |
25,459 | xflr6/concepts | concepts/definitions.py | Definition.rename_object | def rename_object(self, old, new):
"""Replace the name of an object by a new one."""
self._objects.replace(old, new)
pairs = self._pairs
pairs |= {(new, p) for p in self._properties
if (old, p) in pairs and not pairs.remove((old, p))} | python | def rename_object(self, old, new):
self._objects.replace(old, new)
pairs = self._pairs
pairs |= {(new, p) for p in self._properties
if (old, p) in pairs and not pairs.remove((old, p))} | [
"def",
"rename_object",
"(",
"self",
",",
"old",
",",
"new",
")",
":",
"self",
".",
"_objects",
".",
"replace",
"(",
"old",
",",
"new",
")",
"pairs",
"=",
"self",
".",
"_pairs",
"pairs",
"|=",
"{",
"(",
"new",
",",
"p",
")",
"for",
"p",
"in",
"... | Replace the name of an object by a new one. | [
"Replace",
"the",
"name",
"of",
"an",
"object",
"by",
"a",
"new",
"one",
"."
] | 2801b27b05fa02cccee7d549451810ffcbf5c942 | https://github.com/xflr6/concepts/blob/2801b27b05fa02cccee7d549451810ffcbf5c942/concepts/definitions.py#L317-L322 |
25,460 | xflr6/concepts | concepts/definitions.py | Definition.rename_property | def rename_property(self, old, new):
"""Replace the name of a property by a new one."""
self._properties.replace(old, new)
pairs = self._pairs
pairs |= {(o, new) for o in self._objects
if (o, old) in pairs and not pairs.remove((o, old))} | python | def rename_property(self, old, new):
self._properties.replace(old, new)
pairs = self._pairs
pairs |= {(o, new) for o in self._objects
if (o, old) in pairs and not pairs.remove((o, old))} | [
"def",
"rename_property",
"(",
"self",
",",
"old",
",",
"new",
")",
":",
"self",
".",
"_properties",
".",
"replace",
"(",
"old",
",",
"new",
")",
"pairs",
"=",
"self",
".",
"_pairs",
"pairs",
"|=",
"{",
"(",
"o",
",",
"new",
")",
"for",
"o",
"in"... | Replace the name of a property by a new one. | [
"Replace",
"the",
"name",
"of",
"a",
"property",
"by",
"a",
"new",
"one",
"."
] | 2801b27b05fa02cccee7d549451810ffcbf5c942 | https://github.com/xflr6/concepts/blob/2801b27b05fa02cccee7d549451810ffcbf5c942/concepts/definitions.py#L324-L329 |
25,461 | xflr6/concepts | concepts/definitions.py | Definition.add_object | def add_object(self, obj, properties=()):
"""Add an object to the definition and add ``properties`` as related."""
self._objects.add(obj)
self._properties |= properties
self._pairs.update((obj, p) for p in properties) | python | def add_object(self, obj, properties=()):
self._objects.add(obj)
self._properties |= properties
self._pairs.update((obj, p) for p in properties) | [
"def",
"add_object",
"(",
"self",
",",
"obj",
",",
"properties",
"=",
"(",
")",
")",
":",
"self",
".",
"_objects",
".",
"add",
"(",
"obj",
")",
"self",
".",
"_properties",
"|=",
"properties",
"self",
".",
"_pairs",
".",
"update",
"(",
"(",
"obj",
"... | Add an object to the definition and add ``properties`` as related. | [
"Add",
"an",
"object",
"to",
"the",
"definition",
"and",
"add",
"properties",
"as",
"related",
"."
] | 2801b27b05fa02cccee7d549451810ffcbf5c942 | https://github.com/xflr6/concepts/blob/2801b27b05fa02cccee7d549451810ffcbf5c942/concepts/definitions.py#L350-L354 |
25,462 | xflr6/concepts | concepts/definitions.py | Definition.add_property | def add_property(self, prop, objects=()):
"""Add a property to the definition and add ``objects`` as related."""
self._properties.add(prop)
self._objects |= objects
self._pairs.update((o, prop) for o in objects) | python | def add_property(self, prop, objects=()):
self._properties.add(prop)
self._objects |= objects
self._pairs.update((o, prop) for o in objects) | [
"def",
"add_property",
"(",
"self",
",",
"prop",
",",
"objects",
"=",
"(",
")",
")",
":",
"self",
".",
"_properties",
".",
"add",
"(",
"prop",
")",
"self",
".",
"_objects",
"|=",
"objects",
"self",
".",
"_pairs",
".",
"update",
"(",
"(",
"o",
",",
... | Add a property to the definition and add ``objects`` as related. | [
"Add",
"a",
"property",
"to",
"the",
"definition",
"and",
"add",
"objects",
"as",
"related",
"."
] | 2801b27b05fa02cccee7d549451810ffcbf5c942 | https://github.com/xflr6/concepts/blob/2801b27b05fa02cccee7d549451810ffcbf5c942/concepts/definitions.py#L356-L360 |
25,463 | xflr6/concepts | concepts/definitions.py | Definition.remove_object | def remove_object(self, obj):
"""Remove an object from the definition."""
self._objects.remove(obj)
self._pairs.difference_update((obj, p) for p in self._properties) | python | def remove_object(self, obj):
self._objects.remove(obj)
self._pairs.difference_update((obj, p) for p in self._properties) | [
"def",
"remove_object",
"(",
"self",
",",
"obj",
")",
":",
"self",
".",
"_objects",
".",
"remove",
"(",
"obj",
")",
"self",
".",
"_pairs",
".",
"difference_update",
"(",
"(",
"obj",
",",
"p",
")",
"for",
"p",
"in",
"self",
".",
"_properties",
")"
] | Remove an object from the definition. | [
"Remove",
"an",
"object",
"from",
"the",
"definition",
"."
] | 2801b27b05fa02cccee7d549451810ffcbf5c942 | https://github.com/xflr6/concepts/blob/2801b27b05fa02cccee7d549451810ffcbf5c942/concepts/definitions.py#L362-L365 |
25,464 | xflr6/concepts | concepts/definitions.py | Definition.remove_property | def remove_property(self, prop):
"""Remove a property from the definition."""
self._properties.remove(prop)
self._pairs.difference_update((o, prop) for o in self._objects) | python | def remove_property(self, prop):
self._properties.remove(prop)
self._pairs.difference_update((o, prop) for o in self._objects) | [
"def",
"remove_property",
"(",
"self",
",",
"prop",
")",
":",
"self",
".",
"_properties",
".",
"remove",
"(",
"prop",
")",
"self",
".",
"_pairs",
".",
"difference_update",
"(",
"(",
"o",
",",
"prop",
")",
"for",
"o",
"in",
"self",
".",
"_objects",
")... | Remove a property from the definition. | [
"Remove",
"a",
"property",
"from",
"the",
"definition",
"."
] | 2801b27b05fa02cccee7d549451810ffcbf5c942 | https://github.com/xflr6/concepts/blob/2801b27b05fa02cccee7d549451810ffcbf5c942/concepts/definitions.py#L367-L370 |
25,465 | xflr6/concepts | concepts/definitions.py | Definition.set_object | def set_object(self, obj, properties):
"""Add an object to the definition and set its ``properties``."""
self._objects.add(obj)
properties = set(properties)
self._properties |= properties
pairs = self._pairs
for p in self._properties:
if p in properties:
pairs.add((obj, p))
else:
pairs.discard((obj, p)) | python | def set_object(self, obj, properties):
self._objects.add(obj)
properties = set(properties)
self._properties |= properties
pairs = self._pairs
for p in self._properties:
if p in properties:
pairs.add((obj, p))
else:
pairs.discard((obj, p)) | [
"def",
"set_object",
"(",
"self",
",",
"obj",
",",
"properties",
")",
":",
"self",
".",
"_objects",
".",
"add",
"(",
"obj",
")",
"properties",
"=",
"set",
"(",
"properties",
")",
"self",
".",
"_properties",
"|=",
"properties",
"pairs",
"=",
"self",
"."... | Add an object to the definition and set its ``properties``. | [
"Add",
"an",
"object",
"to",
"the",
"definition",
"and",
"set",
"its",
"properties",
"."
] | 2801b27b05fa02cccee7d549451810ffcbf5c942 | https://github.com/xflr6/concepts/blob/2801b27b05fa02cccee7d549451810ffcbf5c942/concepts/definitions.py#L372-L382 |
25,466 | xflr6/concepts | concepts/definitions.py | Definition.set_property | def set_property(self, prop, objects):
"""Add a property to the definition and set its ``objects``."""
self._properties.add(prop)
objects = set(objects)
self._objects |= objects
pairs = self._pairs
for o in self._objects:
if o in objects:
pairs.add((o, prop))
else:
pairs.discard((o, prop)) | python | def set_property(self, prop, objects):
self._properties.add(prop)
objects = set(objects)
self._objects |= objects
pairs = self._pairs
for o in self._objects:
if o in objects:
pairs.add((o, prop))
else:
pairs.discard((o, prop)) | [
"def",
"set_property",
"(",
"self",
",",
"prop",
",",
"objects",
")",
":",
"self",
".",
"_properties",
".",
"add",
"(",
"prop",
")",
"objects",
"=",
"set",
"(",
"objects",
")",
"self",
".",
"_objects",
"|=",
"objects",
"pairs",
"=",
"self",
".",
"_pa... | Add a property to the definition and set its ``objects``. | [
"Add",
"a",
"property",
"to",
"the",
"definition",
"and",
"set",
"its",
"objects",
"."
] | 2801b27b05fa02cccee7d549451810ffcbf5c942 | https://github.com/xflr6/concepts/blob/2801b27b05fa02cccee7d549451810ffcbf5c942/concepts/definitions.py#L384-L394 |
25,467 | xflr6/concepts | concepts/definitions.py | Definition.union_update | def union_update(self, other, ignore_conflicts=False):
"""Update the definition with the union of the ``other``."""
if not ignore_conflicts:
ensure_compatible(self, other)
self._objects |= other._objects
self._properties |= other._properties
self._pairs |= other._pairs | python | def union_update(self, other, ignore_conflicts=False):
if not ignore_conflicts:
ensure_compatible(self, other)
self._objects |= other._objects
self._properties |= other._properties
self._pairs |= other._pairs | [
"def",
"union_update",
"(",
"self",
",",
"other",
",",
"ignore_conflicts",
"=",
"False",
")",
":",
"if",
"not",
"ignore_conflicts",
":",
"ensure_compatible",
"(",
"self",
",",
"other",
")",
"self",
".",
"_objects",
"|=",
"other",
".",
"_objects",
"self",
"... | Update the definition with the union of the ``other``. | [
"Update",
"the",
"definition",
"with",
"the",
"union",
"of",
"the",
"other",
"."
] | 2801b27b05fa02cccee7d549451810ffcbf5c942 | https://github.com/xflr6/concepts/blob/2801b27b05fa02cccee7d549451810ffcbf5c942/concepts/definitions.py#L396-L402 |
25,468 | xflr6/concepts | concepts/definitions.py | Definition.union | def union(self, other, ignore_conflicts=False):
"""Return a new definition from the union of the definitions."""
result = self.copy()
result.union_update(other, ignore_conflicts)
return result | python | def union(self, other, ignore_conflicts=False):
result = self.copy()
result.union_update(other, ignore_conflicts)
return result | [
"def",
"union",
"(",
"self",
",",
"other",
",",
"ignore_conflicts",
"=",
"False",
")",
":",
"result",
"=",
"self",
".",
"copy",
"(",
")",
"result",
".",
"union_update",
"(",
"other",
",",
"ignore_conflicts",
")",
"return",
"result"
] | Return a new definition from the union of the definitions. | [
"Return",
"a",
"new",
"definition",
"from",
"the",
"union",
"of",
"the",
"definitions",
"."
] | 2801b27b05fa02cccee7d549451810ffcbf5c942 | https://github.com/xflr6/concepts/blob/2801b27b05fa02cccee7d549451810ffcbf5c942/concepts/definitions.py#L420-L424 |
25,469 | xflr6/concepts | concepts/definitions.py | Definition.intersection | def intersection(self, other, ignore_conflicts=False):
"""Return a new definition from the intersection of the definitions."""
result = self.copy()
result.intersection_update(other, ignore_conflicts)
return result | python | def intersection(self, other, ignore_conflicts=False):
result = self.copy()
result.intersection_update(other, ignore_conflicts)
return result | [
"def",
"intersection",
"(",
"self",
",",
"other",
",",
"ignore_conflicts",
"=",
"False",
")",
":",
"result",
"=",
"self",
".",
"copy",
"(",
")",
"result",
".",
"intersection_update",
"(",
"other",
",",
"ignore_conflicts",
")",
"return",
"result"
] | Return a new definition from the intersection of the definitions. | [
"Return",
"a",
"new",
"definition",
"from",
"the",
"intersection",
"of",
"the",
"definitions",
"."
] | 2801b27b05fa02cccee7d549451810ffcbf5c942 | https://github.com/xflr6/concepts/blob/2801b27b05fa02cccee7d549451810ffcbf5c942/concepts/definitions.py#L426-L430 |
25,470 | xflr6/concepts | concepts/tools.py | maximal | def maximal(iterable, comparison=operator.lt, _groupkey=operator.itemgetter(0)):
"""Yield the unique maximal elements from ``iterable`` using ``comparison``.
>>> list(maximal([1, 2, 3, 3]))
[3]
>>> list(maximal([1]))
[1]
"""
iterable = set(iterable)
if len(iterable) < 2:
return iterable
return (item for item, pairs
in groupby(permutations(iterable, 2), key=_groupkey)
if not any(starmap(comparison, pairs))) | python | def maximal(iterable, comparison=operator.lt, _groupkey=operator.itemgetter(0)):
iterable = set(iterable)
if len(iterable) < 2:
return iterable
return (item for item, pairs
in groupby(permutations(iterable, 2), key=_groupkey)
if not any(starmap(comparison, pairs))) | [
"def",
"maximal",
"(",
"iterable",
",",
"comparison",
"=",
"operator",
".",
"lt",
",",
"_groupkey",
"=",
"operator",
".",
"itemgetter",
"(",
"0",
")",
")",
":",
"iterable",
"=",
"set",
"(",
"iterable",
")",
"if",
"len",
"(",
"iterable",
")",
"<",
"2"... | Yield the unique maximal elements from ``iterable`` using ``comparison``.
>>> list(maximal([1, 2, 3, 3]))
[3]
>>> list(maximal([1]))
[1] | [
"Yield",
"the",
"unique",
"maximal",
"elements",
"from",
"iterable",
"using",
"comparison",
"."
] | 2801b27b05fa02cccee7d549451810ffcbf5c942 | https://github.com/xflr6/concepts/blob/2801b27b05fa02cccee7d549451810ffcbf5c942/concepts/tools.py#L142-L156 |
25,471 | xflr6/concepts | concepts/tools.py | Unique.replace | def replace(self, item, new_item):
"""Replace an item preserving order.
>>> u = Unique([0, 1, 2])
>>> u.replace(1, 'spam')
>>> u
Unique([0, 'spam', 2])
>>> u.replace('eggs', 1)
Traceback (most recent call last):
...
ValueError: 'eggs' is not in list
>>> u.replace('spam', 0)
Traceback (most recent call last):
...
ValueError: 0 already in list
"""
if new_item in self._seen:
raise ValueError('%r already in list' % new_item)
idx = self._items.index(item)
self._seen.remove(item)
self._seen.add(new_item)
self._items[idx] = new_item | python | def replace(self, item, new_item):
if new_item in self._seen:
raise ValueError('%r already in list' % new_item)
idx = self._items.index(item)
self._seen.remove(item)
self._seen.add(new_item)
self._items[idx] = new_item | [
"def",
"replace",
"(",
"self",
",",
"item",
",",
"new_item",
")",
":",
"if",
"new_item",
"in",
"self",
".",
"_seen",
":",
"raise",
"ValueError",
"(",
"'%r already in list'",
"%",
"new_item",
")",
"idx",
"=",
"self",
".",
"_items",
".",
"index",
"(",
"i... | Replace an item preserving order.
>>> u = Unique([0, 1, 2])
>>> u.replace(1, 'spam')
>>> u
Unique([0, 'spam', 2])
>>> u.replace('eggs', 1)
Traceback (most recent call last):
...
ValueError: 'eggs' is not in list
>>> u.replace('spam', 0)
Traceback (most recent call last):
...
ValueError: 0 already in list | [
"Replace",
"an",
"item",
"preserving",
"order",
"."
] | 2801b27b05fa02cccee7d549451810ffcbf5c942 | https://github.com/xflr6/concepts/blob/2801b27b05fa02cccee7d549451810ffcbf5c942/concepts/tools.py#L58-L81 |
25,472 | xflr6/concepts | concepts/tools.py | Unique.move | def move(self, item, new_index):
"""Move an item to the given position.
>>> u = Unique(['spam', 'eggs'])
>>> u.move('spam', 1)
>>> u
Unique(['eggs', 'spam'])
>>> u.move('ham', 0)
Traceback (most recent call last):
...
ValueError: 'ham' is not in list
"""
idx = self._items.index(item)
if idx != new_index:
item = self._items.pop(idx)
self._items.insert(new_index, item) | python | def move(self, item, new_index):
idx = self._items.index(item)
if idx != new_index:
item = self._items.pop(idx)
self._items.insert(new_index, item) | [
"def",
"move",
"(",
"self",
",",
"item",
",",
"new_index",
")",
":",
"idx",
"=",
"self",
".",
"_items",
".",
"index",
"(",
"item",
")",
"if",
"idx",
"!=",
"new_index",
":",
"item",
"=",
"self",
".",
"_items",
".",
"pop",
"(",
"idx",
")",
"self",
... | Move an item to the given position.
>>> u = Unique(['spam', 'eggs'])
>>> u.move('spam', 1)
>>> u
Unique(['eggs', 'spam'])
>>> u.move('ham', 0)
Traceback (most recent call last):
...
ValueError: 'ham' is not in list | [
"Move",
"an",
"item",
"to",
"the",
"given",
"position",
"."
] | 2801b27b05fa02cccee7d549451810ffcbf5c942 | https://github.com/xflr6/concepts/blob/2801b27b05fa02cccee7d549451810ffcbf5c942/concepts/tools.py#L83-L99 |
25,473 | xflr6/concepts | concepts/tools.py | Unique.issuperset | def issuperset(self, items):
"""Return whether this collection contains all items.
>>> Unique(['spam', 'eggs']).issuperset(['spam', 'spam', 'spam'])
True
"""
return all(_compat.map(self._seen.__contains__, items)) | python | def issuperset(self, items):
return all(_compat.map(self._seen.__contains__, items)) | [
"def",
"issuperset",
"(",
"self",
",",
"items",
")",
":",
"return",
"all",
"(",
"_compat",
".",
"map",
"(",
"self",
".",
"_seen",
".",
"__contains__",
",",
"items",
")",
")"
] | Return whether this collection contains all items.
>>> Unique(['spam', 'eggs']).issuperset(['spam', 'spam', 'spam'])
True | [
"Return",
"whether",
"this",
"collection",
"contains",
"all",
"items",
"."
] | 2801b27b05fa02cccee7d549451810ffcbf5c942 | https://github.com/xflr6/concepts/blob/2801b27b05fa02cccee7d549451810ffcbf5c942/concepts/tools.py#L101-L107 |
25,474 | xflr6/concepts | concepts/tools.py | Unique.rsub | def rsub(self, items):
"""Return order preserving unique items not in this collection.
>>> Unique(['spam']).rsub(['ham', 'spam', 'eggs'])
Unique(['ham', 'eggs'])
"""
ignore = self._seen
seen = set()
add = seen.add
items = [i for i in items
if i not in ignore and i not in seen and not add(i)]
return self._fromargs(seen, items) | python | def rsub(self, items):
ignore = self._seen
seen = set()
add = seen.add
items = [i for i in items
if i not in ignore and i not in seen and not add(i)]
return self._fromargs(seen, items) | [
"def",
"rsub",
"(",
"self",
",",
"items",
")",
":",
"ignore",
"=",
"self",
".",
"_seen",
"seen",
"=",
"set",
"(",
")",
"add",
"=",
"seen",
".",
"add",
"items",
"=",
"[",
"i",
"for",
"i",
"in",
"items",
"if",
"i",
"not",
"in",
"ignore",
"and",
... | Return order preserving unique items not in this collection.
>>> Unique(['spam']).rsub(['ham', 'spam', 'eggs'])
Unique(['ham', 'eggs']) | [
"Return",
"order",
"preserving",
"unique",
"items",
"not",
"in",
"this",
"collection",
"."
] | 2801b27b05fa02cccee7d549451810ffcbf5c942 | https://github.com/xflr6/concepts/blob/2801b27b05fa02cccee7d549451810ffcbf5c942/concepts/tools.py#L109-L120 |
25,475 | scrapinghub/skinfer | skinfer/json_schema_merger.py | merge_schema | def merge_schema(first, second):
"""Returns the result of merging the two given schemas.
"""
if not (type(first) == type(second) == dict):
raise ValueError("Argument is not a schema")
if not (first.get('type') == second.get('type') == 'object'):
raise NotImplementedError("Unsupported root type")
return merge_objects(first, second) | python | def merge_schema(first, second):
if not (type(first) == type(second) == dict):
raise ValueError("Argument is not a schema")
if not (first.get('type') == second.get('type') == 'object'):
raise NotImplementedError("Unsupported root type")
return merge_objects(first, second) | [
"def",
"merge_schema",
"(",
"first",
",",
"second",
")",
":",
"if",
"not",
"(",
"type",
"(",
"first",
")",
"==",
"type",
"(",
"second",
")",
"==",
"dict",
")",
":",
"raise",
"ValueError",
"(",
"\"Argument is not a schema\"",
")",
"if",
"not",
"(",
"fir... | Returns the result of merging the two given schemas. | [
"Returns",
"the",
"result",
"of",
"merging",
"the",
"two",
"given",
"schemas",
"."
] | 7db5bc8b27229f20b718a8f5a1d219b1b0396316 | https://github.com/scrapinghub/skinfer/blob/7db5bc8b27229f20b718a8f5a1d219b1b0396316/skinfer/json_schema_merger.py#L176-L185 |
25,476 | scrapinghub/skinfer | skinfer/schema_inferer.py | generate_and_merge_schemas | def generate_and_merge_schemas(samples):
"""Iterates through the given samples, generating schemas
and merging them, returning the resulting merged schema.
"""
merged = generate_schema_for_sample(next(iter(samples)))
for sample in samples:
merged = merge_schema(merged, generate_schema_for_sample(sample))
return merged | python | def generate_and_merge_schemas(samples):
merged = generate_schema_for_sample(next(iter(samples)))
for sample in samples:
merged = merge_schema(merged, generate_schema_for_sample(sample))
return merged | [
"def",
"generate_and_merge_schemas",
"(",
"samples",
")",
":",
"merged",
"=",
"generate_schema_for_sample",
"(",
"next",
"(",
"iter",
"(",
"samples",
")",
")",
")",
"for",
"sample",
"in",
"samples",
":",
"merged",
"=",
"merge_schema",
"(",
"merged",
",",
"ge... | Iterates through the given samples, generating schemas
and merging them, returning the resulting merged schema. | [
"Iterates",
"through",
"the",
"given",
"samples",
"generating",
"schemas",
"and",
"merging",
"them",
"returning",
"the",
"resulting",
"merged",
"schema",
"."
] | 7db5bc8b27229f20b718a8f5a1d219b1b0396316 | https://github.com/scrapinghub/skinfer/blob/7db5bc8b27229f20b718a8f5a1d219b1b0396316/skinfer/schema_inferer.py#L42-L52 |
25,477 | krischer/mtspec | mtspec/multitaper.py | sine_psd | def sine_psd(data, delta, number_of_tapers=None, number_of_iterations=2,
degree_of_smoothing=1.0, statistics=False, verbose=False):
"""
Wrapper method for the sine_psd subroutine in the library by German A.
Prieto.
The subroutine is in charge of estimating the adaptive sine multitaper as
in Riedel and Sidorenko (1995). It outputs the power spectral density
(PSD).
This is done by performing a MSE adaptive estimation. First a pilot
spectral estimate is used, and S" is estimated, in order to get te number
of tapers to use, using (13) of Riedel and Sidorenko for a min square error
spectrum.
Unlike the prolate spheroidal multitapers, the sine multitaper adaptive
process introduces a variable resolution and error in the frequency domain.
Complete error information is contained in the output variables as the
corridor of 1-standard-deviation errors, and in the number of tapers used
at each frequency. The errors are estimated in the simplest way, from the
number of degrees of freedom (two per taper), not by jack-knifing. The
frequency resolution is found from K*fN/Nf where fN is the Nyquist
frequency and Nf is the number of frequencies estimated. The adaptive
process used is as follows. A quadratic fit to the log PSD within an
adaptively determined frequency band is used to find an estimate of the
local second derivative of the spectrum. This is used in an equation like R
& S (13) for the MSE taper number, with the difference that a parabolic
weighting is applied with increasing taper order. Because the FFTs of the
tapered series can be found by resampling the FFT of the original time
series (doubled in length and padded with zeros) only one FFT is required
per series, no matter how many tapers are used. This makes the program
fast. Compared with the Thomson multitaper programs, this code is not only
fast but simple and short. The spectra associated with the sine tapers are
weighted before averaging with a parabolically varying weight. The
expression for the optimal number of tapers given by R & S must be modified
since it gives an unbounded result near points where S" vanishes, which
happens at many points in most spectra. This program restricts the rate of
growth of the number of tapers so that a neighboring covering interval
estimate is never completely contained in the next such interval.
This method SHOULD not be used for sharp cutoffs or deep valleys, or small
sample sizes. Instead use Thomson multitaper in mtspec in this same
library.
:param data: :class:`numpy.ndarray`
Array with the data.
:param delta: float
Sample spacing of the data.
:param number_of_tapers: integer/None, optional
Number of tapers to use. If none is given, the library will perform an
adaptive taper estimation with a varying number of tapers for each
frequency. Defaults to None.
:param number_of_iterations: integer, optional
Number of iterations to perform. Values less than 2 will be set to 2.
Defaults to 2.
:param degree_of_smoothing: float, optional
Degree of smoothing. Defaults to 1.0.
:param statistics: bool, optional
Calculates and returns statistics. See the notes in the docstring for
further details.
:param verbose: bool, optional
Passed to the fortran library. Defaults to False.
:return: Returns a list with :class:`numpy.ndarray`. See the note below
for details.
.. note::
This method will at return at least two arrays: The calculated
spectrum and the corresponding frequencies. If statistics is True
is will also return (in the given order) (multidimensional) arrays
containing the 1-std errors (a simple dof estimate) and the number
of tapers used for each frequency point.
"""
# Verbose mode on or off.
if verbose is True:
verbose = C.byref(C.c_char('y'))
else:
verbose = None
# Set the number of tapers so it can be read by the library.
if number_of_tapers is None:
number_of_tapers = 0
# initialize _MtspecType to save some space
mt = _MtspecType("float32")
# Transform the data to work with the library.
data = np.require(data, dtype=mt.float, requirements=[mt.order])
# Some variables necessary to call the library.
npts = len(data)
number_of_frequency_bins = int(npts / 2) + 1
# Create output arrays.
frequency_bins = mt.empty(number_of_frequency_bins)
spectrum = mt.empty(number_of_frequency_bins)
# Create optional arrays or set to None.
if statistics is True:
# here an exception, mt sets the type float32, here we need int32
# that is do all the type and POINTER definition once by hand
tapers_per_freq_point = np.empty(number_of_frequency_bins,
dtype='int32', order=mt.order)
tapers_per_freq_point_p = \
tapers_per_freq_point.ctypes.data_as(C.POINTER(C.c_int))
errors = mt.empty((number_of_frequency_bins, 2))
else:
tapers_per_freq_point_p = errors = None
# Call the library. Fortran passes pointers!
mtspeclib.sine_psd_(
C.byref(C.c_int(npts)),
C.byref(C.c_float(delta)), mt.p(data),
C.byref(C.c_int(number_of_tapers)),
C.byref(C.c_int(number_of_iterations)),
C.byref(C.c_float(degree_of_smoothing)),
C.byref(C.c_int(number_of_frequency_bins)),
mt.p(frequency_bins), mt.p(spectrum),
tapers_per_freq_point_p, mt.p(errors), verbose)
# Calculate return values.
return_values = [spectrum, frequency_bins]
if statistics is True:
return_values.extend([errors, tapers_per_freq_point])
return return_values | python | def sine_psd(data, delta, number_of_tapers=None, number_of_iterations=2,
degree_of_smoothing=1.0, statistics=False, verbose=False):
# Verbose mode on or off.
if verbose is True:
verbose = C.byref(C.c_char('y'))
else:
verbose = None
# Set the number of tapers so it can be read by the library.
if number_of_tapers is None:
number_of_tapers = 0
# initialize _MtspecType to save some space
mt = _MtspecType("float32")
# Transform the data to work with the library.
data = np.require(data, dtype=mt.float, requirements=[mt.order])
# Some variables necessary to call the library.
npts = len(data)
number_of_frequency_bins = int(npts / 2) + 1
# Create output arrays.
frequency_bins = mt.empty(number_of_frequency_bins)
spectrum = mt.empty(number_of_frequency_bins)
# Create optional arrays or set to None.
if statistics is True:
# here an exception, mt sets the type float32, here we need int32
# that is do all the type and POINTER definition once by hand
tapers_per_freq_point = np.empty(number_of_frequency_bins,
dtype='int32', order=mt.order)
tapers_per_freq_point_p = \
tapers_per_freq_point.ctypes.data_as(C.POINTER(C.c_int))
errors = mt.empty((number_of_frequency_bins, 2))
else:
tapers_per_freq_point_p = errors = None
# Call the library. Fortran passes pointers!
mtspeclib.sine_psd_(
C.byref(C.c_int(npts)),
C.byref(C.c_float(delta)), mt.p(data),
C.byref(C.c_int(number_of_tapers)),
C.byref(C.c_int(number_of_iterations)),
C.byref(C.c_float(degree_of_smoothing)),
C.byref(C.c_int(number_of_frequency_bins)),
mt.p(frequency_bins), mt.p(spectrum),
tapers_per_freq_point_p, mt.p(errors), verbose)
# Calculate return values.
return_values = [spectrum, frequency_bins]
if statistics is True:
return_values.extend([errors, tapers_per_freq_point])
return return_values | [
"def",
"sine_psd",
"(",
"data",
",",
"delta",
",",
"number_of_tapers",
"=",
"None",
",",
"number_of_iterations",
"=",
"2",
",",
"degree_of_smoothing",
"=",
"1.0",
",",
"statistics",
"=",
"False",
",",
"verbose",
"=",
"False",
")",
":",
"# Verbose mode on or of... | Wrapper method for the sine_psd subroutine in the library by German A.
Prieto.
The subroutine is in charge of estimating the adaptive sine multitaper as
in Riedel and Sidorenko (1995). It outputs the power spectral density
(PSD).
This is done by performing a MSE adaptive estimation. First a pilot
spectral estimate is used, and S" is estimated, in order to get te number
of tapers to use, using (13) of Riedel and Sidorenko for a min square error
spectrum.
Unlike the prolate spheroidal multitapers, the sine multitaper adaptive
process introduces a variable resolution and error in the frequency domain.
Complete error information is contained in the output variables as the
corridor of 1-standard-deviation errors, and in the number of tapers used
at each frequency. The errors are estimated in the simplest way, from the
number of degrees of freedom (two per taper), not by jack-knifing. The
frequency resolution is found from K*fN/Nf where fN is the Nyquist
frequency and Nf is the number of frequencies estimated. The adaptive
process used is as follows. A quadratic fit to the log PSD within an
adaptively determined frequency band is used to find an estimate of the
local second derivative of the spectrum. This is used in an equation like R
& S (13) for the MSE taper number, with the difference that a parabolic
weighting is applied with increasing taper order. Because the FFTs of the
tapered series can be found by resampling the FFT of the original time
series (doubled in length and padded with zeros) only one FFT is required
per series, no matter how many tapers are used. This makes the program
fast. Compared with the Thomson multitaper programs, this code is not only
fast but simple and short. The spectra associated with the sine tapers are
weighted before averaging with a parabolically varying weight. The
expression for the optimal number of tapers given by R & S must be modified
since it gives an unbounded result near points where S" vanishes, which
happens at many points in most spectra. This program restricts the rate of
growth of the number of tapers so that a neighboring covering interval
estimate is never completely contained in the next such interval.
This method SHOULD not be used for sharp cutoffs or deep valleys, or small
sample sizes. Instead use Thomson multitaper in mtspec in this same
library.
:param data: :class:`numpy.ndarray`
Array with the data.
:param delta: float
Sample spacing of the data.
:param number_of_tapers: integer/None, optional
Number of tapers to use. If none is given, the library will perform an
adaptive taper estimation with a varying number of tapers for each
frequency. Defaults to None.
:param number_of_iterations: integer, optional
Number of iterations to perform. Values less than 2 will be set to 2.
Defaults to 2.
:param degree_of_smoothing: float, optional
Degree of smoothing. Defaults to 1.0.
:param statistics: bool, optional
Calculates and returns statistics. See the notes in the docstring for
further details.
:param verbose: bool, optional
Passed to the fortran library. Defaults to False.
:return: Returns a list with :class:`numpy.ndarray`. See the note below
for details.
.. note::
This method will at return at least two arrays: The calculated
spectrum and the corresponding frequencies. If statistics is True
is will also return (in the given order) (multidimensional) arrays
containing the 1-std errors (a simple dof estimate) and the number
of tapers used for each frequency point. | [
"Wrapper",
"method",
"for",
"the",
"sine_psd",
"subroutine",
"in",
"the",
"library",
"by",
"German",
"A",
".",
"Prieto",
"."
] | 06561b6370f13fcb2e731470ba0f7314f4b2362d | https://github.com/krischer/mtspec/blob/06561b6370f13fcb2e731470ba0f7314f4b2362d/mtspec/multitaper.py#L183-L298 |
25,478 | krischer/mtspec | mtspec/multitaper.py | dpss | def dpss(npts, fw, number_of_tapers, auto_spline=True, npts_max=None):
"""
Calculates DPSS also known as Slepian sequences or Slepian tapers.
Calculation of the DPSS (Discrete Prolate Spheroidal Sequences) and the
correspondent eigenvalues. The (1 - eigenvalue) terms are also calculated.
Wraps the ``dpss()`` subroutine from the Fortran library.
By default this routine will use spline interpolation if sequences with
more than 200.000 samples are requested.
.. note::
The tapers are the eigenvectors of the tridiagonal matrix sigma(i, j)
[see Slepian(1978) eq 14 and 25]. They are also the eigenvectors of
the Toeplitz matrix, eq. 18.
:param npts: The number of points in the series.
:type npts: int
:param fw: The time-bandwidth product (number of Rayleigh bins).
:type fw: float
:param number_of_tapers: The desired number of tapers.
:type number_of_tapers: int
:param auto_spline: Whether or not to automatically use spline
interpolation for ``npts`` > 200000.
:type auto_spline: bool
:param npts_max: The number of actual points to calculate the DPSS. If this
number is smaller than ``npts``, spline interpolation will be
performed, regardless of the value of ``auto_spline``.
:type npts_max: None or int
:returns: ``(v, lambda, theta)`` with
``v(npts, number_of_tapers)`` the eigenvectors (tapers), ``lambda`` the
eigenvalues of the ``v``'s and ``theta`` the 1 - ``lambda``
(energy outside the bandwidth) values.
.. rubric:: Example
This example demonstrates how to calculate and plot the first five DPSS'.
>>> import matplotlib.pyplot as plt
>>> from mtspec import dpss
>>> tapers, lamb, theta = dpss(512, 2.5, 5)
>>> for i in range(5):
... plt.plot(tapers[:, i])
.. plot ::
# Same as the code snippet in the docstring, just a bit prettier.
import matplotlib.pyplot as plt
plt.style.use("ggplot")
from mtspec import dpss
tapers, lamb, theta = dpss(512, 2.5, 5)
for i in range(5):
plt.plot(tapers[:, i])
plt.xlim(0, 512)
plt.ylim(-0.09, 0.09)
plt.tight_layout()
"""
mt = _MtspecType("float64")
v = mt.empty((npts, number_of_tapers))
lamb = mt.empty(number_of_tapers)
theta = mt.empty(number_of_tapers)
# Set auto_spline to True.
if npts_max and npts_max < npts:
auto_spline = True
# Always set npts_max.
else:
npts_max = 200000
# Call either the spline routine or the normal routine.
if auto_spline is True and npts > npts_max:
mtspeclib.dpss_spline_(
C.byref(C.c_int(npts_max)), C.byref(C.c_int(npts)),
C.byref(C.c_double(fw)), C.byref(C.c_int(number_of_tapers)),
mt.p(v), mt.p(lamb), mt.p(theta))
else:
mtspeclib.dpss_(C.byref(C.c_int(npts)), C.byref(C.c_double(fw)),
C.byref(C.c_int(number_of_tapers)), mt.p(v),
mt.p(lamb), mt.p(theta))
return (v, lamb, theta) | python | def dpss(npts, fw, number_of_tapers, auto_spline=True, npts_max=None):
mt = _MtspecType("float64")
v = mt.empty((npts, number_of_tapers))
lamb = mt.empty(number_of_tapers)
theta = mt.empty(number_of_tapers)
# Set auto_spline to True.
if npts_max and npts_max < npts:
auto_spline = True
# Always set npts_max.
else:
npts_max = 200000
# Call either the spline routine or the normal routine.
if auto_spline is True and npts > npts_max:
mtspeclib.dpss_spline_(
C.byref(C.c_int(npts_max)), C.byref(C.c_int(npts)),
C.byref(C.c_double(fw)), C.byref(C.c_int(number_of_tapers)),
mt.p(v), mt.p(lamb), mt.p(theta))
else:
mtspeclib.dpss_(C.byref(C.c_int(npts)), C.byref(C.c_double(fw)),
C.byref(C.c_int(number_of_tapers)), mt.p(v),
mt.p(lamb), mt.p(theta))
return (v, lamb, theta) | [
"def",
"dpss",
"(",
"npts",
",",
"fw",
",",
"number_of_tapers",
",",
"auto_spline",
"=",
"True",
",",
"npts_max",
"=",
"None",
")",
":",
"mt",
"=",
"_MtspecType",
"(",
"\"float64\"",
")",
"v",
"=",
"mt",
".",
"empty",
"(",
"(",
"npts",
",",
"number_o... | Calculates DPSS also known as Slepian sequences or Slepian tapers.
Calculation of the DPSS (Discrete Prolate Spheroidal Sequences) and the
correspondent eigenvalues. The (1 - eigenvalue) terms are also calculated.
Wraps the ``dpss()`` subroutine from the Fortran library.
By default this routine will use spline interpolation if sequences with
more than 200.000 samples are requested.
.. note::
The tapers are the eigenvectors of the tridiagonal matrix sigma(i, j)
[see Slepian(1978) eq 14 and 25]. They are also the eigenvectors of
the Toeplitz matrix, eq. 18.
:param npts: The number of points in the series.
:type npts: int
:param fw: The time-bandwidth product (number of Rayleigh bins).
:type fw: float
:param number_of_tapers: The desired number of tapers.
:type number_of_tapers: int
:param auto_spline: Whether or not to automatically use spline
interpolation for ``npts`` > 200000.
:type auto_spline: bool
:param npts_max: The number of actual points to calculate the DPSS. If this
number is smaller than ``npts``, spline interpolation will be
performed, regardless of the value of ``auto_spline``.
:type npts_max: None or int
:returns: ``(v, lambda, theta)`` with
``v(npts, number_of_tapers)`` the eigenvectors (tapers), ``lambda`` the
eigenvalues of the ``v``'s and ``theta`` the 1 - ``lambda``
(energy outside the bandwidth) values.
.. rubric:: Example
This example demonstrates how to calculate and plot the first five DPSS'.
>>> import matplotlib.pyplot as plt
>>> from mtspec import dpss
>>> tapers, lamb, theta = dpss(512, 2.5, 5)
>>> for i in range(5):
... plt.plot(tapers[:, i])
.. plot ::
# Same as the code snippet in the docstring, just a bit prettier.
import matplotlib.pyplot as plt
plt.style.use("ggplot")
from mtspec import dpss
tapers, lamb, theta = dpss(512, 2.5, 5)
for i in range(5):
plt.plot(tapers[:, i])
plt.xlim(0, 512)
plt.ylim(-0.09, 0.09)
plt.tight_layout() | [
"Calculates",
"DPSS",
"also",
"known",
"as",
"Slepian",
"sequences",
"or",
"Slepian",
"tapers",
"."
] | 06561b6370f13fcb2e731470ba0f7314f4b2362d | https://github.com/krischer/mtspec/blob/06561b6370f13fcb2e731470ba0f7314f4b2362d/mtspec/multitaper.py#L301-L384 |
25,479 | krischer/mtspec | mtspec/multitaper.py | wigner_ville_spectrum | def wigner_ville_spectrum(data, delta, time_bandwidth=3.5,
number_of_tapers=None, smoothing_filter=None,
filter_width=100, frequency_divider=1,
verbose=False):
"""
Function to calculate the Wigner-Ville Distribution or Wigner-Ville
Spectrum of a signal using multitaper spectral estimates.
In general it gives better temporal and frequency resolution than a
spectrogram but introduces many artifacts and possibly negative values
which are not physical. This can be alleviated a bit by applying a
smoothing kernel which is also known as a reduced interference
distribution (RID).
Wraps the ``wv_spec()`` and ``wv_spec_to_array()`` subroutines of the
Fortran library.
It is very slow for large arrays so try with a small one (< 5000 samples)
first.
:param data: The input signal.
:type data: numpy.ndarray
:param delta: The sampling interval of the data.
:type delta: float
:param time_bandwidth: Time bandwidth product for the tapers.
:type time_bandwidth: float
:param number_of_tapers: Number of tapers to use. If ``None``, the number
will be automatically determined from the time bandwidth product
which is usually the optimal choice.
:type number_of_tapers: int
:param smoothing_filter: One of ``"boxcar"``, ``"gauss"`` or just ``None``
:type smoothing_filter: str
:param filter_width: Filter width in samples.
:type filter_width: int
:param frequency_divider: This method will always calculate all
frequencies from 0 ... Nyquist frequency. This parameter allows the
adjustment of the maximum frequency, so that the frequencies range
from 0 .. Nyquist frequency / int(frequency_divider).
:type frequency_divider: int
:param verbose: Verbose output on/off.
:type verbose: bool
.. rubric:: Example
This example demonstrates how to plot a signal, its multitaper spectral
estimate, and its Wigner-Ville time-frequency distribution. The signal
is sinusoidal overlaid with two simple linear chirps.
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from mtspec import mtspec, wigner_ville_spectrum
>>> from mtspec.util import signal_bursts
>>> fig = plt.figure()
Get the example signal.
>>> data = signal_bursts()
Plot the data on the top axes.
>>> ax1 = fig.add_axes([0.2,0.75, 0.79, 0.23])
>>> ax1.plot(data, color="0.1")
>>> ax1.set_xlim(0, len(data))
Plot its spectral estimate on the side.
>>> ax2 = fig.add_axes([0.06,0.02,0.13,0.69])
>>> spec, freq = mtspec(data, 10, 3.5)
>>> ax2.plot(spec, freq, color="0.1")
>>> ax2.set_xlim(0, spec.max())
>>> ax2.set_ylim(freq[0], freq[-1])
>>> ax2.set_xticks([])
Create and plot the Wigner-Ville distribution.
>>> wv = wigner_ville_spectrum(data, 10, 3.5,
... smoothing_filter='gauss')
>>> ax3 = fig.add_axes([0.2, 0.02, 0.79, 0.69])
>>> ax3.set_yticks([])
>>> ax3.set_xticks([])
>>> # The square root only serves plotting purposes.
>>> ax3.imshow(np.sqrt(abs(wv)), interpolation='lanczos',
... aspect='auto', cmap="magma")
.. plot::
# Same as the above code snippet just a bit prettier.
import matplotlib.pyplot as plt
plt.style.use("ggplot")
from mtspec import mtspec, wigner_ville_spectrum
from mtspec.util import signal_bursts
import numpy as np
fig = plt.figure()
data = signal_bursts()
# Plot the data
ax1 = fig.add_axes([0.2,0.75, 0.79, 0.23])
ax1.plot(data, color="0.1")
ax1.set_xlim(0, len(data))
# Plot multitaper spectrum
ax2 = fig.add_axes([0.06,0.02,0.13,0.69])
spec, freq = mtspec(data, 10, 3.5)
ax2.plot(spec, freq, color="0.1")
ax2.set_xlim(0, spec.max())
ax2.set_ylim(freq[0], freq[-1])
ax2.set_xticks([])
# Create the wigner ville spectrum
wv = wigner_ville_spectrum(data, 10, 3.5, smoothing_filter='gauss')
# Plot the WV
ax3 = fig.add_axes([0.2, 0.02, 0.79, 0.69])
ax3.set_yticks([])
ax3.set_xticks([])
ax3.imshow(np.sqrt(abs(wv)), interpolation='lanczos', aspect='auto',
cmap="magma")
"""
data = np.require(data, 'float32')
mt = _MtspecType("float32")
npts = len(data)
# Use the optimal number of tapers in case no number is specified.
if number_of_tapers is None:
number_of_tapers = int(2 * time_bandwidth) - 1
# Determine filter.
if not smoothing_filter:
smoothing_filter = 0
elif smoothing_filter == 'boxcar':
smoothing_filter = 1
elif smoothing_filter == 'gauss':
smoothing_filter = 2
else:
msg = 'Invalid value for smoothing filter.'
raise Exception(msg)
# Verbose mode on or off.
if verbose:
verbose = C.byref(C.c_char('y'))
else:
verbose = None
# Allocate the output array
# f90 code internally pads zeros to 2 * npts. That is we only return
# every second frequency point, thus decrease the size of the array
output = mt.empty((npts // 2 // int(frequency_divider) + 1, npts))
mtspeclib.wv_spec_to_array_(C.byref(C.c_int(npts)),
C.byref(C.c_float(delta)),
mt.p(data), mt.p(output),
C.byref(C.c_float(time_bandwidth)),
C.byref(C.c_int(number_of_tapers)),
C.byref(C.c_int(smoothing_filter)),
C.byref(C.c_float(filter_width)),
C.byref(C.c_int(frequency_divider)), verbose)
return output | python | def wigner_ville_spectrum(data, delta, time_bandwidth=3.5,
number_of_tapers=None, smoothing_filter=None,
filter_width=100, frequency_divider=1,
verbose=False):
data = np.require(data, 'float32')
mt = _MtspecType("float32")
npts = len(data)
# Use the optimal number of tapers in case no number is specified.
if number_of_tapers is None:
number_of_tapers = int(2 * time_bandwidth) - 1
# Determine filter.
if not smoothing_filter:
smoothing_filter = 0
elif smoothing_filter == 'boxcar':
smoothing_filter = 1
elif smoothing_filter == 'gauss':
smoothing_filter = 2
else:
msg = 'Invalid value for smoothing filter.'
raise Exception(msg)
# Verbose mode on or off.
if verbose:
verbose = C.byref(C.c_char('y'))
else:
verbose = None
# Allocate the output array
# f90 code internally pads zeros to 2 * npts. That is we only return
# every second frequency point, thus decrease the size of the array
output = mt.empty((npts // 2 // int(frequency_divider) + 1, npts))
mtspeclib.wv_spec_to_array_(C.byref(C.c_int(npts)),
C.byref(C.c_float(delta)),
mt.p(data), mt.p(output),
C.byref(C.c_float(time_bandwidth)),
C.byref(C.c_int(number_of_tapers)),
C.byref(C.c_int(smoothing_filter)),
C.byref(C.c_float(filter_width)),
C.byref(C.c_int(frequency_divider)), verbose)
return output | [
"def",
"wigner_ville_spectrum",
"(",
"data",
",",
"delta",
",",
"time_bandwidth",
"=",
"3.5",
",",
"number_of_tapers",
"=",
"None",
",",
"smoothing_filter",
"=",
"None",
",",
"filter_width",
"=",
"100",
",",
"frequency_divider",
"=",
"1",
",",
"verbose",
"=",
... | Function to calculate the Wigner-Ville Distribution or Wigner-Ville
Spectrum of a signal using multitaper spectral estimates.
In general it gives better temporal and frequency resolution than a
spectrogram but introduces many artifacts and possibly negative values
which are not physical. This can be alleviated a bit by applying a
smoothing kernel which is also known as a reduced interference
distribution (RID).
Wraps the ``wv_spec()`` and ``wv_spec_to_array()`` subroutines of the
Fortran library.
It is very slow for large arrays so try with a small one (< 5000 samples)
first.
:param data: The input signal.
:type data: numpy.ndarray
:param delta: The sampling interval of the data.
:type delta: float
:param time_bandwidth: Time bandwidth product for the tapers.
:type time_bandwidth: float
:param number_of_tapers: Number of tapers to use. If ``None``, the number
will be automatically determined from the time bandwidth product
which is usually the optimal choice.
:type number_of_tapers: int
:param smoothing_filter: One of ``"boxcar"``, ``"gauss"`` or just ``None``
:type smoothing_filter: str
:param filter_width: Filter width in samples.
:type filter_width: int
:param frequency_divider: This method will always calculate all
frequencies from 0 ... Nyquist frequency. This parameter allows the
adjustment of the maximum frequency, so that the frequencies range
from 0 .. Nyquist frequency / int(frequency_divider).
:type frequency_divider: int
:param verbose: Verbose output on/off.
:type verbose: bool
.. rubric:: Example
This example demonstrates how to plot a signal, its multitaper spectral
estimate, and its Wigner-Ville time-frequency distribution. The signal
is sinusoidal overlaid with two simple linear chirps.
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from mtspec import mtspec, wigner_ville_spectrum
>>> from mtspec.util import signal_bursts
>>> fig = plt.figure()
Get the example signal.
>>> data = signal_bursts()
Plot the data on the top axes.
>>> ax1 = fig.add_axes([0.2,0.75, 0.79, 0.23])
>>> ax1.plot(data, color="0.1")
>>> ax1.set_xlim(0, len(data))
Plot its spectral estimate on the side.
>>> ax2 = fig.add_axes([0.06,0.02,0.13,0.69])
>>> spec, freq = mtspec(data, 10, 3.5)
>>> ax2.plot(spec, freq, color="0.1")
>>> ax2.set_xlim(0, spec.max())
>>> ax2.set_ylim(freq[0], freq[-1])
>>> ax2.set_xticks([])
Create and plot the Wigner-Ville distribution.
>>> wv = wigner_ville_spectrum(data, 10, 3.5,
... smoothing_filter='gauss')
>>> ax3 = fig.add_axes([0.2, 0.02, 0.79, 0.69])
>>> ax3.set_yticks([])
>>> ax3.set_xticks([])
>>> # The square root only serves plotting purposes.
>>> ax3.imshow(np.sqrt(abs(wv)), interpolation='lanczos',
... aspect='auto', cmap="magma")
.. plot::
# Same as the above code snippet just a bit prettier.
import matplotlib.pyplot as plt
plt.style.use("ggplot")
from mtspec import mtspec, wigner_ville_spectrum
from mtspec.util import signal_bursts
import numpy as np
fig = plt.figure()
data = signal_bursts()
# Plot the data
ax1 = fig.add_axes([0.2,0.75, 0.79, 0.23])
ax1.plot(data, color="0.1")
ax1.set_xlim(0, len(data))
# Plot multitaper spectrum
ax2 = fig.add_axes([0.06,0.02,0.13,0.69])
spec, freq = mtspec(data, 10, 3.5)
ax2.plot(spec, freq, color="0.1")
ax2.set_xlim(0, spec.max())
ax2.set_ylim(freq[0], freq[-1])
ax2.set_xticks([])
# Create the wigner ville spectrum
wv = wigner_ville_spectrum(data, 10, 3.5, smoothing_filter='gauss')
# Plot the WV
ax3 = fig.add_axes([0.2, 0.02, 0.79, 0.69])
ax3.set_yticks([])
ax3.set_xticks([])
ax3.imshow(np.sqrt(abs(wv)), interpolation='lanczos', aspect='auto',
cmap="magma") | [
"Function",
"to",
"calculate",
"the",
"Wigner",
"-",
"Ville",
"Distribution",
"or",
"Wigner",
"-",
"Ville",
"Spectrum",
"of",
"a",
"signal",
"using",
"multitaper",
"spectral",
"estimates",
"."
] | 06561b6370f13fcb2e731470ba0f7314f4b2362d | https://github.com/krischer/mtspec/blob/06561b6370f13fcb2e731470ba0f7314f4b2362d/mtspec/multitaper.py#L387-L546 |
25,480 | krischer/mtspec | mtspec/multitaper.py | mt_deconvolve | def mt_deconvolve(data_a, data_b, delta, nfft=None, time_bandwidth=None,
number_of_tapers=None, weights="adaptive", demean=True,
fmax=0.0):
"""
Deconvolve two time series using multitapers.
This uses the eigencoefficients and the weights from the multitaper
spectral estimations and more or less follows this paper:
.. |br| raw:: html
<br />
**Receiver Functions from Multiple-Taper Spectral Correlation Estimates**
*Jeffrey Park, Vadim Levin* |br|
Bulletin of the Seismological Society of America Dec 2000,
90 (6) 1507-1520
http://dx.doi.org/10.1785/0119990122
:type data_a: :class:`numpy.ndarray`
:param data_a: Data for first time series.
:type data_b: :class:`numpy.ndarray`
:param data_b: Data for second time series.
:type delta: float
:param delta: Sample spacing of the data.
:type nfft: int
:param nfft: Number of points for the FFT. If ``nfft == None``, no zero
padding will be applied before the FFT.
:type time_bandwidth: float
:param time_bandwidth: Time-bandwidth product. Common values are 2, 3, 4,
and numbers in between.
:type number_of_tapers: int
:param number_of_tapers: Number of tapers to use. Defaults to
``int(2*time_bandwidth) - 1``. This is maximum senseful amount. More
tapers will have no great influence on the final spectrum but increase
the calculation time. Use fewer tapers for a faster calculation.
:type weights: str
:param weights: ``"adaptive"`` or ``"constant"`` weights.
:type deman: bool
:param demean: Force the complex TF to be demeaned.
:type fmax: float
:param fmax: Maximum frequency for lowpass cosine filter. Set this to
zero to not have a filter.
:return: Returns a dictionary with 5 :class:`numpy.ndarray`'s. See the note
below.
.. note::
Returns a dictionary with five arrays:
* ``"deconvolved"``: Deconvolved time series.
* ``"spectrum_a"``: Spectrum of the first time series.
* ``"spectrum_b"``: Spectrum of the second time series.
* ``"spectral_ratio"``: The ratio of both spectra.
* ``"frequencies"``: The used frequency bins for the spectra.
"""
npts = len(data_a)
if len(data_b) != npts:
raise ValueError("Input arrays must have the same length!")
if nfft is None:
nfft = npts
elif nfft < npts:
raise ValueError("nfft must be larger then the number of samples in "
"the array.")
# Deconvolution utilizes the 32bit version.
mt = _MtspecType("float32")
# Use the optimal number of tapers in case no number is specified.
if number_of_tapers is None:
number_of_tapers = int(2 * time_bandwidth) - 1
# Transform the data to work with the library.
data_a = np.require(data_a, mt.float, requirements=[mt.order])
data_b = np.require(data_b, mt.float, requirements=[mt.order])
nf = nfft // 2 + 1
# Internally uses integers
if demean:
demean = 1
else:
demean = 0
# iad = 0 are adaptive, iad = 1 are constant weight - this is
# counter intuitive.
if weights == "constant":
adaptive = 1
elif weights == "adaptive":
adaptive = 0
else:
raise ValueError('Weights must be either "adaptive" or "constant".')
tfun = mt.empty(nfft)
freq = mt.empty(nf)
spec_ratio = mt.empty(nf)
speci = mt.empty(nf)
specj = mt.empty(nf)
mtspeclib.mt_deconv_(
C.byref(C.c_int(int(npts))),
C.byref(C.c_int(int(nfft))),
C.byref(C.c_float(float(delta))),
mt.p(data_a),
mt.p(data_b),
C.byref(C.c_float(float(time_bandwidth))),
C.byref(C.c_int(int(number_of_tapers))),
C.byref(C.c_int(int(nf))),
C.byref(C.c_int(adaptive)),
mt.p(freq),
mt.p(tfun),
mt.p(spec_ratio),
mt.p(speci),
mt.p(specj),
C.byref(C.c_int(demean)),
C.byref(C.c_float(fmax)))
return {
"frequencies": freq,
"deconvolved": tfun,
"spectral_ratio": spec_ratio,
"spectrum_a": speci,
"spectrum_b": specj
} | python | def mt_deconvolve(data_a, data_b, delta, nfft=None, time_bandwidth=None,
number_of_tapers=None, weights="adaptive", demean=True,
fmax=0.0):
npts = len(data_a)
if len(data_b) != npts:
raise ValueError("Input arrays must have the same length!")
if nfft is None:
nfft = npts
elif nfft < npts:
raise ValueError("nfft must be larger then the number of samples in "
"the array.")
# Deconvolution utilizes the 32bit version.
mt = _MtspecType("float32")
# Use the optimal number of tapers in case no number is specified.
if number_of_tapers is None:
number_of_tapers = int(2 * time_bandwidth) - 1
# Transform the data to work with the library.
data_a = np.require(data_a, mt.float, requirements=[mt.order])
data_b = np.require(data_b, mt.float, requirements=[mt.order])
nf = nfft // 2 + 1
# Internally uses integers
if demean:
demean = 1
else:
demean = 0
# iad = 0 are adaptive, iad = 1 are constant weight - this is
# counter intuitive.
if weights == "constant":
adaptive = 1
elif weights == "adaptive":
adaptive = 0
else:
raise ValueError('Weights must be either "adaptive" or "constant".')
tfun = mt.empty(nfft)
freq = mt.empty(nf)
spec_ratio = mt.empty(nf)
speci = mt.empty(nf)
specj = mt.empty(nf)
mtspeclib.mt_deconv_(
C.byref(C.c_int(int(npts))),
C.byref(C.c_int(int(nfft))),
C.byref(C.c_float(float(delta))),
mt.p(data_a),
mt.p(data_b),
C.byref(C.c_float(float(time_bandwidth))),
C.byref(C.c_int(int(number_of_tapers))),
C.byref(C.c_int(int(nf))),
C.byref(C.c_int(adaptive)),
mt.p(freq),
mt.p(tfun),
mt.p(spec_ratio),
mt.p(speci),
mt.p(specj),
C.byref(C.c_int(demean)),
C.byref(C.c_float(fmax)))
return {
"frequencies": freq,
"deconvolved": tfun,
"spectral_ratio": spec_ratio,
"spectrum_a": speci,
"spectrum_b": specj
} | [
"def",
"mt_deconvolve",
"(",
"data_a",
",",
"data_b",
",",
"delta",
",",
"nfft",
"=",
"None",
",",
"time_bandwidth",
"=",
"None",
",",
"number_of_tapers",
"=",
"None",
",",
"weights",
"=",
"\"adaptive\"",
",",
"demean",
"=",
"True",
",",
"fmax",
"=",
"0.... | Deconvolve two time series using multitapers.
This uses the eigencoefficients and the weights from the multitaper
spectral estimations and more or less follows this paper:
.. |br| raw:: html
<br />
**Receiver Functions from Multiple-Taper Spectral Correlation Estimates**
*Jeffrey Park, Vadim Levin* |br|
Bulletin of the Seismological Society of America Dec 2000,
90 (6) 1507-1520
http://dx.doi.org/10.1785/0119990122
:type data_a: :class:`numpy.ndarray`
:param data_a: Data for first time series.
:type data_b: :class:`numpy.ndarray`
:param data_b: Data for second time series.
:type delta: float
:param delta: Sample spacing of the data.
:type nfft: int
:param nfft: Number of points for the FFT. If ``nfft == None``, no zero
padding will be applied before the FFT.
:type time_bandwidth: float
:param time_bandwidth: Time-bandwidth product. Common values are 2, 3, 4,
and numbers in between.
:type number_of_tapers: int
:param number_of_tapers: Number of tapers to use. Defaults to
``int(2*time_bandwidth) - 1``. This is maximum senseful amount. More
tapers will have no great influence on the final spectrum but increase
the calculation time. Use fewer tapers for a faster calculation.
:type weights: str
:param weights: ``"adaptive"`` or ``"constant"`` weights.
:type deman: bool
:param demean: Force the complex TF to be demeaned.
:type fmax: float
:param fmax: Maximum frequency for lowpass cosine filter. Set this to
zero to not have a filter.
:return: Returns a dictionary with 5 :class:`numpy.ndarray`'s. See the note
below.
.. note::
Returns a dictionary with five arrays:
* ``"deconvolved"``: Deconvolved time series.
* ``"spectrum_a"``: Spectrum of the first time series.
* ``"spectrum_b"``: Spectrum of the second time series.
* ``"spectral_ratio"``: The ratio of both spectra.
* ``"frequencies"``: The used frequency bins for the spectra. | [
"Deconvolve",
"two",
"time",
"series",
"using",
"multitapers",
"."
] | 06561b6370f13fcb2e731470ba0f7314f4b2362d | https://github.com/krischer/mtspec/blob/06561b6370f13fcb2e731470ba0f7314f4b2362d/mtspec/multitaper.py#L623-L749 |
25,481 | krischer/mtspec | mtspec/multitaper.py | _MtspecType.empty | def empty(self, shape, complex=False):
"""
A wrapper around np.empty which automatically sets the correct type
and returns an empty array.
:param shape: The shape of the array in np.empty format
"""
if complex:
return np.empty(shape, dtype=self.complex, order=self.order)
return np.empty(shape, dtype=self.float, order=self.order) | python | def empty(self, shape, complex=False):
if complex:
return np.empty(shape, dtype=self.complex, order=self.order)
return np.empty(shape, dtype=self.float, order=self.order) | [
"def",
"empty",
"(",
"self",
",",
"shape",
",",
"complex",
"=",
"False",
")",
":",
"if",
"complex",
":",
"return",
"np",
".",
"empty",
"(",
"shape",
",",
"dtype",
"=",
"self",
".",
"complex",
",",
"order",
"=",
"self",
".",
"order",
")",
"return",
... | A wrapper around np.empty which automatically sets the correct type
and returns an empty array.
:param shape: The shape of the array in np.empty format | [
"A",
"wrapper",
"around",
"np",
".",
"empty",
"which",
"automatically",
"sets",
"the",
"correct",
"type",
"and",
"returns",
"an",
"empty",
"array",
"."
] | 06561b6370f13fcb2e731470ba0f7314f4b2362d | https://github.com/krischer/mtspec/blob/06561b6370f13fcb2e731470ba0f7314f4b2362d/mtspec/multitaper.py#L775-L784 |
25,482 | krischer/mtspec | mtspec/util.py | signal_bursts | def signal_bursts():
"""
Generates a signal with two bursts inside. Useful for testing time
frequency distributions.
:returns: Generated signal
:rtype: numpy.ndarray
"""
np.random.seed(815)
length = 5 * 512
# Baseline low frequency plus noise.
data = np.sin(np.linspace(0, 80 * np.pi, length))
noise = np.random.ranf(length)
noise /= noise.max()
noise /= 15
data += noise
# Double last two fifths of the signal.
data[-2 * 512:] *= 2.0
chirp1 = 2.5 * np.sin(np.linspace(0, 400 * np.pi, 512))
chirp1 *= np.linspace(1, 0, 512)
data[512:2 * 512] += chirp1
# Add second transient signal.
chirp2 = 5.0 * np.sin(np.linspace(0, 200 * np.pi, 512))
chirp2 *= np.linspace(1, 0, 512)
data[3 * 512:4 * 512] += chirp2
return data | python | def signal_bursts():
np.random.seed(815)
length = 5 * 512
# Baseline low frequency plus noise.
data = np.sin(np.linspace(0, 80 * np.pi, length))
noise = np.random.ranf(length)
noise /= noise.max()
noise /= 15
data += noise
# Double last two fifths of the signal.
data[-2 * 512:] *= 2.0
chirp1 = 2.5 * np.sin(np.linspace(0, 400 * np.pi, 512))
chirp1 *= np.linspace(1, 0, 512)
data[512:2 * 512] += chirp1
# Add second transient signal.
chirp2 = 5.0 * np.sin(np.linspace(0, 200 * np.pi, 512))
chirp2 *= np.linspace(1, 0, 512)
data[3 * 512:4 * 512] += chirp2
return data | [
"def",
"signal_bursts",
"(",
")",
":",
"np",
".",
"random",
".",
"seed",
"(",
"815",
")",
"length",
"=",
"5",
"*",
"512",
"# Baseline low frequency plus noise.",
"data",
"=",
"np",
".",
"sin",
"(",
"np",
".",
"linspace",
"(",
"0",
",",
"80",
"*",
"np... | Generates a signal with two bursts inside. Useful for testing time
frequency distributions.
:returns: Generated signal
:rtype: numpy.ndarray | [
"Generates",
"a",
"signal",
"with",
"two",
"bursts",
"inside",
".",
"Useful",
"for",
"testing",
"time",
"frequency",
"distributions",
"."
] | 06561b6370f13fcb2e731470ba0f7314f4b2362d | https://github.com/krischer/mtspec/blob/06561b6370f13fcb2e731470ba0f7314f4b2362d/mtspec/util.py#L57-L86 |
25,483 | krischer/mtspec | mtspec/util.py | linear_chirp | def linear_chirp(npts=2000):
"""
Generates a simple linear chirp.
:param npts: Number of samples.
:type npts: int
:returns: Generated signal
:rtype: numpy.ndarray
"""
time = np.linspace(0, 20, npts)
chirp = np.sin(0.2 * np.pi * (0.1 + 24.0 / 2.0 * time) * time)
return chirp | python | def linear_chirp(npts=2000):
time = np.linspace(0, 20, npts)
chirp = np.sin(0.2 * np.pi * (0.1 + 24.0 / 2.0 * time) * time)
return chirp | [
"def",
"linear_chirp",
"(",
"npts",
"=",
"2000",
")",
":",
"time",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"20",
",",
"npts",
")",
"chirp",
"=",
"np",
".",
"sin",
"(",
"0.2",
"*",
"np",
".",
"pi",
"*",
"(",
"0.1",
"+",
"24.0",
"/",
"2.0",
... | Generates a simple linear chirp.
:param npts: Number of samples.
:type npts: int
:returns: Generated signal
:rtype: numpy.ndarray | [
"Generates",
"a",
"simple",
"linear",
"chirp",
"."
] | 06561b6370f13fcb2e731470ba0f7314f4b2362d | https://github.com/krischer/mtspec/blob/06561b6370f13fcb2e731470ba0f7314f4b2362d/mtspec/util.py#L89-L100 |
25,484 | krischer/mtspec | mtspec/util.py | exponential_chirp | def exponential_chirp(npts=2000):
"""
Generates an exponential chirp.
:param npts: Number of samples.
:type npts: int
:returns: Generated signal
:rtype: numpy.ndarray
"""
time = np.linspace(0, 20, npts)
chirp = np.sin(2 * np.pi * 0.2 * (1.3 ** time - 1) / np.log(1.3))
return chirp | python | def exponential_chirp(npts=2000):
time = np.linspace(0, 20, npts)
chirp = np.sin(2 * np.pi * 0.2 * (1.3 ** time - 1) / np.log(1.3))
return chirp | [
"def",
"exponential_chirp",
"(",
"npts",
"=",
"2000",
")",
":",
"time",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"20",
",",
"npts",
")",
"chirp",
"=",
"np",
".",
"sin",
"(",
"2",
"*",
"np",
".",
"pi",
"*",
"0.2",
"*",
"(",
"1.3",
"**",
"tim... | Generates an exponential chirp.
:param npts: Number of samples.
:type npts: int
:returns: Generated signal
:rtype: numpy.ndarray | [
"Generates",
"an",
"exponential",
"chirp",
"."
] | 06561b6370f13fcb2e731470ba0f7314f4b2362d | https://github.com/krischer/mtspec/blob/06561b6370f13fcb2e731470ba0f7314f4b2362d/mtspec/util.py#L103-L114 |
25,485 | krischer/mtspec | setup.py | get_libgfortran_dir | def get_libgfortran_dir():
"""
Helper function returning the library directory of libgfortran. Useful
on OSX where the C compiler oftentimes has no knowledge of the library
directories of the Fortran compiler. I don't think it can do any harm on
Linux.
"""
for ending in [".3.dylib", ".dylib", ".3.so", ".so"]:
try:
p = Popen(['gfortran', "-print-file-name=libgfortran" + ending],
stdout=PIPE, stderr=PIPE)
p.stderr.close()
line = p.stdout.readline().decode().strip()
p.stdout.close()
if os.path.exists(line):
return [os.path.dirname(line)]
except:
continue
return [] | python | def get_libgfortran_dir():
for ending in [".3.dylib", ".dylib", ".3.so", ".so"]:
try:
p = Popen(['gfortran', "-print-file-name=libgfortran" + ending],
stdout=PIPE, stderr=PIPE)
p.stderr.close()
line = p.stdout.readline().decode().strip()
p.stdout.close()
if os.path.exists(line):
return [os.path.dirname(line)]
except:
continue
return [] | [
"def",
"get_libgfortran_dir",
"(",
")",
":",
"for",
"ending",
"in",
"[",
"\".3.dylib\"",
",",
"\".dylib\"",
",",
"\".3.so\"",
",",
"\".so\"",
"]",
":",
"try",
":",
"p",
"=",
"Popen",
"(",
"[",
"'gfortran'",
",",
"\"-print-file-name=libgfortran\"",
"+",
"endi... | Helper function returning the library directory of libgfortran. Useful
on OSX where the C compiler oftentimes has no knowledge of the library
directories of the Fortran compiler. I don't think it can do any harm on
Linux. | [
"Helper",
"function",
"returning",
"the",
"library",
"directory",
"of",
"libgfortran",
".",
"Useful",
"on",
"OSX",
"where",
"the",
"C",
"compiler",
"oftentimes",
"has",
"no",
"knowledge",
"of",
"the",
"library",
"directories",
"of",
"the",
"Fortran",
"compiler",... | 06561b6370f13fcb2e731470ba0f7314f4b2362d | https://github.com/krischer/mtspec/blob/06561b6370f13fcb2e731470ba0f7314f4b2362d/setup.py#L116-L134 |
25,486 | pyGrowler/Growler | growler/utils/proto.py | PrototypeObject.create | def create(cls, obj):
"""
Create a new prototype object with the argument as the source
prototype.
.. Note:
This does not `initialize` the newly created object any
more than setting its prototype.
Calling the __init__ method is usually unnecessary as all
initialization data should be in the original prototype
object already.
If required, call __init__ explicitly:
>>> proto_obj = MyProtoObj(1, 2, 3)
>>> obj = MyProtoObj.create(proto_obj)
>>> obj.__init__(1, 2, 3)
"""
self = cls.__new__(cls)
self.__proto__ = obj
return self | python | def create(cls, obj):
self = cls.__new__(cls)
self.__proto__ = obj
return self | [
"def",
"create",
"(",
"cls",
",",
"obj",
")",
":",
"self",
"=",
"cls",
".",
"__new__",
"(",
"cls",
")",
"self",
".",
"__proto__",
"=",
"obj",
"return",
"self"
] | Create a new prototype object with the argument as the source
prototype.
.. Note:
This does not `initialize` the newly created object any
more than setting its prototype.
Calling the __init__ method is usually unnecessary as all
initialization data should be in the original prototype
object already.
If required, call __init__ explicitly:
>>> proto_obj = MyProtoObj(1, 2, 3)
>>> obj = MyProtoObj.create(proto_obj)
>>> obj.__init__(1, 2, 3) | [
"Create",
"a",
"new",
"prototype",
"object",
"with",
"the",
"argument",
"as",
"the",
"source",
"prototype",
"."
] | 90c923ff204f28b86a01d741224987a22f69540f | https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/utils/proto.py#L41-L63 |
25,487 | pyGrowler/Growler | growler/utils/proto.py | PrototypeObject.bind | def bind(self, func):
"""
Take a function and create a bound method
"""
if self.__methods__ is None:
self.__methods__ = {}
self.__methods__[func.__name__] = BoundFunction(func) | python | def bind(self, func):
if self.__methods__ is None:
self.__methods__ = {}
self.__methods__[func.__name__] = BoundFunction(func) | [
"def",
"bind",
"(",
"self",
",",
"func",
")",
":",
"if",
"self",
".",
"__methods__",
"is",
"None",
":",
"self",
".",
"__methods__",
"=",
"{",
"}",
"self",
".",
"__methods__",
"[",
"func",
".",
"__name__",
"]",
"=",
"BoundFunction",
"(",
"func",
")"
] | Take a function and create a bound method | [
"Take",
"a",
"function",
"and",
"create",
"a",
"bound",
"method"
] | 90c923ff204f28b86a01d741224987a22f69540f | https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/utils/proto.py#L65-L71 |
25,488 | pyGrowler/Growler | growler/utils/proto.py | PrototypeObject.has_own_property | def has_own_property(self, attr):
"""
Returns if the property
"""
try:
object.__getattribute__(self, attr)
except AttributeError:
return False
else:
return True | python | def has_own_property(self, attr):
try:
object.__getattribute__(self, attr)
except AttributeError:
return False
else:
return True | [
"def",
"has_own_property",
"(",
"self",
",",
"attr",
")",
":",
"try",
":",
"object",
".",
"__getattribute__",
"(",
"self",
",",
"attr",
")",
"except",
"AttributeError",
":",
"return",
"False",
"else",
":",
"return",
"True"
] | Returns if the property | [
"Returns",
"if",
"the",
"property"
] | 90c923ff204f28b86a01d741224987a22f69540f | https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/utils/proto.py#L73-L82 |
25,489 | pyGrowler/Growler | growler/core/application.py | Application.add_router | def add_router(self, path, router):
"""
Adds a router to the list of routers
Args:
path (str or regex): The path on which the router binds
router (growler.Router): The router which will respond to
requests
Raises:
TypeError: If `strict_router_check` attribute is True and
the router is not an instance of growler.Router.
"""
if self.strict_router_check and not isinstance(router, Router):
raise TypeError("Expected object of type Router, found %r" % type(router))
log.info("{} Adding router {} on path {}", id(self), router, path)
self.middleware.add(path=path,
func=router,
method_mask=HTTPMethod.ALL,) | python | def add_router(self, path, router):
if self.strict_router_check and not isinstance(router, Router):
raise TypeError("Expected object of type Router, found %r" % type(router))
log.info("{} Adding router {} on path {}", id(self), router, path)
self.middleware.add(path=path,
func=router,
method_mask=HTTPMethod.ALL,) | [
"def",
"add_router",
"(",
"self",
",",
"path",
",",
"router",
")",
":",
"if",
"self",
".",
"strict_router_check",
"and",
"not",
"isinstance",
"(",
"router",
",",
"Router",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected object of type Router, found %r\"",
"%",
... | Adds a router to the list of routers
Args:
path (str or regex): The path on which the router binds
router (growler.Router): The router which will respond to
requests
Raises:
TypeError: If `strict_router_check` attribute is True and
the router is not an instance of growler.Router. | [
"Adds",
"a",
"router",
"to",
"the",
"list",
"of",
"routers"
] | 90c923ff204f28b86a01d741224987a22f69540f | https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/core/application.py#L296-L315 |
25,490 | pyGrowler/Growler | growler/core/application.py | Application.create_server | def create_server(self,
loop=None,
as_coroutine=False,
protocol_factory=None,
**server_config):
"""
Helper function which constructs a listening server, using the
default growler.http.protocol.Protocol which responds to this
app.
This function exists only to remove boilerplate code for
starting up a growler app when using asyncio.
Args:
as_coroutine (bool): If True, this function does not wait
for the server to be created, and only returns the
coroutine generator object returned by loop.create_server.
This mode should be used when already inside an async
function.
The default mode is to call :method:`run_until_complete`
on the loop paramter, blocking until the server is
created and added to the event loop.
server_config (mixed): These keyword arguments parameters
are passed directly to the BaseEventLoop.create_server
function. Consult their documentation for details.
loop (BaseEventLoop): This is the asyncio event loop used
to provide the underlying `create_server` method, and,
if as_coroutine is False, will block until the server
is created.
protocol_factory (callable): Function returning an asyncio
protocol object (or more specifically, a
`growler.aio.GrowlerProtocol` object) to be called upon
client connection.
The default is the :class:`GrowlerHttpProtocol` factory
function.
**server_config (mixed): These keyword arguments parameters are
passed directly to the BaseEventLoop.create_server function.
Consult their documentation for details.
Returns:
asyncio.Server: The result of asyncio.BaseEventLoop.create_server
which has been passed to the event loop and setup with
the provided parameters. This is returned if gen_coroutine
is False (default).
asyncio.coroutine: An asyncio.coroutine which will
produce the asyncio.Server from the provided configuration parameters.
This is returned if gen_coroutine is True.
"""
if loop is None:
import asyncio
loop = asyncio.get_event_loop()
if protocol_factory is None:
from growler.aio import GrowlerHTTPProtocol
protocol_factory = GrowlerHTTPProtocol.get_factory
create_server = loop.create_server(
protocol_factory(self, loop=loop),
**server_config
)
if as_coroutine:
return create_server
else:
return loop.run_until_complete(create_server) | python | def create_server(self,
loop=None,
as_coroutine=False,
protocol_factory=None,
**server_config):
if loop is None:
import asyncio
loop = asyncio.get_event_loop()
if protocol_factory is None:
from growler.aio import GrowlerHTTPProtocol
protocol_factory = GrowlerHTTPProtocol.get_factory
create_server = loop.create_server(
protocol_factory(self, loop=loop),
**server_config
)
if as_coroutine:
return create_server
else:
return loop.run_until_complete(create_server) | [
"def",
"create_server",
"(",
"self",
",",
"loop",
"=",
"None",
",",
"as_coroutine",
"=",
"False",
",",
"protocol_factory",
"=",
"None",
",",
"*",
"*",
"server_config",
")",
":",
"if",
"loop",
"is",
"None",
":",
"import",
"asyncio",
"loop",
"=",
"asyncio"... | Helper function which constructs a listening server, using the
default growler.http.protocol.Protocol which responds to this
app.
This function exists only to remove boilerplate code for
starting up a growler app when using asyncio.
Args:
as_coroutine (bool): If True, this function does not wait
for the server to be created, and only returns the
coroutine generator object returned by loop.create_server.
This mode should be used when already inside an async
function.
The default mode is to call :method:`run_until_complete`
on the loop paramter, blocking until the server is
created and added to the event loop.
server_config (mixed): These keyword arguments parameters
are passed directly to the BaseEventLoop.create_server
function. Consult their documentation for details.
loop (BaseEventLoop): This is the asyncio event loop used
to provide the underlying `create_server` method, and,
if as_coroutine is False, will block until the server
is created.
protocol_factory (callable): Function returning an asyncio
protocol object (or more specifically, a
`growler.aio.GrowlerProtocol` object) to be called upon
client connection.
The default is the :class:`GrowlerHttpProtocol` factory
function.
**server_config (mixed): These keyword arguments parameters are
passed directly to the BaseEventLoop.create_server function.
Consult their documentation for details.
Returns:
asyncio.Server: The result of asyncio.BaseEventLoop.create_server
which has been passed to the event loop and setup with
the provided parameters. This is returned if gen_coroutine
is False (default).
asyncio.coroutine: An asyncio.coroutine which will
produce the asyncio.Server from the provided configuration parameters.
This is returned if gen_coroutine is True. | [
"Helper",
"function",
"which",
"constructs",
"a",
"listening",
"server",
"using",
"the",
"default",
"growler",
".",
"http",
".",
"protocol",
".",
"Protocol",
"which",
"responds",
"to",
"this",
"app",
"."
] | 90c923ff204f28b86a01d741224987a22f69540f | https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/core/application.py#L616-L683 |
25,491 | pyGrowler/Growler | growler/core/application.py | Application.create_server_and_run_forever | def create_server_and_run_forever(self, loop=None, **server_config):
"""
Helper function which constructs an HTTP server and listens the
loop forever.
This function exists only to remove boilerplate code for starting
up a growler app.
Args:
**server_config: These keyword arguments are forwarded
directly to the BaseEventLoop.create_server function.
Consult their documentation for details.
Parameters:
loop (asyncio.BaseEventLoop): Optional parameter for specifying
an event loop which will handle socket setup.
**server_config: These keyword arguments are forwarded directly to
the create_server function.
"""
if loop is None:
import asyncio
loop = asyncio.get_event_loop()
self.create_server(loop=loop, **server_config)
try:
loop.run_forever()
except KeyboardInterrupt:
pass | python | def create_server_and_run_forever(self, loop=None, **server_config):
if loop is None:
import asyncio
loop = asyncio.get_event_loop()
self.create_server(loop=loop, **server_config)
try:
loop.run_forever()
except KeyboardInterrupt:
pass | [
"def",
"create_server_and_run_forever",
"(",
"self",
",",
"loop",
"=",
"None",
",",
"*",
"*",
"server_config",
")",
":",
"if",
"loop",
"is",
"None",
":",
"import",
"asyncio",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"self",
".",
"create_ser... | Helper function which constructs an HTTP server and listens the
loop forever.
This function exists only to remove boilerplate code for starting
up a growler app.
Args:
**server_config: These keyword arguments are forwarded
directly to the BaseEventLoop.create_server function.
Consult their documentation for details.
Parameters:
loop (asyncio.BaseEventLoop): Optional parameter for specifying
an event loop which will handle socket setup.
**server_config: These keyword arguments are forwarded directly to
the create_server function. | [
"Helper",
"function",
"which",
"constructs",
"an",
"HTTP",
"server",
"and",
"listens",
"the",
"loop",
"forever",
"."
] | 90c923ff204f28b86a01d741224987a22f69540f | https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/core/application.py#L685-L712 |
25,492 | pyGrowler/Growler | growler/middleware/renderer.py | RenderEngine.find_template_filename | def find_template_filename(self, template_name):
"""
Searches for a file matching the given template name.
If found, this method returns the pathlib.Path object of the found
template file.
Args:
template_name (str): Name of the template, with or without a file
extension.
Returns:
pathlib.Path: Path to the matching filename.
"""
def next_file():
filename = self.path / template_name
yield filename
try:
exts = self.default_file_extensions
except AttributeError:
return
strfilename = str(filename)
for ext in exts:
yield Path(strfilename + ext)
for filename in next_file():
if filename.is_file():
return filename | python | def find_template_filename(self, template_name):
def next_file():
filename = self.path / template_name
yield filename
try:
exts = self.default_file_extensions
except AttributeError:
return
strfilename = str(filename)
for ext in exts:
yield Path(strfilename + ext)
for filename in next_file():
if filename.is_file():
return filename | [
"def",
"find_template_filename",
"(",
"self",
",",
"template_name",
")",
":",
"def",
"next_file",
"(",
")",
":",
"filename",
"=",
"self",
".",
"path",
"/",
"template_name",
"yield",
"filename",
"try",
":",
"exts",
"=",
"self",
".",
"default_file_extensions",
... | Searches for a file matching the given template name.
If found, this method returns the pathlib.Path object of the found
template file.
Args:
template_name (str): Name of the template, with or without a file
extension.
Returns:
pathlib.Path: Path to the matching filename. | [
"Searches",
"for",
"a",
"file",
"matching",
"the",
"given",
"template",
"name",
"."
] | 90c923ff204f28b86a01d741224987a22f69540f | https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/middleware/renderer.py#L141-L170 |
25,493 | pyGrowler/Growler | growler/http/responder.py | GrowlerHTTPResponder.set_request_line | def set_request_line(self, method, url, version):
"""
Sets the request line on the responder.
"""
self.parsed_request = (method, url, version)
self.request = {
'method': method,
'url': url,
'version': version
} | python | def set_request_line(self, method, url, version):
self.parsed_request = (method, url, version)
self.request = {
'method': method,
'url': url,
'version': version
} | [
"def",
"set_request_line",
"(",
"self",
",",
"method",
",",
"url",
",",
"version",
")",
":",
"self",
".",
"parsed_request",
"=",
"(",
"method",
",",
"url",
",",
"version",
")",
"self",
".",
"request",
"=",
"{",
"'method'",
":",
"method",
",",
"'url'",
... | Sets the request line on the responder. | [
"Sets",
"the",
"request",
"line",
"on",
"the",
"responder",
"."
] | 90c923ff204f28b86a01d741224987a22f69540f | https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/http/responder.py#L186-L195 |
25,494 | pyGrowler/Growler | growler/http/responder.py | GrowlerHTTPResponder.init_body_buffer | def init_body_buffer(self, method, headers):
"""
Sets up the body_buffer and content_length attributes based
on method and headers.
"""
content_length = headers.get("CONTENT-LENGTH", None)
if method in (HTTPMethod.POST, HTTPMethod.PUT):
if content_length is None:
raise HTTPErrorBadRequest("HTTP Method requires a CONTENT-LENGTH header")
self.content_length = int(content_length)
self.body_buffer = bytearray(0)
elif content_length is not None:
raise HTTPErrorBadRequest(
"HTTP method %s may NOT have a CONTENT-LENGTH header"
) | python | def init_body_buffer(self, method, headers):
content_length = headers.get("CONTENT-LENGTH", None)
if method in (HTTPMethod.POST, HTTPMethod.PUT):
if content_length is None:
raise HTTPErrorBadRequest("HTTP Method requires a CONTENT-LENGTH header")
self.content_length = int(content_length)
self.body_buffer = bytearray(0)
elif content_length is not None:
raise HTTPErrorBadRequest(
"HTTP method %s may NOT have a CONTENT-LENGTH header"
) | [
"def",
"init_body_buffer",
"(",
"self",
",",
"method",
",",
"headers",
")",
":",
"content_length",
"=",
"headers",
".",
"get",
"(",
"\"CONTENT-LENGTH\"",
",",
"None",
")",
"if",
"method",
"in",
"(",
"HTTPMethod",
".",
"POST",
",",
"HTTPMethod",
".",
"PUT",... | Sets up the body_buffer and content_length attributes based
on method and headers. | [
"Sets",
"up",
"the",
"body_buffer",
"and",
"content_length",
"attributes",
"based",
"on",
"method",
"and",
"headers",
"."
] | 90c923ff204f28b86a01d741224987a22f69540f | https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/http/responder.py#L197-L213 |
25,495 | pyGrowler/Growler | growler/http/responder.py | GrowlerHTTPResponder.build_req_and_res | def build_req_and_res(self):
"""
Simple method which calls the request and response factories
the responder was given, and returns the pair.
"""
req = self.build_req(self, self.headers)
res = self.build_res(self._handler)
return req, res | python | def build_req_and_res(self):
req = self.build_req(self, self.headers)
res = self.build_res(self._handler)
return req, res | [
"def",
"build_req_and_res",
"(",
"self",
")",
":",
"req",
"=",
"self",
".",
"build_req",
"(",
"self",
",",
"self",
".",
"headers",
")",
"res",
"=",
"self",
".",
"build_res",
"(",
"self",
".",
"_handler",
")",
"return",
"req",
",",
"res"
] | Simple method which calls the request and response factories
the responder was given, and returns the pair. | [
"Simple",
"method",
"which",
"calls",
"the",
"request",
"and",
"response",
"factories",
"the",
"responder",
"was",
"given",
"and",
"returns",
"the",
"pair",
"."
] | 90c923ff204f28b86a01d741224987a22f69540f | https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/http/responder.py#L215-L222 |
25,496 | pyGrowler/Growler | growler/http/responder.py | GrowlerHTTPResponder.validate_and_store_body_data | def validate_and_store_body_data(self, data):
"""
Attempts simple body data validation by comparining incoming
data to the content length header.
If passes store the data into self._buffer.
Parameters:
data (bytes): Incoming client data to be added to the body
Raises:
HTTPErrorBadRequest: Raised if data is sent when not
expected, or if too much data is sent.
"""
# add data to end of buffer
self.body_buffer[-1:] = data
#
if len(self.body_buffer) > self.content_length:
problem = "Content length exceeds expected value (%d > %d)" % (
len(self.body_buffer), self.content_length
)
raise HTTPErrorBadRequest(phrase=problem) | python | def validate_and_store_body_data(self, data):
# add data to end of buffer
self.body_buffer[-1:] = data
#
if len(self.body_buffer) > self.content_length:
problem = "Content length exceeds expected value (%d > %d)" % (
len(self.body_buffer), self.content_length
)
raise HTTPErrorBadRequest(phrase=problem) | [
"def",
"validate_and_store_body_data",
"(",
"self",
",",
"data",
")",
":",
"# add data to end of buffer",
"self",
".",
"body_buffer",
"[",
"-",
"1",
":",
"]",
"=",
"data",
"#",
"if",
"len",
"(",
"self",
".",
"body_buffer",
")",
">",
"self",
".",
"content_l... | Attempts simple body data validation by comparining incoming
data to the content length header.
If passes store the data into self._buffer.
Parameters:
data (bytes): Incoming client data to be added to the body
Raises:
HTTPErrorBadRequest: Raised if data is sent when not
expected, or if too much data is sent. | [
"Attempts",
"simple",
"body",
"data",
"validation",
"by",
"comparining",
"incoming",
"data",
"to",
"the",
"content",
"length",
"header",
".",
"If",
"passes",
"store",
"the",
"data",
"into",
"self",
".",
"_buffer",
"."
] | 90c923ff204f28b86a01d741224987a22f69540f | https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/http/responder.py#L224-L246 |
25,497 | pyGrowler/Growler | growler/aio/http_protocol.py | GrowlerHTTPProtocol.begin_application | def begin_application(self, req, res):
"""
Entry point for the application middleware chain for an asyncio
event loop.
"""
# Add the middleware processing to the event loop - this *should*
# change the call stack so any server errors do not link back to this
# function
self.loop.create_task(self.http_application.handle_client_request(req, res)) | python | def begin_application(self, req, res):
# Add the middleware processing to the event loop - this *should*
# change the call stack so any server errors do not link back to this
# function
self.loop.create_task(self.http_application.handle_client_request(req, res)) | [
"def",
"begin_application",
"(",
"self",
",",
"req",
",",
"res",
")",
":",
"# Add the middleware processing to the event loop - this *should*",
"# change the call stack so any server errors do not link back to this",
"# function",
"self",
".",
"loop",
".",
"create_task",
"(",
"... | Entry point for the application middleware chain for an asyncio
event loop. | [
"Entry",
"point",
"for",
"the",
"application",
"middleware",
"chain",
"for",
"an",
"asyncio",
"event",
"loop",
"."
] | 90c923ff204f28b86a01d741224987a22f69540f | https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/aio/http_protocol.py#L137-L145 |
25,498 | pyGrowler/Growler | growler/middleware/static.py | Static.calculate_etag | def calculate_etag(file_path):
"""
Calculate an etag value
Args:
a_file (pathlib.Path): The filepath to the
Returns:
String of the etag value to be sent back in header
"""
stat = file_path.stat()
etag = "%x-%x" % (stat.st_mtime_ns, stat.st_size)
return etag | python | def calculate_etag(file_path):
stat = file_path.stat()
etag = "%x-%x" % (stat.st_mtime_ns, stat.st_size)
return etag | [
"def",
"calculate_etag",
"(",
"file_path",
")",
":",
"stat",
"=",
"file_path",
".",
"stat",
"(",
")",
"etag",
"=",
"\"%x-%x\"",
"%",
"(",
"stat",
".",
"st_mtime_ns",
",",
"stat",
".",
"st_size",
")",
"return",
"etag"
] | Calculate an etag value
Args:
a_file (pathlib.Path): The filepath to the
Returns:
String of the etag value to be sent back in header | [
"Calculate",
"an",
"etag",
"value"
] | 90c923ff204f28b86a01d741224987a22f69540f | https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/middleware/static.py#L81-L93 |
25,499 | pyGrowler/Growler | growler/http/response.py | HTTPResponse._set_default_headers | def _set_default_headers(self):
"""
Create some default headers that should be sent along with every HTTP
response
"""
self.headers.setdefault('Date', self.get_current_time)
self.headers.setdefault('Server', self.SERVER_INFO)
self.headers.setdefault('Content-Length', "%d" % len(self.message))
if self.app.enabled('x-powered-by'):
self.headers.setdefault('X-Powered-By', 'Growler') | python | def _set_default_headers(self):
self.headers.setdefault('Date', self.get_current_time)
self.headers.setdefault('Server', self.SERVER_INFO)
self.headers.setdefault('Content-Length', "%d" % len(self.message))
if self.app.enabled('x-powered-by'):
self.headers.setdefault('X-Powered-By', 'Growler') | [
"def",
"_set_default_headers",
"(",
"self",
")",
":",
"self",
".",
"headers",
".",
"setdefault",
"(",
"'Date'",
",",
"self",
".",
"get_current_time",
")",
"self",
".",
"headers",
".",
"setdefault",
"(",
"'Server'",
",",
"self",
".",
"SERVER_INFO",
")",
"se... | Create some default headers that should be sent along with every HTTP
response | [
"Create",
"some",
"default",
"headers",
"that",
"should",
"be",
"sent",
"along",
"with",
"every",
"HTTP",
"response"
] | 90c923ff204f28b86a01d741224987a22f69540f | https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/http/response.py#L65-L74 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.