repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_documentation_string stringlengths 1 47.2k | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|
timknip/pyswf | swf/tag.py | SWFTimelineContainer.get_dependencies | def get_dependencies(self):
""" Returns the character ids this tag refers to """
s = super(SWFTimelineContainer, self).get_dependencies()
for dt in self.all_tags_of_type(DefinitionTag):
s.update(dt.get_dependencies())
return s | python | def get_dependencies(self):
""" Returns the character ids this tag refers to """
s = super(SWFTimelineContainer, self).get_dependencies()
for dt in self.all_tags_of_type(DefinitionTag):
s.update(dt.get_dependencies())
return s | Returns the character ids this tag refers to | https://github.com/timknip/pyswf/blob/3740cc80d7650156831e728ea0d408819e5671eb/swf/tag.py#L151-L156 |
timknip/pyswf | swf/tag.py | SWFTimelineContainer.all_tags_of_type | def all_tags_of_type(self, type_or_types, recurse_into_sprites = True):
"""
Generator for all tags of the given type_or_types.
Generates in breadth-first order, optionally including all sub-containers.
"""
for t in self.tags:
if isinstance(t, type_or_types):
... | python | def all_tags_of_type(self, type_or_types, recurse_into_sprites = True):
"""
Generator for all tags of the given type_or_types.
Generates in breadth-first order, optionally including all sub-containers.
"""
for t in self.tags:
if isinstance(t, type_or_types):
... | Generator for all tags of the given type_or_types.
Generates in breadth-first order, optionally including all sub-containers. | https://github.com/timknip/pyswf/blob/3740cc80d7650156831e728ea0d408819e5671eb/swf/tag.py#L197-L211 |
timknip/pyswf | swf/tag.py | SWFTimelineContainer.build_dictionary | def build_dictionary(self):
"""
Return a dictionary of characterIds to their defining tags.
"""
d = {}
for t in self.all_tags_of_type(DefinitionTag, recurse_into_sprites = False):
if t.characterId in d:
#print 'redefinition of characterId %d:' % (t.cha... | python | def build_dictionary(self):
"""
Return a dictionary of characterIds to their defining tags.
"""
d = {}
for t in self.all_tags_of_type(DefinitionTag, recurse_into_sprites = False):
if t.characterId in d:
#print 'redefinition of characterId %d:' % (t.cha... | Return a dictionary of characterIds to their defining tags. | https://github.com/timknip/pyswf/blob/3740cc80d7650156831e728ea0d408819e5671eb/swf/tag.py#L213-L225 |
timknip/pyswf | swf/tag.py | SWFTimelineContainer.collect_sound_streams | def collect_sound_streams(self):
"""
Return a list of sound streams in this timeline and its children.
The streams are returned in order with respect to the timeline.
A stream is returned as a list: the first element is the tag
which introduced that stream; other elements are th... | python | def collect_sound_streams(self):
"""
Return a list of sound streams in this timeline and its children.
The streams are returned in order with respect to the timeline.
A stream is returned as a list: the first element is the tag
which introduced that stream; other elements are th... | Return a list of sound streams in this timeline and its children.
The streams are returned in order with respect to the timeline.
A stream is returned as a list: the first element is the tag
which introduced that stream; other elements are the tags
which made up the stream body (if any)... | https://github.com/timknip/pyswf/blob/3740cc80d7650156831e728ea0d408819e5671eb/swf/tag.py#L227-L247 |
timknip/pyswf | swf/tag.py | SWFTimelineContainer.collect_video_streams | def collect_video_streams(self):
"""
Return a list of video streams in this timeline and its children.
The streams are returned in order with respect to the timeline.
A stream is returned as a list: the first element is the tag
which introduced that stream; other elements are th... | python | def collect_video_streams(self):
"""
Return a list of video streams in this timeline and its children.
The streams are returned in order with respect to the timeline.
A stream is returned as a list: the first element is the tag
which introduced that stream; other elements are th... | Return a list of video streams in this timeline and its children.
The streams are returned in order with respect to the timeline.
A stream is returned as a list: the first element is the tag
which introduced that stream; other elements are the tags
which made up the stream body (if any)... | https://github.com/timknip/pyswf/blob/3740cc80d7650156831e728ea0d408819e5671eb/swf/tag.py#L249-L273 |
timknip/pyswf | swf/tag.py | TagPlaceObject.parse | def parse(self, data, length, version=1):
""" Parses this tag """
pos = data.tell()
self.characterId = data.readUI16()
self.depth = data.readUI16();
self.matrix = data.readMATRIX();
self.hasCharacter = True;
self.hasMatrix = True;
if data.tell() - pos < le... | python | def parse(self, data, length, version=1):
""" Parses this tag """
pos = data.tell()
self.characterId = data.readUI16()
self.depth = data.readUI16();
self.matrix = data.readMATRIX();
self.hasCharacter = True;
self.hasMatrix = True;
if data.tell() - pos < le... | Parses this tag | https://github.com/timknip/pyswf/blob/3740cc80d7650156831e728ea0d408819e5671eb/swf/tag.py#L416-L426 |
timknip/pyswf | swf/tag.py | TagRemoveObject.parse | def parse(self, data, length, version=1):
""" Parses this tag """
self.characterId = data.readUI16()
self.depth = data.readUI16() | python | def parse(self, data, length, version=1):
""" Parses this tag """
self.characterId = data.readUI16()
self.depth = data.readUI16() | Parses this tag | https://github.com/timknip/pyswf/blob/3740cc80d7650156831e728ea0d408819e5671eb/swf/tag.py#L484-L487 |
timknip/pyswf | swf/export.py | SVGExporter.export | def export(self, swf, force_stroke=False):
""" Exports the specified SWF to SVG.
@param swf The SWF.
@param force_stroke Whether to force strokes on non-stroked fills.
"""
self.svg = self._e.svg(version=SVG_VERSION)
self.force_stroke = force_stroke
self.defs = s... | python | def export(self, swf, force_stroke=False):
""" Exports the specified SWF to SVG.
@param swf The SWF.
@param force_stroke Whether to force strokes on non-stroked fills.
"""
self.svg = self._e.svg(version=SVG_VERSION)
self.force_stroke = force_stroke
self.defs = s... | Exports the specified SWF to SVG.
@param swf The SWF.
@param force_stroke Whether to force strokes on non-stroked fills. | https://github.com/timknip/pyswf/blob/3740cc80d7650156831e728ea0d408819e5671eb/swf/export.py#L514-L546 |
timknip/pyswf | swf/export.py | SingleShapeSVGExporterMixin.export | def export(self, swf, shape, **export_opts):
""" Exports the specified shape of the SWF to SVG.
@param swf The SWF.
@param shape Which shape to export, either by characterId(int) or as a Tag object.
"""
# If `shape` is given as int, find corresponding shape tag.
if is... | python | def export(self, swf, shape, **export_opts):
""" Exports the specified shape of the SWF to SVG.
@param swf The SWF.
@param shape Which shape to export, either by characterId(int) or as a Tag object.
"""
# If `shape` is given as int, find corresponding shape tag.
if is... | Exports the specified shape of the SWF to SVG.
@param swf The SWF.
@param shape Which shape to export, either by characterId(int) or as a Tag object. | https://github.com/timknip/pyswf/blob/3740cc80d7650156831e728ea0d408819e5671eb/swf/export.py#L827-L876 |
timknip/pyswf | swf/export.py | FrameSVGExporterMixin.export | def export(self, swf, frame, **export_opts):
""" Exports a frame of the specified SWF to SVG.
@param swf The SWF.
@param frame Which frame to export, by 0-based index (int)
"""
self.wanted_frame = frame
return super(FrameSVGExporterMixin, self).export(swf, *export_opts... | python | def export(self, swf, frame, **export_opts):
""" Exports a frame of the specified SWF to SVG.
@param swf The SWF.
@param frame Which frame to export, by 0-based index (int)
"""
self.wanted_frame = frame
return super(FrameSVGExporterMixin, self).export(swf, *export_opts... | Exports a frame of the specified SWF to SVG.
@param swf The SWF.
@param frame Which frame to export, by 0-based index (int) | https://github.com/timknip/pyswf/blob/3740cc80d7650156831e728ea0d408819e5671eb/swf/export.py#L879-L886 |
scikit-hep/probfit | probfit/util.py | parse_arg | def parse_arg(f, kwd, offset=0):
"""
convert dictionary of keyword argument and value to positional argument
equivalent to::
vnames = describe(f)
return tuple([kwd[k] for k in vnames[offset:]])
"""
vnames = describe(f)
return tuple([kwd[k] for k in vnames[offset:]]) | python | def parse_arg(f, kwd, offset=0):
"""
convert dictionary of keyword argument and value to positional argument
equivalent to::
vnames = describe(f)
return tuple([kwd[k] for k in vnames[offset:]])
"""
vnames = describe(f)
return tuple([kwd[k] for k in vnames[offset:]]) | convert dictionary of keyword argument and value to positional argument
equivalent to::
vnames = describe(f)
return tuple([kwd[k] for k in vnames[offset:]]) | https://github.com/scikit-hep/probfit/blob/de3593798ea3877dd2785062bed6877dd9058a02/probfit/util.py#L4-L14 |
scikit-hep/probfit | probfit/plotting.py | _get_args_and_errors | def _get_args_and_errors(self, minuit=None, args=None, errors=None):
"""
consistent algorithm to get argument and errors
1) get it from minuit if minuit is available
2) if not get it from args and errors
2.1) if args is dict parse it.
3) if all else fail get it from self.last_arg
"""
ret... | python | def _get_args_and_errors(self, minuit=None, args=None, errors=None):
"""
consistent algorithm to get argument and errors
1) get it from minuit if minuit is available
2) if not get it from args and errors
2.1) if args is dict parse it.
3) if all else fail get it from self.last_arg
"""
ret... | consistent algorithm to get argument and errors
1) get it from minuit if minuit is available
2) if not get it from args and errors
2.1) if args is dict parse it.
3) if all else fail get it from self.last_arg | https://github.com/scikit-hep/probfit/blob/de3593798ea3877dd2785062bed6877dd9058a02/probfit/plotting.py#L28-L55 |
scikit-hep/probfit | probfit/plotting.py | draw_residual | def draw_residual(x, y, yerr, xerr,
show_errbars=True, ax=None,
zero_line=True, grid=True,
**kwargs):
"""Draw a residual plot on the axis.
By default, if show_errbars if True, residuals are drawn as blue points
with errorbars with no endcaps. If show_er... | python | def draw_residual(x, y, yerr, xerr,
show_errbars=True, ax=None,
zero_line=True, grid=True,
**kwargs):
"""Draw a residual plot on the axis.
By default, if show_errbars if True, residuals are drawn as blue points
with errorbars with no endcaps. If show_er... | Draw a residual plot on the axis.
By default, if show_errbars if True, residuals are drawn as blue points
with errorbars with no endcaps. If show_errbars is False, residuals are
drawn as a bar graph with black bars.
**Arguments**
- **x** array of numbers, x-coordinates
- **y** array ... | https://github.com/scikit-hep/probfit/blob/de3593798ea3877dd2785062bed6877dd9058a02/probfit/plotting.py#L135-L193 |
scikit-hep/probfit | probfit/plotting.py | draw_compare | def draw_compare(f, arg, edges, data, errors=None, ax=None, grid=True, normed=False, parts=False):
"""
TODO: this needs to be rewritten
"""
from matplotlib import pyplot as plt
# arg is either map or tuple
ax = plt.gca() if ax is None else ax
arg = parse_arg(f, arg, 1) if isinstance(arg, di... | python | def draw_compare(f, arg, edges, data, errors=None, ax=None, grid=True, normed=False, parts=False):
"""
TODO: this needs to be rewritten
"""
from matplotlib import pyplot as plt
# arg is either map or tuple
ax = plt.gca() if ax is None else ax
arg = parse_arg(f, arg, 1) if isinstance(arg, di... | TODO: this needs to be rewritten | https://github.com/scikit-hep/probfit/blob/de3593798ea3877dd2785062bed6877dd9058a02/probfit/plotting.py#L474-L511 |
scikit-hep/probfit | probfit/plotting.py | draw_pdf | def draw_pdf(f, arg, bound, bins=100, scale=1.0, density=True,
normed_pdf=False, ax=None, **kwds):
"""
draw pdf with given argument and bounds.
**Arguments**
* **f** your pdf. The first argument is assumed to be independent
variable
* **arg** argument can be tuple o... | python | def draw_pdf(f, arg, bound, bins=100, scale=1.0, density=True,
normed_pdf=False, ax=None, **kwds):
"""
draw pdf with given argument and bounds.
**Arguments**
* **f** your pdf. The first argument is assumed to be independent
variable
* **arg** argument can be tuple o... | draw pdf with given argument and bounds.
**Arguments**
* **f** your pdf. The first argument is assumed to be independent
variable
* **arg** argument can be tuple or list
* **bound** tuple(xmin,xmax)
* **bins** number of bins to plot pdf. Default 100.
* **scale... | https://github.com/scikit-hep/probfit/blob/de3593798ea3877dd2785062bed6877dd9058a02/probfit/plotting.py#L519-L550 |
scikit-hep/probfit | probfit/plotting.py | draw_compare_hist | def draw_compare_hist(f, arg, data, bins=100, bound=None, ax=None, weights=None,
normed=False, use_w2=False, parts=False, grid=True):
"""
draw histogram of data with poisson error bar and f(x,*arg).
::
data = np.random.rand(10000)
f = gaussian
draw_compare_his... | python | def draw_compare_hist(f, arg, data, bins=100, bound=None, ax=None, weights=None,
normed=False, use_w2=False, parts=False, grid=True):
"""
draw histogram of data with poisson error bar and f(x,*arg).
::
data = np.random.rand(10000)
f = gaussian
draw_compare_his... | draw histogram of data with poisson error bar and f(x,*arg).
::
data = np.random.rand(10000)
f = gaussian
draw_compare_hist(f, {'mean':0,'sigma':1}, data, normed=True)
**Arguments**
- **f**
- **arg** argument pass to f. Can be dictionary or list.
- **data** da... | https://github.com/scikit-hep/probfit/blob/de3593798ea3877dd2785062bed6877dd9058a02/probfit/plotting.py#L583-L622 |
scikit-hep/probfit | probfit/toy.py | gen_toyn | def gen_toyn(f, nsample, ntoy, bound, accuracy=10000, quiet=True, **kwd):
"""
just alias of gentoy for nample and then reshape to ntoy,nsample)
:param f:
:param nsample:
:param bound:
:param accuracy:
:param quiet:
:param kwd:
:return:
"""
return gen_toy(f, nsample * ntoy, bo... | python | def gen_toyn(f, nsample, ntoy, bound, accuracy=10000, quiet=True, **kwd):
"""
just alias of gentoy for nample and then reshape to ntoy,nsample)
:param f:
:param nsample:
:param bound:
:param accuracy:
:param quiet:
:param kwd:
:return:
"""
return gen_toy(f, nsample * ntoy, bo... | just alias of gentoy for nample and then reshape to ntoy,nsample)
:param f:
:param nsample:
:param bound:
:param accuracy:
:param quiet:
:param kwd:
:return: | https://github.com/scikit-hep/probfit/blob/de3593798ea3877dd2785062bed6877dd9058a02/probfit/toy.py#L14-L25 |
scikit-hep/probfit | probfit/toy.py | gen_toy | def gen_toy(f, nsample, bound, accuracy=10000, quiet=True, **kwd):
"""
generate ntoy
:param f:
:param nsample:
:param ntoy:
:param bound:
:param accuracy:
:param quiet:
:param kwd: the rest of keyword argument will be passed to f
:return: numpy.ndarray
"""
# based on inve... | python | def gen_toy(f, nsample, bound, accuracy=10000, quiet=True, **kwd):
"""
generate ntoy
:param f:
:param nsample:
:param ntoy:
:param bound:
:param accuracy:
:param quiet:
:param kwd: the rest of keyword argument will be passed to f
:return: numpy.ndarray
"""
# based on inve... | generate ntoy
:param f:
:param nsample:
:param ntoy:
:param bound:
:param accuracy:
:param quiet:
:param kwd: the rest of keyword argument will be passed to f
:return: numpy.ndarray | https://github.com/scikit-hep/probfit/blob/de3593798ea3877dd2785062bed6877dd9058a02/probfit/toy.py#L28-L81 |
scikit-hep/probfit | probfit/oneshot.py | fit_uml | def fit_uml(f, data, quiet=False, print_level=0, *arg, **kwd):
"""
perform unbinned likelihood fit
:param f: pdf
:param data: data
:param quiet: if not quite draw latest fit on fail fit
:param printlevel: minuit printlevel
:return:
"""
uml = UnbinnedLH(f, data)
minuit = Minuit(um... | python | def fit_uml(f, data, quiet=False, print_level=0, *arg, **kwd):
"""
perform unbinned likelihood fit
:param f: pdf
:param data: data
:param quiet: if not quite draw latest fit on fail fit
:param printlevel: minuit printlevel
:return:
"""
uml = UnbinnedLH(f, data)
minuit = Minuit(um... | perform unbinned likelihood fit
:param f: pdf
:param data: data
:param quiet: if not quite draw latest fit on fail fit
:param printlevel: minuit printlevel
:return: | https://github.com/scikit-hep/probfit/blob/de3593798ea3877dd2785062bed6877dd9058a02/probfit/oneshot.py#L11-L30 |
scikit-hep/probfit | probfit/oneshot.py | fit_binx2 | def fit_binx2(f, data, bins=30, bound=None, print_level=0, quiet=False, *arg, **kwd):
"""
perform chi^2 fit
:param f:
:param data:
:param bins:
:param range:
:param printlevel:
:param quiet:
:param arg:
:param kwd:
:return:
"""
uml = BinnedChi2(f, data, bins=bins, bou... | python | def fit_binx2(f, data, bins=30, bound=None, print_level=0, quiet=False, *arg, **kwd):
"""
perform chi^2 fit
:param f:
:param data:
:param bins:
:param range:
:param printlevel:
:param quiet:
:param arg:
:param kwd:
:return:
"""
uml = BinnedChi2(f, data, bins=bins, bou... | perform chi^2 fit
:param f:
:param data:
:param bins:
:param range:
:param printlevel:
:param quiet:
:param arg:
:param kwd:
:return: | https://github.com/scikit-hep/probfit/blob/de3593798ea3877dd2785062bed6877dd9058a02/probfit/oneshot.py#L33-L57 |
scikit-hep/probfit | probfit/oneshot.py | fit_binlh | def fit_binlh(f, data, bins=30,
bound=None, quiet=False, weights=None, use_w2=False,
print_level=0, pedantic=True, extended=False,
*arg, **kwd):
"""
perform bin likelihood fit
:param f:
:param data:
:param bins:
:param range:
:param quiet:
:param... | python | def fit_binlh(f, data, bins=30,
bound=None, quiet=False, weights=None, use_w2=False,
print_level=0, pedantic=True, extended=False,
*arg, **kwd):
"""
perform bin likelihood fit
:param f:
:param data:
:param bins:
:param range:
:param quiet:
:param... | perform bin likelihood fit
:param f:
:param data:
:param bins:
:param range:
:param quiet:
:param weights:
:param use_w2:
:param printlevel:
:param pedantic:
:param extended:
:param arg:
:param kwd:
:return: | https://github.com/scikit-hep/probfit/blob/de3593798ea3877dd2785062bed6877dd9058a02/probfit/oneshot.py#L60-L91 |
scikit-hep/probfit | probfit/oneshot.py | pprint_arg | def pprint_arg(vnames, value):
"""
pretty print argument
:param vnames:
:param value:
:return:
"""
ret = ''
for name, v in zip(vnames, value):
ret += '%s=%s;' % (name, str(v))
return ret; | python | def pprint_arg(vnames, value):
"""
pretty print argument
:param vnames:
:param value:
:return:
"""
ret = ''
for name, v in zip(vnames, value):
ret += '%s=%s;' % (name, str(v))
return ret; | pretty print argument
:param vnames:
:param value:
:return: | https://github.com/scikit-hep/probfit/blob/de3593798ea3877dd2785062bed6877dd9058a02/probfit/oneshot.py#L105-L115 |
scikit-hep/probfit | tutorial/tutorial.py | gauss_pdf | def gauss_pdf(x, mu, sigma):
"""Normalized Gaussian"""
return 1 / np.sqrt(2 * np.pi) / sigma * np.exp(-(x - mu) ** 2 / 2. / sigma ** 2) | python | def gauss_pdf(x, mu, sigma):
"""Normalized Gaussian"""
return 1 / np.sqrt(2 * np.pi) / sigma * np.exp(-(x - mu) ** 2 / 2. / sigma ** 2) | Normalized Gaussian | https://github.com/scikit-hep/probfit/blob/de3593798ea3877dd2785062bed6877dd9058a02/tutorial/tutorial.py#L161-L163 |
jmcarp/betfair.py | betfair/utils.py | get_chunks | def get_chunks(sequence, chunk_size):
"""Split sequence into chunks.
:param list sequence:
:param int chunk_size:
"""
return [
sequence[idx:idx + chunk_size]
for idx in range(0, len(sequence), chunk_size)
] | python | def get_chunks(sequence, chunk_size):
"""Split sequence into chunks.
:param list sequence:
:param int chunk_size:
"""
return [
sequence[idx:idx + chunk_size]
for idx in range(0, len(sequence), chunk_size)
] | Split sequence into chunks.
:param list sequence:
:param int chunk_size: | https://github.com/jmcarp/betfair.py/blob/116df2fdc512575d1b4c4f1749d4a5bf98e519ff/betfair/utils.py#L19-L28 |
jmcarp/betfair.py | betfair/utils.py | get_kwargs | def get_kwargs(kwargs):
"""Get all keys and values from dictionary where key is not `self`.
:param dict kwargs: Input parameters
"""
return {
key: value for key, value in six.iteritems(kwargs)
if key != 'self'
} | python | def get_kwargs(kwargs):
"""Get all keys and values from dictionary where key is not `self`.
:param dict kwargs: Input parameters
"""
return {
key: value for key, value in six.iteritems(kwargs)
if key != 'self'
} | Get all keys and values from dictionary where key is not `self`.
:param dict kwargs: Input parameters | https://github.com/jmcarp/betfair.py/blob/116df2fdc512575d1b4c4f1749d4a5bf98e519ff/betfair/utils.py#L31-L39 |
jmcarp/betfair.py | betfair/utils.py | check_status_code | def check_status_code(response, codes=None):
"""Check HTTP status code and raise exception if incorrect.
:param Response response: HTTP response
:param codes: List of accepted codes or callable
:raises: ApiError if code invalid
"""
codes = codes or [httplib.OK]
checker = (
codes
... | python | def check_status_code(response, codes=None):
"""Check HTTP status code and raise exception if incorrect.
:param Response response: HTTP response
:param codes: List of accepted codes or callable
:raises: ApiError if code invalid
"""
codes = codes or [httplib.OK]
checker = (
codes
... | Check HTTP status code and raise exception if incorrect.
:param Response response: HTTP response
:param codes: List of accepted codes or callable
:raises: ApiError if code invalid | https://github.com/jmcarp/betfair.py/blob/116df2fdc512575d1b4c4f1749d4a5bf98e519ff/betfair/utils.py#L42-L56 |
jmcarp/betfair.py | betfair/utils.py | result_or_error | def result_or_error(response):
"""Get `result` field from Betfair response or raise exception if not
found.
:param Response response:
:raises: ApiError if no results passed
"""
data = response.json()
result = data.get('result')
if result is not None:
return result
raise exce... | python | def result_or_error(response):
"""Get `result` field from Betfair response or raise exception if not
found.
:param Response response:
:raises: ApiError if no results passed
"""
data = response.json()
result = data.get('result')
if result is not None:
return result
raise exce... | Get `result` field from Betfair response or raise exception if not
found.
:param Response response:
:raises: ApiError if no results passed | https://github.com/jmcarp/betfair.py/blob/116df2fdc512575d1b4c4f1749d4a5bf98e519ff/betfair/utils.py#L59-L70 |
jmcarp/betfair.py | betfair/utils.py | process_result | def process_result(result, model=None):
"""Cast response JSON to Betfair model(s).
:param result: Betfair response JSON
:param BetfairModel model: Deserialization format; if `None`, return raw
JSON
"""
if model is None:
return result
if isinstance(result, collections.Sequence):
... | python | def process_result(result, model=None):
"""Cast response JSON to Betfair model(s).
:param result: Betfair response JSON
:param BetfairModel model: Deserialization format; if `None`, return raw
JSON
"""
if model is None:
return result
if isinstance(result, collections.Sequence):
... | Cast response JSON to Betfair model(s).
:param result: Betfair response JSON
:param BetfairModel model: Deserialization format; if `None`, return raw
JSON | https://github.com/jmcarp/betfair.py/blob/116df2fdc512575d1b4c4f1749d4a5bf98e519ff/betfair/utils.py#L73-L84 |
jmcarp/betfair.py | betfair/utils.py | make_payload | def make_payload(base, method, params):
"""Build Betfair JSON-RPC payload.
:param str base: Betfair base ("Sports" or "Account")
:param str method: Betfair endpoint
:param dict params: Request parameters
"""
payload = {
'jsonrpc': '2.0',
'method': '{base}APING/v1.0/{method}'.for... | python | def make_payload(base, method, params):
"""Build Betfair JSON-RPC payload.
:param str base: Betfair base ("Sports" or "Account")
:param str method: Betfair endpoint
:param dict params: Request parameters
"""
payload = {
'jsonrpc': '2.0',
'method': '{base}APING/v1.0/{method}'.for... | Build Betfair JSON-RPC payload.
:param str base: Betfair base ("Sports" or "Account")
:param str method: Betfair endpoint
:param dict params: Request parameters | https://github.com/jmcarp/betfair.py/blob/116df2fdc512575d1b4c4f1749d4a5bf98e519ff/betfair/utils.py#L100-L113 |
jmcarp/betfair.py | betfair/utils.py | requires_login | def requires_login(func, *args, **kwargs):
"""Decorator to check that the user is logged in. Raises `BetfairError`
if instance variable `session_token` is absent.
"""
self = args[0]
if self.session_token:
return func(*args, **kwargs)
raise exceptions.NotLoggedIn() | python | def requires_login(func, *args, **kwargs):
"""Decorator to check that the user is logged in. Raises `BetfairError`
if instance variable `session_token` is absent.
"""
self = args[0]
if self.session_token:
return func(*args, **kwargs)
raise exceptions.NotLoggedIn() | Decorator to check that the user is logged in. Raises `BetfairError`
if instance variable `session_token` is absent. | https://github.com/jmcarp/betfair.py/blob/116df2fdc512575d1b4c4f1749d4a5bf98e519ff/betfair/utils.py#L117-L124 |
jmcarp/betfair.py | betfair/price.py | nearest_price | def nearest_price(price, cutoffs=CUTOFFS):
"""Returns the nearest Betfair odds value to price.
Adapted from Anton Zemlyanov's AlgoTrader project (MIT licensed).
https://github.com/AlgoTrader/betfair-sports-api/blob/master/lib/betfair_price.js
:param float price: Approximate Betfair price (i.e. decimal... | python | def nearest_price(price, cutoffs=CUTOFFS):
"""Returns the nearest Betfair odds value to price.
Adapted from Anton Zemlyanov's AlgoTrader project (MIT licensed).
https://github.com/AlgoTrader/betfair-sports-api/blob/master/lib/betfair_price.js
:param float price: Approximate Betfair price (i.e. decimal... | Returns the nearest Betfair odds value to price.
Adapted from Anton Zemlyanov's AlgoTrader project (MIT licensed).
https://github.com/AlgoTrader/betfair-sports-api/blob/master/lib/betfair_price.js
:param float price: Approximate Betfair price (i.e. decimal odds value)
:param tuple cutoffs: Optional tu... | https://github.com/jmcarp/betfair.py/blob/116df2fdc512575d1b4c4f1749d4a5bf98e519ff/betfair/price.py#L49-L70 |
jmcarp/betfair.py | betfair/price.py | ticks_difference | def ticks_difference(price_1, price_2):
"""Returns the absolute difference in terms of "ticks" (i.e. individual
price increments) between two Betfair prices.
:param float price_1: An exact, valid Betfair price
:param float price_2: An exact, valid Betfair price
:returns: The absolute value of the d... | python | def ticks_difference(price_1, price_2):
"""Returns the absolute difference in terms of "ticks" (i.e. individual
price increments) between two Betfair prices.
:param float price_1: An exact, valid Betfair price
:param float price_2: An exact, valid Betfair price
:returns: The absolute value of the d... | Returns the absolute difference in terms of "ticks" (i.e. individual
price increments) between two Betfair prices.
:param float price_1: An exact, valid Betfair price
:param float price_2: An exact, valid Betfair price
:returns: The absolute value of the difference between the prices in "ticks"
:rt... | https://github.com/jmcarp/betfair.py/blob/116df2fdc512575d1b4c4f1749d4a5bf98e519ff/betfair/price.py#L73-L84 |
jmcarp/betfair.py | betfair/price.py | price_ticks_away | def price_ticks_away(price, n_ticks):
"""Returns an exact, valid Betfair price that is n_ticks "ticks" away from
the given price. n_ticks may positive, negative or zero (in which case the
same price is returned) but if there is no price n_ticks away from the
given price then an exception will be thrown.... | python | def price_ticks_away(price, n_ticks):
"""Returns an exact, valid Betfair price that is n_ticks "ticks" away from
the given price. n_ticks may positive, negative or zero (in which case the
same price is returned) but if there is no price n_ticks away from the
given price then an exception will be thrown.... | Returns an exact, valid Betfair price that is n_ticks "ticks" away from
the given price. n_ticks may positive, negative or zero (in which case the
same price is returned) but if there is no price n_ticks away from the
given price then an exception will be thrown.
:param float price: An exact, valid Bet... | https://github.com/jmcarp/betfair.py/blob/116df2fdc512575d1b4c4f1749d4a5bf98e519ff/betfair/price.py#L87-L99 |
jmcarp/betfair.py | betfair/betfair.py | Betfair.login | def login(self, username, password):
"""Log in to Betfair. Sets `session_token` if successful.
:param str username: Username
:param str password: Password
:raises: BetfairLoginError
"""
response = self.session.post(
os.path.join(self.identity_url, 'certlogin'... | python | def login(self, username, password):
"""Log in to Betfair. Sets `session_token` if successful.
:param str username: Username
:param str password: Password
:raises: BetfairLoginError
"""
response = self.session.post(
os.path.join(self.identity_url, 'certlogin'... | Log in to Betfair. Sets `session_token` if successful.
:param str username: Username
:param str password: Password
:raises: BetfairLoginError | https://github.com/jmcarp/betfair.py/blob/116df2fdc512575d1b4c4f1749d4a5bf98e519ff/betfair/betfair.py#L93-L117 |
jmcarp/betfair.py | betfair/betfair.py | Betfair.list_market_profit_and_loss | def list_market_profit_and_loss(
self, market_ids, include_settled_bets=False,
include_bsp_bets=None, net_of_commission=None):
"""Retrieve profit and loss for a given list of markets.
:param list market_ids: List of markets to calculate profit and loss
:param bool includ... | python | def list_market_profit_and_loss(
self, market_ids, include_settled_bets=False,
include_bsp_bets=None, net_of_commission=None):
"""Retrieve profit and loss for a given list of markets.
:param list market_ids: List of markets to calculate profit and loss
:param bool includ... | Retrieve profit and loss for a given list of markets.
:param list market_ids: List of markets to calculate profit and loss
:param bool include_settled_bets: Option to include settled bets
:param bool include_bsp_bets: Option to include BSP bets
:param bool net_of_commission: Option to r... | https://github.com/jmcarp/betfair.py/blob/116df2fdc512575d1b4c4f1749d4a5bf98e519ff/betfair/betfair.py#L284-L301 |
jmcarp/betfair.py | betfair/betfair.py | Betfair.iter_list_market_book | def iter_list_market_book(self, market_ids, chunk_size, **kwargs):
"""Split call to `list_market_book` into separate requests.
:param list market_ids: List of market IDs
:param int chunk_size: Number of records per chunk
:param dict kwargs: Arguments passed to `list_market_book`
... | python | def iter_list_market_book(self, market_ids, chunk_size, **kwargs):
"""Split call to `list_market_book` into separate requests.
:param list market_ids: List of market IDs
:param int chunk_size: Number of records per chunk
:param dict kwargs: Arguments passed to `list_market_book`
... | Split call to `list_market_book` into separate requests.
:param list market_ids: List of market IDs
:param int chunk_size: Number of records per chunk
:param dict kwargs: Arguments passed to `list_market_book` | https://github.com/jmcarp/betfair.py/blob/116df2fdc512575d1b4c4f1749d4a5bf98e519ff/betfair/betfair.py#L305-L315 |
jmcarp/betfair.py | betfair/betfair.py | Betfair.iter_list_market_profit_and_loss | def iter_list_market_profit_and_loss(
self, market_ids, chunk_size, **kwargs):
"""Split call to `list_market_profit_and_loss` into separate requests.
:param list market_ids: List of market IDs
:param int chunk_size: Number of records per chunk
:param dict kwargs: Arguments p... | python | def iter_list_market_profit_and_loss(
self, market_ids, chunk_size, **kwargs):
"""Split call to `list_market_profit_and_loss` into separate requests.
:param list market_ids: List of market IDs
:param int chunk_size: Number of records per chunk
:param dict kwargs: Arguments p... | Split call to `list_market_profit_and_loss` into separate requests.
:param list market_ids: List of market IDs
:param int chunk_size: Number of records per chunk
:param dict kwargs: Arguments passed to `list_market_profit_and_loss` | https://github.com/jmcarp/betfair.py/blob/116df2fdc512575d1b4c4f1749d4a5bf98e519ff/betfair/betfair.py#L317-L328 |
jmcarp/betfair.py | betfair/betfair.py | Betfair.place_orders | def place_orders(self, market_id, instructions, customer_ref=None):
"""Place new orders into market. This operation is atomic in that all
orders will be placed or none will be placed.
:param str market_id: The market id these orders are to be placed on
:param list instructions: List of ... | python | def place_orders(self, market_id, instructions, customer_ref=None):
"""Place new orders into market. This operation is atomic in that all
orders will be placed or none will be placed.
:param str market_id: The market id these orders are to be placed on
:param list instructions: List of ... | Place new orders into market. This operation is atomic in that all
orders will be placed or none will be placed.
:param str market_id: The market id these orders are to be placed on
:param list instructions: List of `PlaceInstruction` objects
:param str customer_ref: Optional order iden... | https://github.com/jmcarp/betfair.py/blob/116df2fdc512575d1b4c4f1749d4a5bf98e519ff/betfair/betfair.py#L384-L397 |
jmcarp/betfair.py | betfair/betfair.py | Betfair.cancel_orders | def cancel_orders(self, market_id, instructions, customer_ref=None):
"""Cancel all bets OR cancel all bets on a market OR fully or
partially cancel particular orders on a market.
:param str market_id: If not supplied all bets are cancelled
:param list instructions: List of `CancelInstru... | python | def cancel_orders(self, market_id, instructions, customer_ref=None):
"""Cancel all bets OR cancel all bets on a market OR fully or
partially cancel particular orders on a market.
:param str market_id: If not supplied all bets are cancelled
:param list instructions: List of `CancelInstru... | Cancel all bets OR cancel all bets on a market OR fully or
partially cancel particular orders on a market.
:param str market_id: If not supplied all bets are cancelled
:param list instructions: List of `CancelInstruction` objects
:param str customer_ref: Optional order identifier string | https://github.com/jmcarp/betfair.py/blob/116df2fdc512575d1b4c4f1749d4a5bf98e519ff/betfair/betfair.py#L400-L413 |
jmcarp/betfair.py | betfair/betfair.py | Betfair.replace_orders | def replace_orders(self, market_id, instructions, customer_ref=None):
"""This operation is logically a bulk cancel followed by a bulk place.
The cancel is completed first then the new orders are placed.
:param str market_id: The market id these orders are to be placed on
:param list ins... | python | def replace_orders(self, market_id, instructions, customer_ref=None):
"""This operation is logically a bulk cancel followed by a bulk place.
The cancel is completed first then the new orders are placed.
:param str market_id: The market id these orders are to be placed on
:param list ins... | This operation is logically a bulk cancel followed by a bulk place.
The cancel is completed first then the new orders are placed.
:param str market_id: The market id these orders are to be placed on
:param list instructions: List of `ReplaceInstruction` objects
:param str customer_ref: ... | https://github.com/jmcarp/betfair.py/blob/116df2fdc512575d1b4c4f1749d4a5bf98e519ff/betfair/betfair.py#L416-L429 |
jmcarp/betfair.py | betfair/betfair.py | Betfair.update_orders | def update_orders(self, market_id, instructions, customer_ref=None):
"""Update non-exposure changing fields.
:param str market_id: The market id these orders are to be placed on
:param list instructions: List of `UpdateInstruction` objects
:param str customer_ref: Optional order identif... | python | def update_orders(self, market_id, instructions, customer_ref=None):
"""Update non-exposure changing fields.
:param str market_id: The market id these orders are to be placed on
:param list instructions: List of `UpdateInstruction` objects
:param str customer_ref: Optional order identif... | Update non-exposure changing fields.
:param str market_id: The market id these orders are to be placed on
:param list instructions: List of `UpdateInstruction` objects
:param str customer_ref: Optional order identifier string | https://github.com/jmcarp/betfair.py/blob/116df2fdc512575d1b4c4f1749d4a5bf98e519ff/betfair/betfair.py#L432-L444 |
jmcarp/betfair.py | betfair/betfair.py | Betfair.get_account_funds | def get_account_funds(self, wallet=None):
"""Get available to bet amount.
:param Wallet wallet: Name of the wallet in question
"""
return self.make_api_request(
'Account',
'getAccountFunds',
utils.get_kwargs(locals()),
model=models.Account... | python | def get_account_funds(self, wallet=None):
"""Get available to bet amount.
:param Wallet wallet: Name of the wallet in question
"""
return self.make_api_request(
'Account',
'getAccountFunds',
utils.get_kwargs(locals()),
model=models.Account... | Get available to bet amount.
:param Wallet wallet: Name of the wallet in question | https://github.com/jmcarp/betfair.py/blob/116df2fdc512575d1b4c4f1749d4a5bf98e519ff/betfair/betfair.py#L447-L457 |
jmcarp/betfair.py | betfair/betfair.py | Betfair.get_account_statement | def get_account_statement(
self, locale=None, from_record=None, record_count=None,
item_date_range=None, include_item=None, wallet=None):
"""Get account statement.
:param str locale: The language to be used where applicable
:param int from_record: Specifies the first rec... | python | def get_account_statement(
self, locale=None, from_record=None, record_count=None,
item_date_range=None, include_item=None, wallet=None):
"""Get account statement.
:param str locale: The language to be used where applicable
:param int from_record: Specifies the first rec... | Get account statement.
:param str locale: The language to be used where applicable
:param int from_record: Specifies the first record that will be returned
:param int record_count: Specifies the maximum number of records to be returned
:param TimeRange item_date_range: Return items with... | https://github.com/jmcarp/betfair.py/blob/116df2fdc512575d1b4c4f1749d4a5bf98e519ff/betfair/betfair.py#L460-L477 |
jmcarp/betfair.py | betfair/betfair.py | Betfair.get_account_details | def get_account_details(self):
"""Returns the details relating your account, including your discount
rate and Betfair point balance.
"""
return self.make_api_request(
'Account',
'getAccountDetails',
utils.get_kwargs(locals()),
model=models.... | python | def get_account_details(self):
"""Returns the details relating your account, including your discount
rate and Betfair point balance.
"""
return self.make_api_request(
'Account',
'getAccountDetails',
utils.get_kwargs(locals()),
model=models.... | Returns the details relating your account, including your discount
rate and Betfair point balance. | https://github.com/jmcarp/betfair.py/blob/116df2fdc512575d1b4c4f1749d4a5bf98e519ff/betfair/betfair.py#L480-L489 |
jmcarp/betfair.py | betfair/betfair.py | Betfair.list_currency_rates | def list_currency_rates(self, from_currency=None):
"""Returns a list of currency rates based on given currency
:param str from_currency: The currency from which the rates are computed
"""
return self.make_api_request(
'Account',
'listCurrencyRates',
u... | python | def list_currency_rates(self, from_currency=None):
"""Returns a list of currency rates based on given currency
:param str from_currency: The currency from which the rates are computed
"""
return self.make_api_request(
'Account',
'listCurrencyRates',
u... | Returns a list of currency rates based on given currency
:param str from_currency: The currency from which the rates are computed | https://github.com/jmcarp/betfair.py/blob/116df2fdc512575d1b4c4f1749d4a5bf98e519ff/betfair/betfair.py#L492-L502 |
jmcarp/betfair.py | betfair/betfair.py | Betfair.transfer_funds | def transfer_funds(self, from_, to, amount):
"""Transfer funds between the UK Exchange and Australian Exchange wallets.
:param Wallet from_: Source wallet
:param Wallet to: Destination wallet
:param float amount: Amount to transfer
"""
return self.make_api_request(
... | python | def transfer_funds(self, from_, to, amount):
"""Transfer funds between the UK Exchange and Australian Exchange wallets.
:param Wallet from_: Source wallet
:param Wallet to: Destination wallet
:param float amount: Amount to transfer
"""
return self.make_api_request(
... | Transfer funds between the UK Exchange and Australian Exchange wallets.
:param Wallet from_: Source wallet
:param Wallet to: Destination wallet
:param float amount: Amount to transfer | https://github.com/jmcarp/betfair.py/blob/116df2fdc512575d1b4c4f1749d4a5bf98e519ff/betfair/betfair.py#L505-L517 |
pinax/pinax-comments | pinax/comments/templatetags/pinax_comments_tags.py | comment_count | def comment_count(object):
"""
Usage:
{% comment_count obj %}
or
{% comment_count obj as var %}
"""
return Comment.objects.filter(
object_id=object.pk,
content_type=ContentType.objects.get_for_model(object)
).count() | python | def comment_count(object):
"""
Usage:
{% comment_count obj %}
or
{% comment_count obj as var %}
"""
return Comment.objects.filter(
object_id=object.pk,
content_type=ContentType.objects.get_for_model(object)
).count() | Usage:
{% comment_count obj %}
or
{% comment_count obj as var %} | https://github.com/pinax/pinax-comments/blob/3c239b929075d3843f6ed2d07c94b022e6c5b5ff/pinax/comments/templatetags/pinax_comments_tags.py#L26-L36 |
pinax/pinax-comments | pinax/comments/templatetags/pinax_comments_tags.py | comments | def comments(object):
"""
Usage:
{% comments obj as var %}
"""
return Comment.objects.filter(
object_id=object.pk,
content_type=ContentType.objects.get_for_model(object)
) | python | def comments(object):
"""
Usage:
{% comments obj as var %}
"""
return Comment.objects.filter(
object_id=object.pk,
content_type=ContentType.objects.get_for_model(object)
) | Usage:
{% comments obj as var %} | https://github.com/pinax/pinax-comments/blob/3c239b929075d3843f6ed2d07c94b022e6c5b5ff/pinax/comments/templatetags/pinax_comments_tags.py#L40-L48 |
pinax/pinax-comments | pinax/comments/templatetags/pinax_comments_tags.py | comment_form | def comment_form(context, object):
"""
Usage:
{% comment_form obj as comment_form %}
Will read the `user` var out of the contex to know if the form should be
form an auth'd user or not.
"""
user = context.get("user")
form_class = context.get("form", CommentForm)
form = form_class... | python | def comment_form(context, object):
"""
Usage:
{% comment_form obj as comment_form %}
Will read the `user` var out of the contex to know if the form should be
form an auth'd user or not.
"""
user = context.get("user")
form_class = context.get("form", CommentForm)
form = form_class... | Usage:
{% comment_form obj as comment_form %}
Will read the `user` var out of the contex to know if the form should be
form an auth'd user or not. | https://github.com/pinax/pinax-comments/blob/3c239b929075d3843f6ed2d07c94b022e6c5b5ff/pinax/comments/templatetags/pinax_comments_tags.py#L52-L62 |
pinax/pinax-comments | pinax/comments/templatetags/pinax_comments_tags.py | comment_target | def comment_target(object):
"""
Usage:
{% comment_target obj [as varname] %}
"""
return reverse("pinax_comments:post_comment", kwargs={
"content_type_id": ContentType.objects.get_for_model(object).pk,
"object_id": object.pk
}) | python | def comment_target(object):
"""
Usage:
{% comment_target obj [as varname] %}
"""
return reverse("pinax_comments:post_comment", kwargs={
"content_type_id": ContentType.objects.get_for_model(object).pk,
"object_id": object.pk
}) | Usage:
{% comment_target obj [as varname] %} | https://github.com/pinax/pinax-comments/blob/3c239b929075d3843f6ed2d07c94b022e6c5b5ff/pinax/comments/templatetags/pinax_comments_tags.py#L66-L74 |
edmondburnett/twitter-text-python | ttp/ttp.py | Parser.parse | def parse(self, text, html=True):
'''Parse the text and return a ParseResult instance.'''
self._urls = []
self._users = []
self._lists = []
self._tags = []
reply = REPLY_REGEX.match(text)
reply = reply.groups(0)[0] if reply is not None else None
parsed_h... | python | def parse(self, text, html=True):
'''Parse the text and return a ParseResult instance.'''
self._urls = []
self._users = []
self._lists = []
self._tags = []
reply = REPLY_REGEX.match(text)
reply = reply.groups(0)[0] if reply is not None else None
parsed_h... | Parse the text and return a ParseResult instance. | https://github.com/edmondburnett/twitter-text-python/blob/2a23ced35bfd34c4bc4b7148afd85771e9eb8669/ttp/ttp.py#L125-L137 |
edmondburnett/twitter-text-python | ttp/ttp.py | Parser._text | def _text(self, text):
'''Parse a Tweet without generating HTML.'''
URL_REGEX.sub(self._parse_urls, text)
USERNAME_REGEX.sub(self._parse_users, text)
LIST_REGEX.sub(self._parse_lists, text)
HASHTAG_REGEX.sub(self._parse_tags, text)
return None | python | def _text(self, text):
'''Parse a Tweet without generating HTML.'''
URL_REGEX.sub(self._parse_urls, text)
USERNAME_REGEX.sub(self._parse_users, text)
LIST_REGEX.sub(self._parse_lists, text)
HASHTAG_REGEX.sub(self._parse_tags, text)
return None | Parse a Tweet without generating HTML. | https://github.com/edmondburnett/twitter-text-python/blob/2a23ced35bfd34c4bc4b7148afd85771e9eb8669/ttp/ttp.py#L139-L145 |
edmondburnett/twitter-text-python | ttp/ttp.py | Parser._html | def _html(self, text):
'''Parse a Tweet and generate HTML.'''
html = URL_REGEX.sub(self._parse_urls, text)
html = USERNAME_REGEX.sub(self._parse_users, html)
html = LIST_REGEX.sub(self._parse_lists, html)
return HASHTAG_REGEX.sub(self._parse_tags, html) | python | def _html(self, text):
'''Parse a Tweet and generate HTML.'''
html = URL_REGEX.sub(self._parse_urls, text)
html = USERNAME_REGEX.sub(self._parse_users, html)
html = LIST_REGEX.sub(self._parse_lists, html)
return HASHTAG_REGEX.sub(self._parse_tags, html) | Parse a Tweet and generate HTML. | https://github.com/edmondburnett/twitter-text-python/blob/2a23ced35bfd34c4bc4b7148afd85771e9eb8669/ttp/ttp.py#L147-L152 |
edmondburnett/twitter-text-python | ttp/ttp.py | Parser._parse_urls | def _parse_urls(self, match):
'''Parse URLs.'''
mat = match.group(0)
# Fix a bug in the regex concerning www...com and www.-foo.com domains
# TODO fix this in the regex instead of working around it here
domain = match.group(5)
if domain[0] in '.-':
return ma... | python | def _parse_urls(self, match):
'''Parse URLs.'''
mat = match.group(0)
# Fix a bug in the regex concerning www...com and www.-foo.com domains
# TODO fix this in the regex instead of working around it here
domain = match.group(5)
if domain[0] in '.-':
return ma... | Parse URLs. | https://github.com/edmondburnett/twitter-text-python/blob/2a23ced35bfd34c4bc4b7148afd85771e9eb8669/ttp/ttp.py#L155-L195 |
edmondburnett/twitter-text-python | ttp/ttp.py | Parser._parse_users | def _parse_users(self, match):
'''Parse usernames.'''
# Don't parse lists here
if match.group(2) is not None:
return match.group(0)
mat = match.group(0)
if self._include_spans:
self._users.append((mat[1:], match.span(0)))
else:
self._... | python | def _parse_users(self, match):
'''Parse usernames.'''
# Don't parse lists here
if match.group(2) is not None:
return match.group(0)
mat = match.group(0)
if self._include_spans:
self._users.append((mat[1:], match.span(0)))
else:
self._... | Parse usernames. | https://github.com/edmondburnett/twitter-text-python/blob/2a23ced35bfd34c4bc4b7148afd85771e9eb8669/ttp/ttp.py#L197-L211 |
edmondburnett/twitter-text-python | ttp/ttp.py | Parser._parse_lists | def _parse_lists(self, match):
'''Parse lists.'''
# Don't parse usernames here
if match.group(4) is None:
return match.group(0)
pre, at_char, user, list_name = match.groups()
list_name = list_name[1:]
if self._include_spans:
self._lists.append((u... | python | def _parse_lists(self, match):
'''Parse lists.'''
# Don't parse usernames here
if match.group(4) is None:
return match.group(0)
pre, at_char, user, list_name = match.groups()
list_name = list_name[1:]
if self._include_spans:
self._lists.append((u... | Parse lists. | https://github.com/edmondburnett/twitter-text-python/blob/2a23ced35bfd34c4bc4b7148afd85771e9eb8669/ttp/ttp.py#L213-L228 |
edmondburnett/twitter-text-python | ttp/ttp.py | Parser._parse_tags | def _parse_tags(self, match):
'''Parse hashtags.'''
mat = match.group(0)
# Fix problems with the regex capturing stuff infront of the #
tag = None
for i in '#\uff03':
pos = mat.rfind(i)
if pos != -1:
tag = i
break
... | python | def _parse_tags(self, match):
'''Parse hashtags.'''
mat = match.group(0)
# Fix problems with the regex capturing stuff infront of the #
tag = None
for i in '#\uff03':
pos = mat.rfind(i)
if pos != -1:
tag = i
break
... | Parse hashtags. | https://github.com/edmondburnett/twitter-text-python/blob/2a23ced35bfd34c4bc4b7148afd85771e9eb8669/ttp/ttp.py#L230-L253 |
edmondburnett/twitter-text-python | ttp/ttp.py | Parser._shorten_url | def _shorten_url(self, text):
'''Shorten a URL and make sure to not cut of html entities.'''
if len(text) > self._max_url_length and self._max_url_length != -1:
text = text[0:self._max_url_length - 3]
amp = text.rfind('&')
close = text.rfind(';')
if amp !... | python | def _shorten_url(self, text):
'''Shorten a URL and make sure to not cut of html entities.'''
if len(text) > self._max_url_length and self._max_url_length != -1:
text = text[0:self._max_url_length - 3]
amp = text.rfind('&')
close = text.rfind(';')
if amp !... | Shorten a URL and make sure to not cut of html entities. | https://github.com/edmondburnett/twitter-text-python/blob/2a23ced35bfd34c4bc4b7148afd85771e9eb8669/ttp/ttp.py#L255-L268 |
edmondburnett/twitter-text-python | ttp/ttp.py | Parser.format_list | def format_list(self, at_char, user, list_name):
'''Return formatted HTML for a list.'''
return '<a href="https://twitter.com/%s/lists/%s">%s%s/%s</a>' \
% (user, list_name, at_char, user, list_name) | python | def format_list(self, at_char, user, list_name):
'''Return formatted HTML for a list.'''
return '<a href="https://twitter.com/%s/lists/%s">%s%s/%s</a>' \
% (user, list_name, at_char, user, list_name) | Return formatted HTML for a list. | https://github.com/edmondburnett/twitter-text-python/blob/2a23ced35bfd34c4bc4b7148afd85771e9eb8669/ttp/ttp.py#L281-L284 |
edmondburnett/twitter-text-python | ttp/utils.py | follow_shortlinks | def follow_shortlinks(shortlinks):
"""Follow redirects in list of shortlinks, return dict of resulting URLs"""
links_followed = {}
for shortlink in shortlinks:
url = shortlink
request_result = requests.get(url)
redirect_history = request_result.history
# history might look li... | python | def follow_shortlinks(shortlinks):
"""Follow redirects in list of shortlinks, return dict of resulting URLs"""
links_followed = {}
for shortlink in shortlinks:
url = shortlink
request_result = requests.get(url)
redirect_history = request_result.history
# history might look li... | Follow redirects in list of shortlinks, return dict of resulting URLs | https://github.com/edmondburnett/twitter-text-python/blob/2a23ced35bfd34c4bc4b7148afd85771e9eb8669/ttp/utils.py#L8-L24 |
cloudendpoints/endpoints-python | endpoints/resource_container.py | _GetFieldAttributes | def _GetFieldAttributes(field):
"""Decomposes field into the needed arguments to pass to the constructor.
This can be used to create copies of the field or to compare if two fields
are "equal" (since __eq__ is not implemented on messages.Field).
Args:
field: A ProtoRPC message field (potentially to be cop... | python | def _GetFieldAttributes(field):
"""Decomposes field into the needed arguments to pass to the constructor.
This can be used to create copies of the field or to compare if two fields
are "equal" (since __eq__ is not implemented on messages.Field).
Args:
field: A ProtoRPC message field (potentially to be cop... | Decomposes field into the needed arguments to pass to the constructor.
This can be used to create copies of the field or to compare if two fields
are "equal" (since __eq__ is not implemented on messages.Field).
Args:
field: A ProtoRPC message field (potentially to be copied).
Raises:
TypeError: If th... | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/resource_container.py#L142-L178 |
cloudendpoints/endpoints-python | endpoints/resource_container.py | _CompareFields | def _CompareFields(field, other_field):
"""Checks if two ProtoRPC fields are "equal".
Compares the arguments, rather than the id of the elements (which is
the default __eq__ behavior) as well as the class of the fields.
Args:
field: A ProtoRPC message field to be compared.
other_field: A ProtoRPC mess... | python | def _CompareFields(field, other_field):
"""Checks if two ProtoRPC fields are "equal".
Compares the arguments, rather than the id of the elements (which is
the default __eq__ behavior) as well as the class of the fields.
Args:
field: A ProtoRPC message field to be compared.
other_field: A ProtoRPC mess... | Checks if two ProtoRPC fields are "equal".
Compares the arguments, rather than the id of the elements (which is
the default __eq__ behavior) as well as the class of the fields.
Args:
field: A ProtoRPC message field to be compared.
other_field: A ProtoRPC message field to be compared.
Returns:
Boo... | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/resource_container.py#L181-L198 |
cloudendpoints/endpoints-python | endpoints/resource_container.py | _CopyField | def _CopyField(field, number=None):
"""Copies a (potentially) owned ProtoRPC field instance into a new copy.
Args:
field: A ProtoRPC message field to be copied.
number: An integer for the field to override the number of the field.
Defaults to None.
Raises:
TypeError: If the field is not an i... | python | def _CopyField(field, number=None):
"""Copies a (potentially) owned ProtoRPC field instance into a new copy.
Args:
field: A ProtoRPC message field to be copied.
number: An integer for the field to override the number of the field.
Defaults to None.
Raises:
TypeError: If the field is not an i... | Copies a (potentially) owned ProtoRPC field instance into a new copy.
Args:
field: A ProtoRPC message field to be copied.
number: An integer for the field to override the number of the field.
Defaults to None.
Raises:
TypeError: If the field is not an instance of messages.Field.
Returns:
... | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/resource_container.py#L201-L218 |
cloudendpoints/endpoints-python | endpoints/resource_container.py | ResourceContainer.combined_message_class | def combined_message_class(self):
"""A ProtoRPC message class with both request and parameters fields.
Caches the result in a local private variable. Uses _CopyField to create
copies of the fields from the existing request and parameters classes since
those fields are "owned" by the message classes.
... | python | def combined_message_class(self):
"""A ProtoRPC message class with both request and parameters fields.
Caches the result in a local private variable. Uses _CopyField to create
copies of the fields from the existing request and parameters classes since
those fields are "owned" by the message classes.
... | A ProtoRPC message class with both request and parameters fields.
Caches the result in a local private variable. Uses _CopyField to create
copies of the fields from the existing request and parameters classes since
those fields are "owned" by the message classes.
Raises:
TypeError: If a field na... | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/resource_container.py#L58-L100 |
cloudendpoints/endpoints-python | endpoints/resource_container.py | ResourceContainer.add_to_cache | def add_to_cache(cls, remote_info, container): # pylint: disable=g-bad-name
"""Adds a ResourceContainer to a cache tying it to a protorpc method.
Args:
remote_info: Instance of protorpc.remote._RemoteMethodInfo corresponding
to a method.
container: An instance of ResourceContainer.
... | python | def add_to_cache(cls, remote_info, container): # pylint: disable=g-bad-name
"""Adds a ResourceContainer to a cache tying it to a protorpc method.
Args:
remote_info: Instance of protorpc.remote._RemoteMethodInfo corresponding
to a method.
container: An instance of ResourceContainer.
... | Adds a ResourceContainer to a cache tying it to a protorpc method.
Args:
remote_info: Instance of protorpc.remote._RemoteMethodInfo corresponding
to a method.
container: An instance of ResourceContainer.
Raises:
TypeError: if the container is not an instance of cls.
KeyError:... | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/resource_container.py#L103-L122 |
cloudendpoints/endpoints-python | endpoints/resource_container.py | ResourceContainer.get_request_message | def get_request_message(cls, remote_info): # pylint: disable=g-bad-name
"""Gets request message or container from remote info.
Args:
remote_info: Instance of protorpc.remote._RemoteMethodInfo corresponding
to a method.
Returns:
Either an instance of the request type from the remote ... | python | def get_request_message(cls, remote_info): # pylint: disable=g-bad-name
"""Gets request message or container from remote info.
Args:
remote_info: Instance of protorpc.remote._RemoteMethodInfo corresponding
to a method.
Returns:
Either an instance of the request type from the remote ... | Gets request message or container from remote info.
Args:
remote_info: Instance of protorpc.remote._RemoteMethodInfo corresponding
to a method.
Returns:
Either an instance of the request type from the remote or the
ResourceContainer that was cached with the remote method. | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/resource_container.py#L125-L139 |
cloudendpoints/endpoints-python | endpoints/users_id_token.py | get_current_user | def get_current_user():
"""Get user information from the id_token or oauth token in the request.
This should only be called from within an Endpoints request handler,
decorated with an @endpoints.method decorator. The decorator should include
the https://www.googleapis.com/auth/userinfo.email scope.
If `end... | python | def get_current_user():
"""Get user information from the id_token or oauth token in the request.
This should only be called from within an Endpoints request handler,
decorated with an @endpoints.method decorator. The decorator should include
the https://www.googleapis.com/auth/userinfo.email scope.
If `end... | Get user information from the id_token or oauth token in the request.
This should only be called from within an Endpoints request handler,
decorated with an @endpoints.method decorator. The decorator should include
the https://www.googleapis.com/auth/userinfo.email scope.
If `endpoints_management.control.wsg... | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/users_id_token.py#L96-L147 |
cloudendpoints/endpoints-python | endpoints/users_id_token.py | _is_auth_info_available | def _is_auth_info_available():
"""Check if user auth info has been set in environment variables."""
return (_ENDPOINTS_USER_INFO in os.environ or
(_ENV_AUTH_EMAIL in os.environ and _ENV_AUTH_DOMAIN in os.environ) or
_ENV_USE_OAUTH_SCOPE in os.environ) | python | def _is_auth_info_available():
"""Check if user auth info has been set in environment variables."""
return (_ENDPOINTS_USER_INFO in os.environ or
(_ENV_AUTH_EMAIL in os.environ and _ENV_AUTH_DOMAIN in os.environ) or
_ENV_USE_OAUTH_SCOPE in os.environ) | Check if user auth info has been set in environment variables. | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/users_id_token.py#L151-L155 |
cloudendpoints/endpoints-python | endpoints/users_id_token.py | _maybe_set_current_user_vars | def _maybe_set_current_user_vars(method, api_info=None, request=None):
"""Get user information from the id_token or oauth token in the request.
Used internally by Endpoints to set up environment variables for user
authentication.
Args:
method: The class method that's handling this request. This method
... | python | def _maybe_set_current_user_vars(method, api_info=None, request=None):
"""Get user information from the id_token or oauth token in the request.
Used internally by Endpoints to set up environment variables for user
authentication.
Args:
method: The class method that's handling this request. This method
... | Get user information from the id_token or oauth token in the request.
Used internally by Endpoints to set up environment variables for user
authentication.
Args:
method: The class method that's handling this request. This method
should be annotated with @endpoints.method.
api_info: An api_config.... | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/users_id_token.py#L158-L245 |
cloudendpoints/endpoints-python | endpoints/users_id_token.py | _get_token | def _get_token(
request=None, allowed_auth_schemes=('OAuth', 'Bearer'),
allowed_query_keys=('bearer_token', 'access_token')):
"""Get the auth token for this request.
Auth token may be specified in either the Authorization header or
as a query param (either access_token or bearer_token). We'll check in
... | python | def _get_token(
request=None, allowed_auth_schemes=('OAuth', 'Bearer'),
allowed_query_keys=('bearer_token', 'access_token')):
"""Get the auth token for this request.
Auth token may be specified in either the Authorization header or
as a query param (either access_token or bearer_token). We'll check in
... | Get the auth token for this request.
Auth token may be specified in either the Authorization header or
as a query param (either access_token or bearer_token). We'll check in
this order:
1. Authorization header.
2. bearer_token query param.
3. access_token query param.
Args:
request: The curre... | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/users_id_token.py#L248-L285 |
cloudendpoints/endpoints-python | endpoints/users_id_token.py | _get_id_token_user | def _get_id_token_user(token, issuers, audiences, allowed_client_ids, time_now, cache):
"""Get a User for the given id token, if the token is valid.
Args:
token: The id_token to check.
issuers: dict of Issuers
audiences: List of audiences that are acceptable.
allowed_client_ids: List of client IDs ... | python | def _get_id_token_user(token, issuers, audiences, allowed_client_ids, time_now, cache):
"""Get a User for the given id token, if the token is valid.
Args:
token: The id_token to check.
issuers: dict of Issuers
audiences: List of audiences that are acceptable.
allowed_client_ids: List of client IDs ... | Get a User for the given id token, if the token is valid.
Args:
token: The id_token to check.
issuers: dict of Issuers
audiences: List of audiences that are acceptable.
allowed_client_ids: List of client IDs that are acceptable.
time_now: The current time as a long (eg. long(time.time())).
ca... | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/users_id_token.py#L288-L330 |
cloudendpoints/endpoints-python | endpoints/users_id_token.py | _process_scopes | def _process_scopes(scopes):
"""Parse a scopes list into a set of all scopes and a set of sufficient scope sets.
scopes: A list of strings, each of which is a space-separated list of scopes.
Examples: ['scope1']
['scope1', 'scope2']
['scope1', 'scope2 scope3']
Retu... | python | def _process_scopes(scopes):
"""Parse a scopes list into a set of all scopes and a set of sufficient scope sets.
scopes: A list of strings, each of which is a space-separated list of scopes.
Examples: ['scope1']
['scope1', 'scope2']
['scope1', 'scope2 scope3']
Retu... | Parse a scopes list into a set of all scopes and a set of sufficient scope sets.
scopes: A list of strings, each of which is a space-separated list of scopes.
Examples: ['scope1']
['scope1', 'scope2']
['scope1', 'scope2 scope3']
Returns:
all_scopes: a set of s... | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/users_id_token.py#L342-L362 |
cloudendpoints/endpoints-python | endpoints/users_id_token.py | _are_scopes_sufficient | def _are_scopes_sufficient(authorized_scopes, sufficient_scopes):
"""Check if a list of authorized scopes satisfies any set of sufficient scopes.
Args:
authorized_scopes: a list of strings, return value from oauth.get_authorized_scopes
sufficient_scopes: a set of sets of strings, return value from... | python | def _are_scopes_sufficient(authorized_scopes, sufficient_scopes):
"""Check if a list of authorized scopes satisfies any set of sufficient scopes.
Args:
authorized_scopes: a list of strings, return value from oauth.get_authorized_scopes
sufficient_scopes: a set of sets of strings, return value from... | Check if a list of authorized scopes satisfies any set of sufficient scopes.
Args:
authorized_scopes: a list of strings, return value from oauth.get_authorized_scopes
sufficient_scopes: a set of sets of strings, return value from _process_scopes | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/users_id_token.py#L365-L375 |
cloudendpoints/endpoints-python | endpoints/users_id_token.py | _set_bearer_user_vars | def _set_bearer_user_vars(allowed_client_ids, scopes):
"""Validate the oauth bearer token and set endpoints auth user variables.
If the bearer token is valid, this sets ENDPOINTS_USE_OAUTH_SCOPE. This
provides enough information that our endpoints.get_current_user() function
can get the user.
Args:
all... | python | def _set_bearer_user_vars(allowed_client_ids, scopes):
"""Validate the oauth bearer token and set endpoints auth user variables.
If the bearer token is valid, this sets ENDPOINTS_USE_OAUTH_SCOPE. This
provides enough information that our endpoints.get_current_user() function
can get the user.
Args:
all... | Validate the oauth bearer token and set endpoints auth user variables.
If the bearer token is valid, this sets ENDPOINTS_USE_OAUTH_SCOPE. This
provides enough information that our endpoints.get_current_user() function
can get the user.
Args:
allowed_client_ids: List of client IDs that are acceptable.
... | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/users_id_token.py#L379-L410 |
cloudendpoints/endpoints-python | endpoints/users_id_token.py | _set_bearer_user_vars_local | def _set_bearer_user_vars_local(token, allowed_client_ids, scopes):
"""Validate the oauth bearer token on the dev server.
Since the functions in the oauth module return only example results in local
development, this hits the tokeninfo endpoint and attempts to validate the
token. If it's valid, we'll set _ENV... | python | def _set_bearer_user_vars_local(token, allowed_client_ids, scopes):
"""Validate the oauth bearer token on the dev server.
Since the functions in the oauth module return only example results in local
development, this hits the tokeninfo endpoint and attempts to validate the
token. If it's valid, we'll set _ENV... | Validate the oauth bearer token on the dev server.
Since the functions in the oauth module return only example results in local
development, this hits the tokeninfo endpoint and attempts to validate the
token. If it's valid, we'll set _ENV_AUTH_EMAIL and _ENV_AUTH_DOMAIN so we
can get the user from the token.... | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/users_id_token.py#L413-L463 |
cloudendpoints/endpoints-python | endpoints/users_id_token.py | _verify_parsed_token | def _verify_parsed_token(parsed_token, issuers, audiences, allowed_client_ids, is_legacy_google_auth=True):
"""Verify a parsed user ID token.
Args:
parsed_token: The parsed token information.
issuers: A list of allowed issuers
audiences: The allowed audiences.
allowed_client_ids: The allowed client... | python | def _verify_parsed_token(parsed_token, issuers, audiences, allowed_client_ids, is_legacy_google_auth=True):
"""Verify a parsed user ID token.
Args:
parsed_token: The parsed token information.
issuers: A list of allowed issuers
audiences: The allowed audiences.
allowed_client_ids: The allowed client... | Verify a parsed user ID token.
Args:
parsed_token: The parsed token information.
issuers: A list of allowed issuers
audiences: The allowed audiences.
allowed_client_ids: The allowed client IDs.
Returns:
True if the token is verified, False otherwise. | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/users_id_token.py#L470-L514 |
cloudendpoints/endpoints-python | endpoints/users_id_token.py | _get_cert_expiration_time | def _get_cert_expiration_time(headers):
"""Get the expiration time for a cert, given the response headers.
Get expiration time from the headers in the result. If we can't get
a time from the headers, this returns 0, indicating that the cert
shouldn't be cached.
Args:
headers: A dict containing the resp... | python | def _get_cert_expiration_time(headers):
"""Get the expiration time for a cert, given the response headers.
Get expiration time from the headers in the result. If we can't get
a time from the headers, this returns 0, indicating that the cert
shouldn't be cached.
Args:
headers: A dict containing the resp... | Get the expiration time for a cert, given the response headers.
Get expiration time from the headers in the result. If we can't get
a time from the headers, this returns 0, indicating that the cert
shouldn't be cached.
Args:
headers: A dict containing the response headers from the request to get
ce... | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/users_id_token.py#L524-L561 |
cloudendpoints/endpoints-python | endpoints/users_id_token.py | _get_cached_certs | def _get_cached_certs(cert_uri, cache):
"""Get certs from cache if present; otherwise, gets from URI and caches them.
Args:
cert_uri: URI from which to retrieve certs if cache is stale or empty.
cache: Cache of pre-fetched certs.
Returns:
The retrieved certs.
"""
certs = cache.get(cert_uri, name... | python | def _get_cached_certs(cert_uri, cache):
"""Get certs from cache if present; otherwise, gets from URI and caches them.
Args:
cert_uri: URI from which to retrieve certs if cache is stale or empty.
cache: Cache of pre-fetched certs.
Returns:
The retrieved certs.
"""
certs = cache.get(cert_uri, name... | Get certs from cache if present; otherwise, gets from URI and caches them.
Args:
cert_uri: URI from which to retrieve certs if cache is stale or empty.
cache: Cache of pre-fetched certs.
Returns:
The retrieved certs. | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/users_id_token.py#L564-L593 |
cloudendpoints/endpoints-python | endpoints/users_id_token.py | _verify_signed_jwt_with_certs | def _verify_signed_jwt_with_certs(
jwt, time_now, cache,
cert_uri=_DEFAULT_CERT_URI):
"""Verify a JWT against public certs.
See http://self-issued.info/docs/draft-jones-json-web-token.html.
The PyCrypto library included with Google App Engine is severely limited and
so you have to use it very carefull... | python | def _verify_signed_jwt_with_certs(
jwt, time_now, cache,
cert_uri=_DEFAULT_CERT_URI):
"""Verify a JWT against public certs.
See http://self-issued.info/docs/draft-jones-json-web-token.html.
The PyCrypto library included with Google App Engine is severely limited and
so you have to use it very carefull... | Verify a JWT against public certs.
See http://self-issued.info/docs/draft-jones-json-web-token.html.
The PyCrypto library included with Google App Engine is severely limited and
so you have to use it very carefully to verify JWT signatures. The first
issue is that the library can't read X.509 files, so we mak... | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/users_id_token.py#L603-L732 |
cloudendpoints/endpoints-python | endpoints/users_id_token.py | convert_jwks_uri | def convert_jwks_uri(jwks_uri):
"""
The PyCrypto library included with Google App Engine is severely limited and
can't read X.509 files, so we change the URI to a special URI that has the
public cert in modulus/exponent form in JSON.
"""
if not jwks_uri.startswith(_TEXT_CERT_PREFIX):
return jwks_uri
r... | python | def convert_jwks_uri(jwks_uri):
"""
The PyCrypto library included with Google App Engine is severely limited and
can't read X.509 files, so we change the URI to a special URI that has the
public cert in modulus/exponent form in JSON.
"""
if not jwks_uri.startswith(_TEXT_CERT_PREFIX):
return jwks_uri
r... | The PyCrypto library included with Google App Engine is severely limited and
can't read X.509 files, so we change the URI to a special URI that has the
public cert in modulus/exponent form in JSON. | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/users_id_token.py#L739-L747 |
cloudendpoints/endpoints-python | endpoints/users_id_token.py | get_verified_jwt | def get_verified_jwt(
providers, audiences,
check_authorization_header=True, check_query_arg=True,
request=None, cache=memcache):
"""
This function will extract, verify, and parse a JWT token from the
Authorization header or access_token query argument.
The JWT is assumed to contain an issuer and a... | python | def get_verified_jwt(
providers, audiences,
check_authorization_header=True, check_query_arg=True,
request=None, cache=memcache):
"""
This function will extract, verify, and parse a JWT token from the
Authorization header or access_token query argument.
The JWT is assumed to contain an issuer and a... | This function will extract, verify, and parse a JWT token from the
Authorization header or access_token query argument.
The JWT is assumed to contain an issuer and audience claim, as well
as issued-at and expiration timestamps. The signature will be
cryptographically verified, the claims and timestamps will be... | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/users_id_token.py#L750-L794 |
cloudendpoints/endpoints-python | endpoints/users_id_token.py | _listlike_guard | def _listlike_guard(obj, name, iterable_only=False, log_warning=True):
"""
We frequently require passed objects to support iteration or
containment expressions, but not be strings. (Of course, strings
support iteration and containment, but not usefully.) If the passed
object is a string, we'll wrap it in a t... | python | def _listlike_guard(obj, name, iterable_only=False, log_warning=True):
"""
We frequently require passed objects to support iteration or
containment expressions, but not be strings. (Of course, strings
support iteration and containment, but not usefully.) If the passed
object is a string, we'll wrap it in a t... | We frequently require passed objects to support iteration or
containment expressions, but not be strings. (Of course, strings
support iteration and containment, but not usefully.) If the passed
object is a string, we'll wrap it in a tuple and return it. If it's
already an iterable, we'll return it as-is. Other... | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/users_id_token.py#L824-L843 |
cloudendpoints/endpoints-python | endpoints/directory_list_generator.py | DirectoryListGenerator.__item_descriptor | def __item_descriptor(self, config):
"""Builds an item descriptor for a service configuration.
Args:
config: A dictionary containing the service configuration to describe.
Returns:
A dictionary that describes the service configuration.
"""
descriptor = {
'kind': 'discovery#dire... | python | def __item_descriptor(self, config):
"""Builds an item descriptor for a service configuration.
Args:
config: A dictionary containing the service configuration to describe.
Returns:
A dictionary that describes the service configuration.
"""
descriptor = {
'kind': 'discovery#dire... | Builds an item descriptor for a service configuration.
Args:
config: A dictionary containing the service configuration to describe.
Returns:
A dictionary that describes the service configuration. | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/directory_list_generator.py#L56-L99 |
cloudendpoints/endpoints-python | endpoints/directory_list_generator.py | DirectoryListGenerator.__directory_list_descriptor | def __directory_list_descriptor(self, configs):
"""Builds a directory list for an API.
Args:
configs: List of dicts containing the service configurations to list.
Returns:
A dictionary that can be deserialized into JSON in discovery list format.
Raises:
ApiConfigurationError: If the... | python | def __directory_list_descriptor(self, configs):
"""Builds a directory list for an API.
Args:
configs: List of dicts containing the service configurations to list.
Returns:
A dictionary that can be deserialized into JSON in discovery list format.
Raises:
ApiConfigurationError: If the... | Builds a directory list for an API.
Args:
configs: List of dicts containing the service configurations to list.
Returns:
A dictionary that can be deserialized into JSON in discovery list format.
Raises:
ApiConfigurationError: If there's something wrong with the API
configuration... | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/directory_list_generator.py#L101-L130 |
cloudendpoints/endpoints-python | endpoints/directory_list_generator.py | DirectoryListGenerator.get_directory_list_doc | def get_directory_list_doc(self, configs):
"""JSON dict description of a protorpc.remote.Service in list format.
Args:
configs: Either a single dict or a list of dicts containing the service
configurations to list.
Returns:
dict, The directory list document as a JSON dict.
"""
... | python | def get_directory_list_doc(self, configs):
"""JSON dict description of a protorpc.remote.Service in list format.
Args:
configs: Either a single dict or a list of dicts containing the service
configurations to list.
Returns:
dict, The directory list document as a JSON dict.
"""
... | JSON dict description of a protorpc.remote.Service in list format.
Args:
configs: Either a single dict or a list of dicts containing the service
configurations to list.
Returns:
dict, The directory list document as a JSON dict. | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/directory_list_generator.py#L132-L148 |
cloudendpoints/endpoints-python | endpoints/directory_list_generator.py | DirectoryListGenerator.pretty_print_config_to_json | def pretty_print_config_to_json(self, configs):
"""JSON string description of a protorpc.remote.Service in a discovery doc.
Args:
configs: Either a single dict or a list of dicts containing the service
configurations to list.
Returns:
string, The directory list document as a JSON strin... | python | def pretty_print_config_to_json(self, configs):
"""JSON string description of a protorpc.remote.Service in a discovery doc.
Args:
configs: Either a single dict or a list of dicts containing the service
configurations to list.
Returns:
string, The directory list document as a JSON strin... | JSON string description of a protorpc.remote.Service in a discovery doc.
Args:
configs: Either a single dict or a list of dicts containing the service
configurations to list.
Returns:
string, The directory list document as a JSON string. | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/directory_list_generator.py#L150-L162 |
cloudendpoints/endpoints-python | endpoints/errors.py | RequestError.__format_error | def __format_error(self, error_list_tag):
"""Format this error into a JSON response.
Args:
error_list_tag: A string specifying the name of the tag to use for the
error list.
Returns:
A dict containing the reformatted JSON error response.
"""
error = {'domain': self.domain(),
... | python | def __format_error(self, error_list_tag):
"""Format this error into a JSON response.
Args:
error_list_tag: A string specifying the name of the tag to use for the
error list.
Returns:
A dict containing the reformatted JSON error response.
"""
error = {'domain': self.domain(),
... | Format this error into a JSON response.
Args:
error_list_tag: A string specifying the name of the tag to use for the
error list.
Returns:
A dict containing the reformatted JSON error response. | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/errors.py#L100-L116 |
cloudendpoints/endpoints-python | endpoints/errors.py | RequestError.rest_error | def rest_error(self):
"""Format this error into a response to a REST request.
Returns:
A string containing the reformatted error response.
"""
error_json = self.__format_error('errors')
return json.dumps(error_json, indent=1, sort_keys=True) | python | def rest_error(self):
"""Format this error into a response to a REST request.
Returns:
A string containing the reformatted error response.
"""
error_json = self.__format_error('errors')
return json.dumps(error_json, indent=1, sort_keys=True) | Format this error into a response to a REST request.
Returns:
A string containing the reformatted error response. | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/errors.py#L118-L125 |
cloudendpoints/endpoints-python | endpoints/errors.py | BackendError._get_status_code | def _get_status_code(self, http_status):
"""Get the HTTP status code from an HTTP status string.
Args:
http_status: A string containing a HTTP status code and reason.
Returns:
An integer with the status code number from http_status.
"""
try:
return int(http_status.split(' ', 1)[0... | python | def _get_status_code(self, http_status):
"""Get the HTTP status code from an HTTP status string.
Args:
http_status: A string containing a HTTP status code and reason.
Returns:
An integer with the status code number from http_status.
"""
try:
return int(http_status.split(' ', 1)[0... | Get the HTTP status code from an HTTP status string.
Args:
http_status: A string containing a HTTP status code and reason.
Returns:
An integer with the status code number from http_status. | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/errors.py#L239-L253 |
cloudendpoints/endpoints-python | endpoints/api_config_manager.py | ApiConfigManager.process_api_config_response | def process_api_config_response(self, config_json):
"""Parses a JSON API config and registers methods for dispatch.
Side effects:
Parses method name, etc. for all methods and updates the indexing
data structures with the information.
Args:
config_json: A dict, the JSON body of the getApi... | python | def process_api_config_response(self, config_json):
"""Parses a JSON API config and registers methods for dispatch.
Side effects:
Parses method name, etc. for all methods and updates the indexing
data structures with the information.
Args:
config_json: A dict, the JSON body of the getApi... | Parses a JSON API config and registers methods for dispatch.
Side effects:
Parses method name, etc. for all methods and updates the indexing
data structures with the information.
Args:
config_json: A dict, the JSON body of the getApiConfigs response. | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config_manager.py#L53-L77 |
cloudendpoints/endpoints-python | endpoints/api_config_manager.py | ApiConfigManager._get_sorted_methods | def _get_sorted_methods(self, methods):
"""Get a copy of 'methods' sorted the way they would be on the live server.
Args:
methods: JSON configuration of an API's methods.
Returns:
The same configuration with the methods sorted based on what order
they'll be checked by the server.
"""... | python | def _get_sorted_methods(self, methods):
"""Get a copy of 'methods' sorted the way they would be on the live server.
Args:
methods: JSON configuration of an API's methods.
Returns:
The same configuration with the methods sorted based on what order
they'll be checked by the server.
"""... | Get a copy of 'methods' sorted the way they would be on the live server.
Args:
methods: JSON configuration of an API's methods.
Returns:
The same configuration with the methods sorted based on what order
they'll be checked by the server. | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config_manager.py#L79-L150 |
cloudendpoints/endpoints-python | endpoints/api_config_manager.py | ApiConfigManager._get_path_params | def _get_path_params(match):
"""Gets path parameters from a regular expression match.
Args:
match: A regular expression Match object for a path.
Returns:
A dictionary containing the variable names converted from base64.
"""
result = {}
for var_name, value in match.groupdict().iteri... | python | def _get_path_params(match):
"""Gets path parameters from a regular expression match.
Args:
match: A regular expression Match object for a path.
Returns:
A dictionary containing the variable names converted from base64.
"""
result = {}
for var_name, value in match.groupdict().iteri... | Gets path parameters from a regular expression match.
Args:
match: A regular expression Match object for a path.
Returns:
A dictionary containing the variable names converted from base64. | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config_manager.py#L153-L166 |
cloudendpoints/endpoints-python | endpoints/api_config_manager.py | ApiConfigManager.lookup_rest_method | def lookup_rest_method(self, path, request_uri, http_method):
"""Look up the rest method at call time.
The method is looked up in self._rest_methods, the list it is saved
in for SaveRestMethod.
Args:
path: A string containing the path from the URL of the request.
http_method: A string cont... | python | def lookup_rest_method(self, path, request_uri, http_method):
"""Look up the rest method at call time.
The method is looked up in self._rest_methods, the list it is saved
in for SaveRestMethod.
Args:
path: A string containing the path from the URL of the request.
http_method: A string cont... | Look up the rest method at call time.
The method is looked up in self._rest_methods, the list it is saved
in for SaveRestMethod.
Args:
path: A string containing the path from the URL of the request.
http_method: A string containing HTTP method of the request.
Returns:
Tuple of (<met... | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config_manager.py#L168-L202 |
cloudendpoints/endpoints-python | endpoints/api_config_manager.py | ApiConfigManager._add_discovery_config | def _add_discovery_config(self):
"""Add the Discovery configuration to our list of configs.
This should only be called with self._config_lock. The code here assumes
the lock is held.
"""
lookup_key = (discovery_service.DiscoveryService.API_CONFIG['name'],
discovery_service.Discov... | python | def _add_discovery_config(self):
"""Add the Discovery configuration to our list of configs.
This should only be called with self._config_lock. The code here assumes
the lock is held.
"""
lookup_key = (discovery_service.DiscoveryService.API_CONFIG['name'],
discovery_service.Discov... | Add the Discovery configuration to our list of configs.
This should only be called with self._config_lock. The code here assumes
the lock is held. | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config_manager.py#L204-L212 |
cloudendpoints/endpoints-python | endpoints/api_config_manager.py | ApiConfigManager.save_config | def save_config(self, lookup_key, config):
"""Save a configuration to the cache of configs.
Args:
lookup_key: A string containing the cache lookup key.
config: The dict containing the configuration to save to the cache.
"""
with self._config_lock:
self._configs[lookup_key] = config | python | def save_config(self, lookup_key, config):
"""Save a configuration to the cache of configs.
Args:
lookup_key: A string containing the cache lookup key.
config: The dict containing the configuration to save to the cache.
"""
with self._config_lock:
self._configs[lookup_key] = config | Save a configuration to the cache of configs.
Args:
lookup_key: A string containing the cache lookup key.
config: The dict containing the configuration to save to the cache. | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config_manager.py#L214-L222 |
cloudendpoints/endpoints-python | endpoints/api_config_manager.py | ApiConfigManager._from_safe_path_param_name | def _from_safe_path_param_name(safe_parameter):
"""Takes a safe regex group name and converts it back to the original value.
Only alphanumeric characters and underscore are allowed in variable name
tokens, and numeric are not allowed as the first character.
The safe_parameter is a base32 representatio... | python | def _from_safe_path_param_name(safe_parameter):
"""Takes a safe regex group name and converts it back to the original value.
Only alphanumeric characters and underscore are allowed in variable name
tokens, and numeric are not allowed as the first character.
The safe_parameter is a base32 representatio... | Takes a safe regex group name and converts it back to the original value.
Only alphanumeric characters and underscore are allowed in variable name
tokens, and numeric are not allowed as the first character.
The safe_parameter is a base32 representation of the actual value.
Args:
safe_parameter:... | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config_manager.py#L245-L264 |
cloudendpoints/endpoints-python | endpoints/api_config_manager.py | ApiConfigManager._compile_path_pattern | def _compile_path_pattern(pattern):
r"""Generates a compiled regex pattern for a path pattern.
e.g. '/MyApi/v1/notes/{id}'
returns re.compile(r'/MyApi/v1/notes/(?P<id>[^/?#\[\]{}]*)')
Args:
pattern: A string, the parameterized path pattern to be checked.
Returns:
A compiled regex obje... | python | def _compile_path_pattern(pattern):
r"""Generates a compiled regex pattern for a path pattern.
e.g. '/MyApi/v1/notes/{id}'
returns re.compile(r'/MyApi/v1/notes/(?P<id>[^/?#\[\]{}]*)')
Args:
pattern: A string, the parameterized path pattern to be checked.
Returns:
A compiled regex obje... | r"""Generates a compiled regex pattern for a path pattern.
e.g. '/MyApi/v1/notes/{id}'
returns re.compile(r'/MyApi/v1/notes/(?P<id>[^/?#\[\]{}]*)')
Args:
pattern: A string, the parameterized path pattern to be checked.
Returns:
A compiled regex object to match this path pattern. | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config_manager.py#L267-L304 |
cloudendpoints/endpoints-python | endpoints/api_config_manager.py | ApiConfigManager._save_rest_method | def _save_rest_method(self, method_name, api_name, version, method):
"""Store Rest api methods in a list for lookup at call time.
The list is self._rest_methods, a list of tuples:
[(<compiled_path>, <path_pattern>, <method_dict>), ...]
where:
<compiled_path> is a compiled regex to match against... | python | def _save_rest_method(self, method_name, api_name, version, method):
"""Store Rest api methods in a list for lookup at call time.
The list is self._rest_methods, a list of tuples:
[(<compiled_path>, <path_pattern>, <method_dict>), ...]
where:
<compiled_path> is a compiled regex to match against... | Store Rest api methods in a list for lookup at call time.
The list is self._rest_methods, a list of tuples:
[(<compiled_path>, <path_pattern>, <method_dict>), ...]
where:
<compiled_path> is a compiled regex to match against the incoming URL
<path_pattern> is a string representing the original... | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config_manager.py#L306-L350 |
cloudendpoints/endpoints-python | endpoints/apiserving.py | api_server | def api_server(api_services, **kwargs):
"""Create an api_server.
The primary function of this method is to set up the WSGIApplication
instance for the service handlers described by the services passed in.
Additionally, it registers each API in ApiConfigRegistry for later use
in the BackendService.getApiConfi... | python | def api_server(api_services, **kwargs):
"""Create an api_server.
The primary function of this method is to set up the WSGIApplication
instance for the service handlers described by the services passed in.
Additionally, it registers each API in ApiConfigRegistry for later use
in the BackendService.getApiConfi... | Create an api_server.
The primary function of this method is to set up the WSGIApplication
instance for the service handlers described by the services passed in.
Additionally, it registers each API in ApiConfigRegistry for later use
in the BackendService.getApiConfigs() (API config enumeration service).
It a... | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/apiserving.py#L541-L606 |
cloudendpoints/endpoints-python | endpoints/apiserving.py | ApiConfigRegistry.register_backend | def register_backend(self, config_contents):
"""Register a single API and its config contents.
Args:
config_contents: Dict containing API configuration.
"""
if config_contents is None:
return
self.__register_class(config_contents)
self.__api_configs.append(config_contents)
self.... | python | def register_backend(self, config_contents):
"""Register a single API and its config contents.
Args:
config_contents: Dict containing API configuration.
"""
if config_contents is None:
return
self.__register_class(config_contents)
self.__api_configs.append(config_contents)
self.... | Register a single API and its config contents.
Args:
config_contents: Dict containing API configuration. | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/apiserving.py#L197-L207 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.