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_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
welbornprod/colr | colr/progress.py | AnimatedProgress._advance_frame | def _advance_frame(self):
""" Sets `self.current_frame` to the next frame, looping to the
beginning if needed.
"""
self.current_frame += 1
if self.current_frame == self.frame_len:
self.current_frame = 0 | python | def _advance_frame(self):
""" Sets `self.current_frame` to the next frame, looping to the
beginning if needed.
"""
self.current_frame += 1
if self.current_frame == self.frame_len:
self.current_frame = 0 | [
"def",
"_advance_frame",
"(",
"self",
")",
":",
"self",
".",
"current_frame",
"+=",
"1",
"if",
"self",
".",
"current_frame",
"==",
"self",
".",
"frame_len",
":",
"self",
".",
"current_frame",
"=",
"0"
] | Sets `self.current_frame` to the next frame, looping to the
beginning if needed. | [
"Sets",
"self",
".",
"current_frame",
"to",
"the",
"next",
"frame",
"looping",
"to",
"the",
"beginning",
"if",
"needed",
"."
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress.py#L568-L574 |
welbornprod/colr | colr/progress.py | AnimatedProgress._get_delay | def _get_delay(self, userdelay, frameslist):
""" Get the appropriate delay value to use, trying in this order:
userdelay
frameslist.delay
default_delay
The user can override the frameslist's delay by specifiying a
value, and if neither are... | python | def _get_delay(self, userdelay, frameslist):
""" Get the appropriate delay value to use, trying in this order:
userdelay
frameslist.delay
default_delay
The user can override the frameslist's delay by specifiying a
value, and if neither are... | [
"def",
"_get_delay",
"(",
"self",
",",
"userdelay",
",",
"frameslist",
")",
":",
"# User frameslists might not be a FrameSet.",
"delay",
"=",
"userdelay",
"or",
"getattr",
"(",
"frameslist",
",",
"'delay'",
",",
"None",
")",
"delay",
"=",
"(",
"delay",
"or",
"... | Get the appropriate delay value to use, trying in this order:
userdelay
frameslist.delay
default_delay
The user can override the frameslist's delay by specifiying a
value, and if neither are given the default is used. | [
"Get",
"the",
"appropriate",
"delay",
"value",
"to",
"use",
"trying",
"in",
"this",
"order",
":",
"userdelay",
"frameslist",
".",
"delay",
"default_delay"
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress.py#L576-L590 |
welbornprod/colr | colr/progress.py | AnimatedProgress.write_char_delay | def write_char_delay(self, ctl, delay):
""" Write the formatted format pieces in order, applying a delay
between characters for the text only.
"""
for i, fmt in enumerate(self.fmt):
if '{text' in fmt:
# The text will use a write delay.
ctl.... | python | def write_char_delay(self, ctl, delay):
""" Write the formatted format pieces in order, applying a delay
between characters for the text only.
"""
for i, fmt in enumerate(self.fmt):
if '{text' in fmt:
# The text will use a write delay.
ctl.... | [
"def",
"write_char_delay",
"(",
"self",
",",
"ctl",
",",
"delay",
")",
":",
"for",
"i",
",",
"fmt",
"in",
"enumerate",
"(",
"self",
".",
"fmt",
")",
":",
"if",
"'{text'",
"in",
"fmt",
":",
"# The text will use a write delay.",
"ctl",
".",
"text",
"(",
... | Write the formatted format pieces in order, applying a delay
between characters for the text only. | [
"Write",
"the",
"formatted",
"format",
"pieces",
"in",
"order",
"applying",
"a",
"delay",
"between",
"characters",
"for",
"the",
"text",
"only",
"."
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress.py#L600-L624 |
welbornprod/colr | colr/progress.py | ProgressBar.update | def update(self, percent=None, text=None):
""" Update the progress bar percentage and message. """
if percent is not None:
self.percent = percent
if text is not None:
self.message = text
super().update() | python | def update(self, percent=None, text=None):
""" Update the progress bar percentage and message. """
if percent is not None:
self.percent = percent
if text is not None:
self.message = text
super().update() | [
"def",
"update",
"(",
"self",
",",
"percent",
"=",
"None",
",",
"text",
"=",
"None",
")",
":",
"if",
"percent",
"is",
"not",
"None",
":",
"self",
".",
"percent",
"=",
"percent",
"if",
"text",
"is",
"not",
"None",
":",
"self",
".",
"message",
"=",
... | Update the progress bar percentage and message. | [
"Update",
"the",
"progress",
"bar",
"percentage",
"and",
"message",
"."
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress.py#L754-L760 |
welbornprod/colr | colr/progress_frames.py | cls_get_by_name | def cls_get_by_name(cls, name):
""" Return a class attribute by searching the attributes `name` attribute.
"""
try:
val = getattr(cls, name)
except AttributeError:
for attr in (a for a in dir(cls) if not a.startswith('_')):
try:
val = getattr(cls, attr)
... | python | def cls_get_by_name(cls, name):
""" Return a class attribute by searching the attributes `name` attribute.
"""
try:
val = getattr(cls, name)
except AttributeError:
for attr in (a for a in dir(cls) if not a.startswith('_')):
try:
val = getattr(cls, attr)
... | [
"def",
"cls_get_by_name",
"(",
"cls",
",",
"name",
")",
":",
"try",
":",
"val",
"=",
"getattr",
"(",
"cls",
",",
"name",
")",
"except",
"AttributeError",
":",
"for",
"attr",
"in",
"(",
"a",
"for",
"a",
"in",
"dir",
"(",
"cls",
")",
"if",
"not",
"... | Return a class attribute by searching the attributes `name` attribute. | [
"Return",
"a",
"class",
"attribute",
"by",
"searching",
"the",
"attributes",
"name",
"attribute",
"."
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L39-L60 |
welbornprod/colr | colr/progress_frames.py | cls_names | def cls_names(cls, wanted_cls, registered=True):
""" Return a list of attributes for all `wanted_cls` attributes in this
class, where `wanted_cls` is the desired attribute type.
"""
return [
fset.name
for fset in cls_sets(cls, wanted_cls, registered=registered)
] | python | def cls_names(cls, wanted_cls, registered=True):
""" Return a list of attributes for all `wanted_cls` attributes in this
class, where `wanted_cls` is the desired attribute type.
"""
return [
fset.name
for fset in cls_sets(cls, wanted_cls, registered=registered)
] | [
"def",
"cls_names",
"(",
"cls",
",",
"wanted_cls",
",",
"registered",
"=",
"True",
")",
":",
"return",
"[",
"fset",
".",
"name",
"for",
"fset",
"in",
"cls_sets",
"(",
"cls",
",",
"wanted_cls",
",",
"registered",
"=",
"registered",
")",
"]"
] | Return a list of attributes for all `wanted_cls` attributes in this
class, where `wanted_cls` is the desired attribute type. | [
"Return",
"a",
"list",
"of",
"attributes",
"for",
"all",
"wanted_cls",
"attributes",
"in",
"this",
"class",
"where",
"wanted_cls",
"is",
"the",
"desired",
"attribute",
"type",
"."
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L63-L70 |
welbornprod/colr | colr/progress_frames.py | cls_register | def cls_register(cls, frameset, new_class, init_args, name=None):
""" Register a new FrameSet or FrameSet subclass as a member/attribute
of a class.
Returns the new FrameSet or FrameSet subclass.
Arguments:
frameset : An existing FrameSet, or an iterable of strings.
... | python | def cls_register(cls, frameset, new_class, init_args, name=None):
""" Register a new FrameSet or FrameSet subclass as a member/attribute
of a class.
Returns the new FrameSet or FrameSet subclass.
Arguments:
frameset : An existing FrameSet, or an iterable of strings.
... | [
"def",
"cls_register",
"(",
"cls",
",",
"frameset",
",",
"new_class",
",",
"init_args",
",",
"name",
"=",
"None",
")",
":",
"name",
"=",
"name",
"or",
"getattr",
"(",
"frameset",
",",
"'name'",
",",
"None",
")",
"if",
"name",
"is",
"None",
":",
"rais... | Register a new FrameSet or FrameSet subclass as a member/attribute
of a class.
Returns the new FrameSet or FrameSet subclass.
Arguments:
frameset : An existing FrameSet, or an iterable of strings.
init_args : A list of properties from the `frameset` to try to use
... | [
"Register",
"a",
"new",
"FrameSet",
"or",
"FrameSet",
"subclass",
"as",
"a",
"member",
"/",
"attribute",
"of",
"a",
"class",
".",
"Returns",
"the",
"new",
"FrameSet",
"or",
"FrameSet",
"subclass",
".",
"Arguments",
":",
"frameset",
":",
"An",
"existing",
"... | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L73-L101 |
welbornprod/colr | colr/progress_frames.py | cls_sets | def cls_sets(cls, wanted_cls, registered=True):
""" Return a list of all `wanted_cls` attributes in this
class, where `wanted_cls` is the desired attribute type.
"""
sets = []
for attr in dir(cls):
if attr.startswith('_'):
continue
val = getattr(cls, attr, None)
... | python | def cls_sets(cls, wanted_cls, registered=True):
""" Return a list of all `wanted_cls` attributes in this
class, where `wanted_cls` is the desired attribute type.
"""
sets = []
for attr in dir(cls):
if attr.startswith('_'):
continue
val = getattr(cls, attr, None)
... | [
"def",
"cls_sets",
"(",
"cls",
",",
"wanted_cls",
",",
"registered",
"=",
"True",
")",
":",
"sets",
"=",
"[",
"]",
"for",
"attr",
"in",
"dir",
"(",
"cls",
")",
":",
"if",
"attr",
".",
"startswith",
"(",
"'_'",
")",
":",
"continue",
"val",
"=",
"g... | Return a list of all `wanted_cls` attributes in this
class, where `wanted_cls` is the desired attribute type. | [
"Return",
"a",
"list",
"of",
"all",
"wanted_cls",
"attributes",
"in",
"this",
"class",
"where",
"wanted_cls",
"is",
"the",
"desired",
"attribute",
"type",
"."
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L104-L118 |
welbornprod/colr | colr/progress_frames.py | _build_color_variants | def _build_color_variants(cls):
""" Build colorized variants of all frames and return a list of
all frame object names.
"""
# Get the basic frame types first.
frametypes = cls.sets(registered=False)
_colornames = [
# 'black', disabled for now, it won't show on my terminal.
'... | python | def _build_color_variants(cls):
""" Build colorized variants of all frames and return a list of
all frame object names.
"""
# Get the basic frame types first.
frametypes = cls.sets(registered=False)
_colornames = [
# 'black', disabled for now, it won't show on my terminal.
'... | [
"def",
"_build_color_variants",
"(",
"cls",
")",
":",
"# Get the basic frame types first.",
"frametypes",
"=",
"cls",
".",
"sets",
"(",
"registered",
"=",
"False",
")",
"_colornames",
"=",
"[",
"# 'black', disabled for now, it won't show on my terminal.",
"'red'",
",",
... | Build colorized variants of all frames and return a list of
all frame object names. | [
"Build",
"colorized",
"variants",
"of",
"all",
"frames",
"and",
"return",
"a",
"list",
"of",
"all",
"frame",
"object",
"names",
"."
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L808-L832 |
welbornprod/colr | colr/progress_frames.py | FrameSet.from_barset | def from_barset(
cls, barset, name=None, delay=None,
use_wrapper=True, wrapper=None):
""" Copy a BarSet's frames to create a new FrameSet.
Arguments:
barset : An existing BarSet object to copy frames from.
name : A name for the new... | python | def from_barset(
cls, barset, name=None, delay=None,
use_wrapper=True, wrapper=None):
""" Copy a BarSet's frames to create a new FrameSet.
Arguments:
barset : An existing BarSet object to copy frames from.
name : A name for the new... | [
"def",
"from_barset",
"(",
"cls",
",",
"barset",
",",
"name",
"=",
"None",
",",
"delay",
"=",
"None",
",",
"use_wrapper",
"=",
"True",
",",
"wrapper",
"=",
"None",
")",
":",
"if",
"wrapper",
":",
"data",
"=",
"tuple",
"(",
"barset",
".",
"wrap_str",
... | Copy a BarSet's frames to create a new FrameSet.
Arguments:
barset : An existing BarSet object to copy frames from.
name : A name for the new FrameSet.
delay : Delay for the animation.
use_wrapper : Whether to use the old bar... | [
"Copy",
"a",
"BarSet",
"s",
"frames",
"to",
"create",
"a",
"new",
"FrameSet",
"."
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L378-L402 |
welbornprod/colr | colr/progress_frames.py | BarSet.as_gradient | def as_gradient(self, name=None, style=None, rgb_mode=False):
""" Wrap each frame in a Colr object, using `Colr.gradient`.
Arguments:
name : Starting color name. One of `Colr.gradient_names`.
"""
return self._as_gradient(
('wrapper', ),
name=n... | python | def as_gradient(self, name=None, style=None, rgb_mode=False):
""" Wrap each frame in a Colr object, using `Colr.gradient`.
Arguments:
name : Starting color name. One of `Colr.gradient_names`.
"""
return self._as_gradient(
('wrapper', ),
name=n... | [
"def",
"as_gradient",
"(",
"self",
",",
"name",
"=",
"None",
",",
"style",
"=",
"None",
",",
"rgb_mode",
"=",
"False",
")",
":",
"return",
"self",
".",
"_as_gradient",
"(",
"(",
"'wrapper'",
",",
")",
",",
"name",
"=",
"name",
",",
"style",
"=",
"s... | Wrap each frame in a Colr object, using `Colr.gradient`.
Arguments:
name : Starting color name. One of `Colr.gradient_names`. | [
"Wrap",
"each",
"frame",
"in",
"a",
"Colr",
"object",
"using",
"Colr",
".",
"gradient",
".",
"Arguments",
":",
"name",
":",
"Starting",
"color",
"name",
".",
"One",
"of",
"Colr",
".",
"gradient_names",
"."
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L440-L450 |
welbornprod/colr | colr/progress_frames.py | BarSet.as_percent | def as_percent(self, percent):
""" Return a string representing a percentage of this progress bar.
BarSet('1234567890', wrapper=('[, ']')).as_percent(50)
>>> '[12345 ]'
"""
if not self:
return self.wrap_str()
length = len(self)
# Using mod... | python | def as_percent(self, percent):
""" Return a string representing a percentage of this progress bar.
BarSet('1234567890', wrapper=('[, ']')).as_percent(50)
>>> '[12345 ]'
"""
if not self:
return self.wrap_str()
length = len(self)
# Using mod... | [
"def",
"as_percent",
"(",
"self",
",",
"percent",
")",
":",
"if",
"not",
"self",
":",
"return",
"self",
".",
"wrap_str",
"(",
")",
"length",
"=",
"len",
"(",
"self",
")",
"# Using mod 100, to provide some kind of \"auto reset\". 0 is 0 though.",
"percentmod",
"=",... | Return a string representing a percentage of this progress bar.
BarSet('1234567890', wrapper=('[, ']')).as_percent(50)
>>> '[12345 ]' | [
"Return",
"a",
"string",
"representing",
"a",
"percentage",
"of",
"this",
"progress",
"bar",
".",
"BarSet",
"(",
"1234567890",
"wrapper",
"=",
"(",
"[",
"]",
"))",
".",
"as_percent",
"(",
"50",
")",
">>>",
"[",
"12345",
"]"
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L452-L469 |
welbornprod/colr | colr/progress_frames.py | BarSet.as_rainbow | def as_rainbow(self, offset=35, style=None, rgb_mode=False):
""" Wrap each frame in a Colr object, using `Colr.rainbow`. """
return self._as_rainbow(
('wrapper', ),
offset=offset,
style=style,
rgb_mode=rgb_mode,
) | python | def as_rainbow(self, offset=35, style=None, rgb_mode=False):
""" Wrap each frame in a Colr object, using `Colr.rainbow`. """
return self._as_rainbow(
('wrapper', ),
offset=offset,
style=style,
rgb_mode=rgb_mode,
) | [
"def",
"as_rainbow",
"(",
"self",
",",
"offset",
"=",
"35",
",",
"style",
"=",
"None",
",",
"rgb_mode",
"=",
"False",
")",
":",
"return",
"self",
".",
"_as_rainbow",
"(",
"(",
"'wrapper'",
",",
")",
",",
"offset",
"=",
"offset",
",",
"style",
"=",
... | Wrap each frame in a Colr object, using `Colr.rainbow`. | [
"Wrap",
"each",
"frame",
"in",
"a",
"Colr",
"object",
"using",
"Colr",
".",
"rainbow",
"."
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L471-L478 |
welbornprod/colr | colr/progress_frames.py | BarSet.from_char | def from_char(
cls, char, name=None, width=None, fill_char=None,
bounce=False, reverse=False, back_char=None, wrapper=None):
""" Create progress bar frames from a "moving" character.
The frames simulate movement of the character, from left to
right through empty s... | python | def from_char(
cls, char, name=None, width=None, fill_char=None,
bounce=False, reverse=False, back_char=None, wrapper=None):
""" Create progress bar frames from a "moving" character.
The frames simulate movement of the character, from left to
right through empty s... | [
"def",
"from_char",
"(",
"cls",
",",
"char",
",",
"name",
"=",
"None",
",",
"width",
"=",
"None",
",",
"fill_char",
"=",
"None",
",",
"bounce",
"=",
"False",
",",
"reverse",
"=",
"False",
",",
"back_char",
"=",
"None",
",",
"wrapper",
"=",
"None",
... | Create progress bar frames from a "moving" character.
The frames simulate movement of the character, from left to
right through empty space (`fill_char`).
Arguments:
char : Character to move across the bar.
name : Name for the new ... | [
"Create",
"progress",
"bar",
"frames",
"from",
"a",
"moving",
"character",
".",
"The",
"frames",
"simulate",
"movement",
"of",
"the",
"character",
"from",
"left",
"to",
"right",
"through",
"empty",
"space",
"(",
"fill_char",
")",
"."
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L481-L515 |
welbornprod/colr | colr/progress_frames.py | BarSet.from_str | def from_str(cls, s, name=None, fill_char=None, wrapper=None):
""" Create progress bar frames from a single string.
The frames simulate growth, from an empty string to the final
string (`s`).
Arguments:
s : Final string for a complete progress bar.
... | python | def from_str(cls, s, name=None, fill_char=None, wrapper=None):
""" Create progress bar frames from a single string.
The frames simulate growth, from an empty string to the final
string (`s`).
Arguments:
s : Final string for a complete progress bar.
... | [
"def",
"from_str",
"(",
"cls",
",",
"s",
",",
"name",
"=",
"None",
",",
"fill_char",
"=",
"None",
",",
"wrapper",
"=",
"None",
")",
":",
"fill_char",
"=",
"fill_char",
"or",
"cls",
".",
"default_fill_char",
"maxlen",
"=",
"len",
"(",
"s",
")",
"frame... | Create progress bar frames from a single string.
The frames simulate growth, from an empty string to the final
string (`s`).
Arguments:
s : Final string for a complete progress bar.
name : Name for the new BarSet.
fill_c... | [
"Create",
"progress",
"bar",
"frames",
"from",
"a",
"single",
"string",
".",
"The",
"frames",
"simulate",
"growth",
"from",
"an",
"empty",
"string",
"to",
"the",
"final",
"string",
"(",
"s",
")",
"."
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L518-L549 |
welbornprod/colr | colr/progress_frames.py | BarSet._generate_move | def _generate_move(
cls, char, width=None, fill_char=None,
bounce=False, reverse=True, back_char=None):
""" Yields strings that simulate movement of a character from left
to right. For use with `BarSet.from_char`.
Arguments:
char : Charac... | python | def _generate_move(
cls, char, width=None, fill_char=None,
bounce=False, reverse=True, back_char=None):
""" Yields strings that simulate movement of a character from left
to right. For use with `BarSet.from_char`.
Arguments:
char : Charac... | [
"def",
"_generate_move",
"(",
"cls",
",",
"char",
",",
"width",
"=",
"None",
",",
"fill_char",
"=",
"None",
",",
"bounce",
"=",
"False",
",",
"reverse",
"=",
"True",
",",
"back_char",
"=",
"None",
")",
":",
"width",
"=",
"width",
"or",
"cls",
".",
... | Yields strings that simulate movement of a character from left
to right. For use with `BarSet.from_char`.
Arguments:
char : Character to move across the progress bar.
width : Width for the progress bar.
Default: cl... | [
"Yields",
"strings",
"that",
"simulate",
"movement",
"of",
"a",
"character",
"from",
"left",
"to",
"right",
".",
"For",
"use",
"with",
"BarSet",
".",
"from_char",
"."
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L552-L597 |
welbornprod/colr | colr/progress_frames.py | BarSet.with_wrapper | def with_wrapper(self, wrapper=None, name=None):
""" Copy this BarSet, and return a new BarSet with the specified
name and wrapper.
If no name is given, `{self.name}_custom_wrapper` is used.
If no wrapper is given, the new BarSet will have no wrapper.
"""
name... | python | def with_wrapper(self, wrapper=None, name=None):
""" Copy this BarSet, and return a new BarSet with the specified
name and wrapper.
If no name is given, `{self.name}_custom_wrapper` is used.
If no wrapper is given, the new BarSet will have no wrapper.
"""
name... | [
"def",
"with_wrapper",
"(",
"self",
",",
"wrapper",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"name",
"=",
"name",
"or",
"'{}_custom_wrapper'",
".",
"format",
"(",
"self",
".",
"name",
")",
"return",
"self",
".",
"__class__",
"(",
"self",
".",
... | Copy this BarSet, and return a new BarSet with the specified
name and wrapper.
If no name is given, `{self.name}_custom_wrapper` is used.
If no wrapper is given, the new BarSet will have no wrapper. | [
"Copy",
"this",
"BarSet",
"and",
"return",
"a",
"new",
"BarSet",
"with",
"the",
"specified",
"name",
"and",
"wrapper",
".",
"If",
"no",
"name",
"is",
"given",
"{",
"self",
".",
"name",
"}",
"_custom_wrapper",
"is",
"used",
".",
"If",
"no",
"wrapper",
"... | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L599-L606 |
welbornprod/colr | colr/progress_frames.py | BarSet.wrap_str | def wrap_str(self, s=None, wrapper=None):
""" Wrap a string in self.wrapper, with some extra handling for
empty/None strings.
If `wrapper` is set, use it instead.
"""
wrapper = wrapper or (self.wrapper or ('', ''))
return str('' if s is None else s).join(wrapper) | python | def wrap_str(self, s=None, wrapper=None):
""" Wrap a string in self.wrapper, with some extra handling for
empty/None strings.
If `wrapper` is set, use it instead.
"""
wrapper = wrapper or (self.wrapper or ('', ''))
return str('' if s is None else s).join(wrapper) | [
"def",
"wrap_str",
"(",
"self",
",",
"s",
"=",
"None",
",",
"wrapper",
"=",
"None",
")",
":",
"wrapper",
"=",
"wrapper",
"or",
"(",
"self",
".",
"wrapper",
"or",
"(",
"''",
",",
"''",
")",
")",
"return",
"str",
"(",
"''",
"if",
"s",
"is",
"None... | Wrap a string in self.wrapper, with some extra handling for
empty/None strings.
If `wrapper` is set, use it instead. | [
"Wrap",
"a",
"string",
"in",
"self",
".",
"wrapper",
"with",
"some",
"extra",
"handling",
"for",
"empty",
"/",
"None",
"strings",
".",
"If",
"wrapper",
"is",
"set",
"use",
"it",
"instead",
"."
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L608-L614 |
welbornprod/colr | colr/progress_frames.py | Bars.register | def register(cls, barset, name=None):
""" Register a new BarSet as a member/attribute of this class.
Returns the new BarSet.
Arguments:
barset : An existing BarSet, or an iterable of strings.
name : New name for the BarSet, also used as the
... | python | def register(cls, barset, name=None):
""" Register a new BarSet as a member/attribute of this class.
Returns the new BarSet.
Arguments:
barset : An existing BarSet, or an iterable of strings.
name : New name for the BarSet, also used as the
... | [
"def",
"register",
"(",
"cls",
",",
"barset",
",",
"name",
"=",
"None",
")",
":",
"return",
"cls_register",
"(",
"cls",
",",
"barset",
",",
"BarSet",
",",
"(",
"'wrapper'",
",",
")",
",",
"name",
"=",
"name",
")"
] | Register a new BarSet as a member/attribute of this class.
Returns the new BarSet.
Arguments:
barset : An existing BarSet, or an iterable of strings.
name : New name for the BarSet, also used as the
classes attribute name.
... | [
"Register",
"a",
"new",
"BarSet",
"as",
"a",
"member",
"/",
"attribute",
"of",
"this",
"class",
".",
"Returns",
"the",
"new",
"BarSet",
".",
"Arguments",
":",
"barset",
":",
"An",
"existing",
"BarSet",
"or",
"an",
"iterable",
"of",
"strings",
".",
"name"... | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L632-L643 |
welbornprod/colr | colr/progress_frames.py | Frames.register | def register(cls, frameset, name=None):
""" Register a new FrameSet as a member/attribute of this class.
Returns the new FrameSet.
Arguments:
frameset : An existing FrameSet, or an iterable of strings.
name : New name for the FrameSet, also used as t... | python | def register(cls, frameset, name=None):
""" Register a new FrameSet as a member/attribute of this class.
Returns the new FrameSet.
Arguments:
frameset : An existing FrameSet, or an iterable of strings.
name : New name for the FrameSet, also used as t... | [
"def",
"register",
"(",
"cls",
",",
"frameset",
",",
"name",
"=",
"None",
")",
":",
"return",
"cls_register",
"(",
"cls",
",",
"frameset",
",",
"FrameSet",
",",
"(",
"'delay'",
",",
")",
",",
"name",
"=",
"name",
")"
] | Register a new FrameSet as a member/attribute of this class.
Returns the new FrameSet.
Arguments:
frameset : An existing FrameSet, or an iterable of strings.
name : New name for the FrameSet, also used as the
classes attribute nam... | [
"Register",
"a",
"new",
"FrameSet",
"as",
"a",
"member",
"/",
"attribute",
"of",
"this",
"class",
".",
"Returns",
"the",
"new",
"FrameSet",
".",
"Arguments",
":",
"frameset",
":",
"An",
"existing",
"FrameSet",
"or",
"an",
"iterable",
"of",
"strings",
".",
... | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L685-L696 |
geertj/gruvi | lib/gruvi/transports.py | TransportError.from_errno | def from_errno(cls, errno):
"""Create a new instance from a :mod:`pyuv.errno` error code."""
message = '{}: {}'.format(pyuv.errno.errorcode.get(errno, errno),
pyuv.errno.strerror(errno))
return cls(message, errno) | python | def from_errno(cls, errno):
"""Create a new instance from a :mod:`pyuv.errno` error code."""
message = '{}: {}'.format(pyuv.errno.errorcode.get(errno, errno),
pyuv.errno.strerror(errno))
return cls(message, errno) | [
"def",
"from_errno",
"(",
"cls",
",",
"errno",
")",
":",
"message",
"=",
"'{}: {}'",
".",
"format",
"(",
"pyuv",
".",
"errno",
".",
"errorcode",
".",
"get",
"(",
"errno",
",",
"errno",
")",
",",
"pyuv",
".",
"errno",
".",
"strerror",
"(",
"errno",
... | Create a new instance from a :mod:`pyuv.errno` error code. | [
"Create",
"a",
"new",
"instance",
"from",
"a",
":",
"mod",
":",
"pyuv",
".",
"errno",
"error",
"code",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/transports.py#L36-L40 |
geertj/gruvi | lib/gruvi/transports.py | BaseTransport.start | def start(self, protocol):
"""Bind to *protocol* and start calling callbacks on it. """
if self._protocol is not None:
raise TransportError('already started')
self._protocol = protocol
self._protocol.connection_made(self)
if self._readable:
self.resume_rea... | python | def start(self, protocol):
"""Bind to *protocol* and start calling callbacks on it. """
if self._protocol is not None:
raise TransportError('already started')
self._protocol = protocol
self._protocol.connection_made(self)
if self._readable:
self.resume_rea... | [
"def",
"start",
"(",
"self",
",",
"protocol",
")",
":",
"if",
"self",
".",
"_protocol",
"is",
"not",
"None",
":",
"raise",
"TransportError",
"(",
"'already started'",
")",
"self",
".",
"_protocol",
"=",
"protocol",
"self",
".",
"_protocol",
".",
"connectio... | Bind to *protocol* and start calling callbacks on it. | [
"Bind",
"to",
"*",
"protocol",
"*",
"and",
"start",
"calling",
"callbacks",
"on",
"it",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/transports.py#L67-L77 |
geertj/gruvi | lib/gruvi/transports.py | BaseTransport.set_write_buffer_limits | def set_write_buffer_limits(self, high=None, low=None):
"""Set the low and high watermark for the write buffer."""
if high is None:
high = self.write_buffer_size
if low is None:
low = high // 2
if low > high:
low = high
self._write_buffer_high ... | python | def set_write_buffer_limits(self, high=None, low=None):
"""Set the low and high watermark for the write buffer."""
if high is None:
high = self.write_buffer_size
if low is None:
low = high // 2
if low > high:
low = high
self._write_buffer_high ... | [
"def",
"set_write_buffer_limits",
"(",
"self",
",",
"high",
"=",
"None",
",",
"low",
"=",
"None",
")",
":",
"if",
"high",
"is",
"None",
":",
"high",
"=",
"self",
".",
"write_buffer_size",
"if",
"low",
"is",
"None",
":",
"low",
"=",
"high",
"//",
"2",... | Set the low and high watermark for the write buffer. | [
"Set",
"the",
"low",
"and",
"high",
"watermark",
"for",
"the",
"write",
"buffer",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/transports.py#L96-L105 |
geertj/gruvi | lib/gruvi/transports.py | BaseTransport.close | def close(self):
"""Close the transport after all oustanding data has been written."""
if self._closing or self._handle.closed:
return
elif self._protocol is None:
raise TransportError('transport not started')
# If the write buffer is empty, close now. Otherwise d... | python | def close(self):
"""Close the transport after all oustanding data has been written."""
if self._closing or self._handle.closed:
return
elif self._protocol is None:
raise TransportError('transport not started')
# If the write buffer is empty, close now. Otherwise d... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_closing",
"or",
"self",
".",
"_handle",
".",
"closed",
":",
"return",
"elif",
"self",
".",
"_protocol",
"is",
"None",
":",
"raise",
"TransportError",
"(",
"'transport not started'",
")",
"# If the... | Close the transport after all oustanding data has been written. | [
"Close",
"the",
"transport",
"after",
"all",
"oustanding",
"data",
"has",
"been",
"written",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/transports.py#L163-L175 |
geertj/gruvi | lib/gruvi/transports.py | BaseTransport.abort | def abort(self):
"""Close the transport immediately."""
if self._handle.closed:
return
elif self._protocol is None:
raise TransportError('transport not started')
self._handle.close(self._on_close_complete)
assert self._handle.closed | python | def abort(self):
"""Close the transport immediately."""
if self._handle.closed:
return
elif self._protocol is None:
raise TransportError('transport not started')
self._handle.close(self._on_close_complete)
assert self._handle.closed | [
"def",
"abort",
"(",
"self",
")",
":",
"if",
"self",
".",
"_handle",
".",
"closed",
":",
"return",
"elif",
"self",
".",
"_protocol",
"is",
"None",
":",
"raise",
"TransportError",
"(",
"'transport not started'",
")",
"self",
".",
"_handle",
".",
"close",
... | Close the transport immediately. | [
"Close",
"the",
"transport",
"immediately",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/transports.py#L177-L184 |
geertj/gruvi | lib/gruvi/transports.py | Transport.write | def write(self, data, handle=None):
"""Write *data* to the transport."""
if not isinstance(data, (bytes, bytearray, memoryview)):
raise TypeError("data: expecting a bytes-like instance, got {!r}"
.format(type(data).__name__))
if handle is not None and ... | python | def write(self, data, handle=None):
"""Write *data* to the transport."""
if not isinstance(data, (bytes, bytearray, memoryview)):
raise TypeError("data: expecting a bytes-like instance, got {!r}"
.format(type(data).__name__))
if handle is not None and ... | [
"def",
"write",
"(",
"self",
",",
"data",
",",
"handle",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"(",
"bytes",
",",
"bytearray",
",",
"memoryview",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"data: expecting a bytes-like instan... | Write *data* to the transport. | [
"Write",
"*",
"data",
"*",
"to",
"the",
"transport",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/transports.py#L287-L311 |
geertj/gruvi | lib/gruvi/transports.py | Transport.write_eof | def write_eof(self):
"""Shut down the write direction of the transport."""
self._check_status()
if not self._writable:
raise TransportError('transport is not writable')
if self._closing:
raise TransportError('transport is closing')
try:
self._h... | python | def write_eof(self):
"""Shut down the write direction of the transport."""
self._check_status()
if not self._writable:
raise TransportError('transport is not writable')
if self._closing:
raise TransportError('transport is closing')
try:
self._h... | [
"def",
"write_eof",
"(",
"self",
")",
":",
"self",
".",
"_check_status",
"(",
")",
"if",
"not",
"self",
".",
"_writable",
":",
"raise",
"TransportError",
"(",
"'transport is not writable'",
")",
"if",
"self",
".",
"_closing",
":",
"raise",
"TransportError",
... | Shut down the write direction of the transport. | [
"Shut",
"down",
"the",
"write",
"direction",
"of",
"the",
"transport",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/transports.py#L318-L331 |
geertj/gruvi | lib/gruvi/transports.py | Transport.get_extra_info | def get_extra_info(self, name, default=None):
"""Get transport specific data.
In addition to the fields from :meth:`BaseTransport.get_extra_info`,
the following information is also available:
===================== ===================================================
Name ... | python | def get_extra_info(self, name, default=None):
"""Get transport specific data.
In addition to the fields from :meth:`BaseTransport.get_extra_info`,
the following information is also available:
===================== ===================================================
Name ... | [
"def",
"get_extra_info",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
")",
":",
"if",
"name",
"==",
"'sockname'",
":",
"if",
"not",
"hasattr",
"(",
"self",
".",
"_handle",
",",
"'getsockname'",
")",
":",
"return",
"default",
"try",
":",
"retu... | Get transport specific data.
In addition to the fields from :meth:`BaseTransport.get_extra_info`,
the following information is also available:
===================== ===================================================
Name Description
===================== ==... | [
"Get",
"transport",
"specific",
"data",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/transports.py#L337-L397 |
geertj/gruvi | lib/gruvi/transports.py | DatagramTransport._on_recv_complete | def _on_recv_complete(self, handle, addr, flags, data, error):
"""Callback used with handle.start_recv()."""
assert handle is self._handle
if error:
self._log.warning('pyuv error {} in recv callback', error)
self._protocol.error_received(TransportError.from_errno(error))
... | python | def _on_recv_complete(self, handle, addr, flags, data, error):
"""Callback used with handle.start_recv()."""
assert handle is self._handle
if error:
self._log.warning('pyuv error {} in recv callback', error)
self._protocol.error_received(TransportError.from_errno(error))
... | [
"def",
"_on_recv_complete",
"(",
"self",
",",
"handle",
",",
"addr",
",",
"flags",
",",
"data",
",",
"error",
")",
":",
"assert",
"handle",
"is",
"self",
".",
"_handle",
"if",
"error",
":",
"self",
".",
"_log",
".",
"warning",
"(",
"'pyuv error {} in rec... | Callback used with handle.start_recv(). | [
"Callback",
"used",
"with",
"handle",
".",
"start_recv",
"()",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/transports.py#L424-L434 |
geertj/gruvi | lib/gruvi/transports.py | DatagramTransport._on_send_complete | def _on_send_complete(self, handle, error):
"""Callback used with handle.send()."""
assert handle is self._handle
self._write_buffer_size -= 1
assert self._write_buffer_size >= 0
if self._error:
self._log.debug('ignore sendto status {} after error', error)
# S... | python | def _on_send_complete(self, handle, error):
"""Callback used with handle.send()."""
assert handle is self._handle
self._write_buffer_size -= 1
assert self._write_buffer_size >= 0
if self._error:
self._log.debug('ignore sendto status {} after error', error)
# S... | [
"def",
"_on_send_complete",
"(",
"self",
",",
"handle",
",",
"error",
")",
":",
"assert",
"handle",
"is",
"self",
".",
"_handle",
"self",
".",
"_write_buffer_size",
"-=",
"1",
"assert",
"self",
".",
"_write_buffer_size",
">=",
"0",
"if",
"self",
".",
"_err... | Callback used with handle.send(). | [
"Callback",
"used",
"with",
"handle",
".",
"send",
"()",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/transports.py#L456-L468 |
geertj/gruvi | lib/gruvi/transports.py | DatagramTransport.sendto | def sendto(self, data, addr=None):
"""Send a datagram containing *data* to *addr*.
The *addr* argument may be omitted only if the handle was bound to a
default remote address.
"""
if not isinstance(data, (bytes, bytearray, memoryview)):
raise TypeError("data: expecti... | python | def sendto(self, data, addr=None):
"""Send a datagram containing *data* to *addr*.
The *addr* argument may be omitted only if the handle was bound to a
default remote address.
"""
if not isinstance(data, (bytes, bytearray, memoryview)):
raise TypeError("data: expecti... | [
"def",
"sendto",
"(",
"self",
",",
"data",
",",
"addr",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"(",
"bytes",
",",
"bytearray",
",",
"memoryview",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"data: expecting a bytes-like instanc... | Send a datagram containing *data* to *addr*.
The *addr* argument may be omitted only if the handle was bound to a
default remote address. | [
"Send",
"a",
"datagram",
"containing",
"*",
"data",
"*",
"to",
"*",
"addr",
"*",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/transports.py#L470-L493 |
geertj/gruvi | lib/gruvi/dbus.py | parse_dbus_address | def parse_dbus_address(address):
"""Parse a D-BUS address string into a list of addresses."""
if address == 'session':
address = os.environ.get('DBUS_SESSION_BUS_ADDRESS')
if not address:
raise ValueError('$DBUS_SESSION_BUS_ADDRESS not set')
elif address == 'system':
addr... | python | def parse_dbus_address(address):
"""Parse a D-BUS address string into a list of addresses."""
if address == 'session':
address = os.environ.get('DBUS_SESSION_BUS_ADDRESS')
if not address:
raise ValueError('$DBUS_SESSION_BUS_ADDRESS not set')
elif address == 'system':
addr... | [
"def",
"parse_dbus_address",
"(",
"address",
")",
":",
"if",
"address",
"==",
"'session'",
":",
"address",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'DBUS_SESSION_BUS_ADDRESS'",
")",
"if",
"not",
"address",
":",
"raise",
"ValueError",
"(",
"'$DBUS_SESSION_B... | Parse a D-BUS address string into a list of addresses. | [
"Parse",
"a",
"D",
"-",
"BUS",
"address",
"string",
"into",
"a",
"list",
"of",
"addresses",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/dbus.py#L98-L128 |
geertj/gruvi | lib/gruvi/dbus.py | parse_dbus_header | def parse_dbus_header(header):
"""Parse a D-BUS header. Return the message size."""
if six.indexbytes(header, 0) == ord('l'):
endian = '<'
elif six.indexbytes(header, 0) == ord('B'):
endian = '>'
else:
raise ValueError('illegal endianness')
if not 1 <= six.indexbytes(header, ... | python | def parse_dbus_header(header):
"""Parse a D-BUS header. Return the message size."""
if six.indexbytes(header, 0) == ord('l'):
endian = '<'
elif six.indexbytes(header, 0) == ord('B'):
endian = '>'
else:
raise ValueError('illegal endianness')
if not 1 <= six.indexbytes(header, ... | [
"def",
"parse_dbus_header",
"(",
"header",
")",
":",
"if",
"six",
".",
"indexbytes",
"(",
"header",
",",
"0",
")",
"==",
"ord",
"(",
"'l'",
")",
":",
"endian",
"=",
"'<'",
"elif",
"six",
".",
"indexbytes",
"(",
"header",
",",
"0",
")",
"==",
"ord",... | Parse a D-BUS header. Return the message size. | [
"Parse",
"a",
"D",
"-",
"BUS",
"header",
".",
"Return",
"the",
"message",
"size",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/dbus.py#L188-L203 |
geertj/gruvi | lib/gruvi/dbus.py | TxdbusAuthenticator.getMechanismName | def getMechanismName(self):
"""Return the authentication mechanism name."""
if self._server_side:
mech = self._authenticator.current_mech
return mech.getMechanismName() if mech else None
else:
return getattr(self._authenticator, 'authMech', None) | python | def getMechanismName(self):
"""Return the authentication mechanism name."""
if self._server_side:
mech = self._authenticator.current_mech
return mech.getMechanismName() if mech else None
else:
return getattr(self._authenticator, 'authMech', None) | [
"def",
"getMechanismName",
"(",
"self",
")",
":",
"if",
"self",
".",
"_server_side",
":",
"mech",
"=",
"self",
".",
"_authenticator",
".",
"current_mech",
"return",
"mech",
".",
"getMechanismName",
"(",
")",
"if",
"mech",
"else",
"None",
"else",
":",
"retu... | Return the authentication mechanism name. | [
"Return",
"the",
"authentication",
"mechanism",
"name",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/dbus.py#L168-L174 |
geertj/gruvi | lib/gruvi/dbus.py | TxdbusAuthenticator.getUserName | def getUserName(self):
"""Return the authenticated user name (server side)."""
if not self._server_side:
return
mech = self._authenticator.current_mech
return mech.getUserName() if mech else None | python | def getUserName(self):
"""Return the authenticated user name (server side)."""
if not self._server_side:
return
mech = self._authenticator.current_mech
return mech.getUserName() if mech else None | [
"def",
"getUserName",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_server_side",
":",
"return",
"mech",
"=",
"self",
".",
"_authenticator",
".",
"current_mech",
"return",
"mech",
".",
"getUserName",
"(",
")",
"if",
"mech",
"else",
"None"
] | Return the authenticated user name (server side). | [
"Return",
"the",
"authenticated",
"user",
"name",
"(",
"server",
"side",
")",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/dbus.py#L176-L181 |
geertj/gruvi | lib/gruvi/dbus.py | DbusProtocol.get_unique_name | def get_unique_name(self):
"""Return the unique name of the D-BUS connection."""
self._name_acquired.wait()
if self._error:
raise compat.saved_exc(self._error)
elif self._transport is None:
raise DbusError('not connected')
return self._unique_name | python | def get_unique_name(self):
"""Return the unique name of the D-BUS connection."""
self._name_acquired.wait()
if self._error:
raise compat.saved_exc(self._error)
elif self._transport is None:
raise DbusError('not connected')
return self._unique_name | [
"def",
"get_unique_name",
"(",
"self",
")",
":",
"self",
".",
"_name_acquired",
".",
"wait",
"(",
")",
"if",
"self",
".",
"_error",
":",
"raise",
"compat",
".",
"saved_exc",
"(",
"self",
".",
"_error",
")",
"elif",
"self",
".",
"_transport",
"is",
"Non... | Return the unique name of the D-BUS connection. | [
"Return",
"the",
"unique",
"name",
"of",
"the",
"D",
"-",
"BUS",
"connection",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/dbus.py#L409-L416 |
geertj/gruvi | lib/gruvi/dbus.py | DbusProtocol.send_message | def send_message(self, message):
"""Send a D-BUS message.
The *message* argument must be ``gruvi.txdbus.DbusMessage`` instance.
"""
if not isinstance(message, txdbus.DbusMessage):
raise TypeError('message: expecting DbusMessage instance (got {!r})',
... | python | def send_message(self, message):
"""Send a D-BUS message.
The *message* argument must be ``gruvi.txdbus.DbusMessage`` instance.
"""
if not isinstance(message, txdbus.DbusMessage):
raise TypeError('message: expecting DbusMessage instance (got {!r})',
... | [
"def",
"send_message",
"(",
"self",
",",
"message",
")",
":",
"if",
"not",
"isinstance",
"(",
"message",
",",
"txdbus",
".",
"DbusMessage",
")",
":",
"raise",
"TypeError",
"(",
"'message: expecting DbusMessage instance (got {!r})'",
",",
"type",
"(",
"message",
... | Send a D-BUS message.
The *message* argument must be ``gruvi.txdbus.DbusMessage`` instance. | [
"Send",
"a",
"D",
"-",
"BUS",
"message",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/dbus.py#L419-L432 |
geertj/gruvi | lib/gruvi/dbus.py | DbusProtocol.call_method | def call_method(self, service, path, interface, method, signature=None,
args=None, no_reply=False, auto_start=False, timeout=-1):
"""Call a D-BUS method and wait for its reply.
This method calls the D-BUS method with name *method* that resides on
the object at bus address *s... | python | def call_method(self, service, path, interface, method, signature=None,
args=None, no_reply=False, auto_start=False, timeout=-1):
"""Call a D-BUS method and wait for its reply.
This method calls the D-BUS method with name *method* that resides on
the object at bus address *s... | [
"def",
"call_method",
"(",
"self",
",",
"service",
",",
"path",
",",
"interface",
",",
"method",
",",
"signature",
"=",
"None",
",",
"args",
"=",
"None",
",",
"no_reply",
"=",
"False",
",",
"auto_start",
"=",
"False",
",",
"timeout",
"=",
"-",
"1",
"... | Call a D-BUS method and wait for its reply.
This method calls the D-BUS method with name *method* that resides on
the object at bus address *service*, at path *path*, on interface
*interface*.
The *signature* and *args* are optional arguments that can be used to
add parameters ... | [
"Call",
"a",
"D",
"-",
"BUS",
"method",
"and",
"wait",
"for",
"its",
"reply",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/dbus.py#L435-L475 |
geertj/gruvi | lib/gruvi/dbus.py | DbusClient.connect | def connect(self, address='session'):
"""Connect to *address* and wait until the connection is established.
The *address* argument must be a D-BUS server address, in the format
described in the D-BUS specification. It may also be one of the special
addresses ``'session'`` or ``'system'`... | python | def connect(self, address='session'):
"""Connect to *address* and wait until the connection is established.
The *address* argument must be a D-BUS server address, in the format
described in the D-BUS specification. It may also be one of the special
addresses ``'session'`` or ``'system'`... | [
"def",
"connect",
"(",
"self",
",",
"address",
"=",
"'session'",
")",
":",
"if",
"isinstance",
"(",
"address",
",",
"six",
".",
"string_types",
")",
":",
"addresses",
"=",
"parse_dbus_address",
"(",
"address",
")",
"else",
":",
"addresses",
"=",
"[",
"ad... | Connect to *address* and wait until the connection is established.
The *address* argument must be a D-BUS server address, in the format
described in the D-BUS specification. It may also be one of the special
addresses ``'session'`` or ``'system'``, to connect to the D-BUS
session and sy... | [
"Connect",
"to",
"*",
"address",
"*",
"and",
"wait",
"until",
"the",
"connection",
"is",
"established",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/dbus.py#L492-L513 |
geertj/gruvi | lib/gruvi/dbus.py | DbusServer.listen | def listen(self, address='session'):
"""Start listening on *address* for new connection.
The *address* argument must be a D-BUS server address, in the format
described in the D-BUS specification. It may also be one of the special
addresses ``'session'`` or ``'system'``, to connect to th... | python | def listen(self, address='session'):
"""Start listening on *address* for new connection.
The *address* argument must be a D-BUS server address, in the format
described in the D-BUS specification. It may also be one of the special
addresses ``'session'`` or ``'system'``, to connect to th... | [
"def",
"listen",
"(",
"self",
",",
"address",
"=",
"'session'",
")",
":",
"if",
"isinstance",
"(",
"address",
",",
"six",
".",
"string_types",
")",
":",
"addresses",
"=",
"parse_dbus_address",
"(",
"address",
")",
"else",
":",
"addresses",
"=",
"[",
"add... | Start listening on *address* for new connection.
The *address* argument must be a D-BUS server address, in the format
described in the D-BUS specification. It may also be one of the special
addresses ``'session'`` or ``'system'``, to connect to the D-BUS
session and system bus, respecti... | [
"Start",
"listening",
"on",
"*",
"address",
"*",
"for",
"new",
"connection",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/dbus.py#L537-L553 |
geertj/gruvi | lib/gruvi/util.py | docfrom | def docfrom(base):
"""Decorator to set a function's docstring from another function."""
def setdoc(func):
func.__doc__ = (getattr(base, '__doc__') or '') + (func.__doc__ or '')
return func
return setdoc | python | def docfrom(base):
"""Decorator to set a function's docstring from another function."""
def setdoc(func):
func.__doc__ = (getattr(base, '__doc__') or '') + (func.__doc__ or '')
return func
return setdoc | [
"def",
"docfrom",
"(",
"base",
")",
":",
"def",
"setdoc",
"(",
"func",
")",
":",
"func",
".",
"__doc__",
"=",
"(",
"getattr",
"(",
"base",
",",
"'__doc__'",
")",
"or",
"''",
")",
"+",
"(",
"func",
".",
"__doc__",
"or",
"''",
")",
"return",
"func"... | Decorator to set a function's docstring from another function. | [
"Decorator",
"to",
"set",
"a",
"function",
"s",
"docstring",
"from",
"another",
"function",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/util.py#L64-L69 |
geertj/gruvi | lib/gruvi/util.py | objref | def objref(obj):
"""Return a string that uniquely and compactly identifies an object."""
ref = _objrefs.get(obj)
if ref is None:
clsname = obj.__class__.__name__.split('.')[-1]
seqno = _lastids.setdefault(clsname, 1)
ref = '{}-{}'.format(clsname, seqno)
_objrefs[obj] = ref
... | python | def objref(obj):
"""Return a string that uniquely and compactly identifies an object."""
ref = _objrefs.get(obj)
if ref is None:
clsname = obj.__class__.__name__.split('.')[-1]
seqno = _lastids.setdefault(clsname, 1)
ref = '{}-{}'.format(clsname, seqno)
_objrefs[obj] = ref
... | [
"def",
"objref",
"(",
"obj",
")",
":",
"ref",
"=",
"_objrefs",
".",
"get",
"(",
"obj",
")",
"if",
"ref",
"is",
"None",
":",
"clsname",
"=",
"obj",
".",
"__class__",
".",
"__name__",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"seqno",
"=... | Return a string that uniquely and compactly identifies an object. | [
"Return",
"a",
"string",
"that",
"uniquely",
"and",
"compactly",
"identifies",
"an",
"object",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/util.py#L75-L84 |
geertj/gruvi | lib/gruvi/util.py | delegate_method | def delegate_method(other, method, name=None):
"""Add a method to the current class that delegates to another method.
The *other* argument must be a property that returns the instance to
delegate to. Due to an implementation detail, the property must be defined
in the current class. The *method* argume... | python | def delegate_method(other, method, name=None):
"""Add a method to the current class that delegates to another method.
The *other* argument must be a property that returns the instance to
delegate to. Due to an implementation detail, the property must be defined
in the current class. The *method* argume... | [
"def",
"delegate_method",
"(",
"other",
",",
"method",
",",
"name",
"=",
"None",
")",
":",
"frame",
"=",
"sys",
".",
"_getframe",
"(",
"1",
")",
"classdict",
"=",
"frame",
".",
"f_locals",
"@",
"functools",
".",
"wraps",
"(",
"method",
")",
"def",
"d... | Add a method to the current class that delegates to another method.
The *other* argument must be a property that returns the instance to
delegate to. Due to an implementation detail, the property must be defined
in the current class. The *method* argument specifies a method to delegate
to. It can be an... | [
"Add",
"a",
"method",
"to",
"the",
"current",
"class",
"that",
"delegates",
"to",
"another",
"method",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/util.py#L94-L143 |
geertj/gruvi | lib/gruvi/http.py | accept_ws | def accept_ws(buf, pos):
"""Skip whitespace at the current buffer position."""
match = re_ws.match(buf, pos)
if not match:
return None, pos
return buf[match.start(0):match.end(0)], match.end(0) | python | def accept_ws(buf, pos):
"""Skip whitespace at the current buffer position."""
match = re_ws.match(buf, pos)
if not match:
return None, pos
return buf[match.start(0):match.end(0)], match.end(0) | [
"def",
"accept_ws",
"(",
"buf",
",",
"pos",
")",
":",
"match",
"=",
"re_ws",
".",
"match",
"(",
"buf",
",",
"pos",
")",
"if",
"not",
"match",
":",
"return",
"None",
",",
"pos",
"return",
"buf",
"[",
"match",
".",
"start",
"(",
"0",
")",
":",
"m... | Skip whitespace at the current buffer position. | [
"Skip",
"whitespace",
"at",
"the",
"current",
"buffer",
"position",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L131-L136 |
geertj/gruvi | lib/gruvi/http.py | accept_lit | def accept_lit(char, buf, pos):
"""Accept a literal character at the current buffer position."""
if pos >= len(buf) or buf[pos] != char:
return None, pos
return char, pos+1 | python | def accept_lit(char, buf, pos):
"""Accept a literal character at the current buffer position."""
if pos >= len(buf) or buf[pos] != char:
return None, pos
return char, pos+1 | [
"def",
"accept_lit",
"(",
"char",
",",
"buf",
",",
"pos",
")",
":",
"if",
"pos",
">=",
"len",
"(",
"buf",
")",
"or",
"buf",
"[",
"pos",
"]",
"!=",
"char",
":",
"return",
"None",
",",
"pos",
"return",
"char",
",",
"pos",
"+",
"1"
] | Accept a literal character at the current buffer position. | [
"Accept",
"a",
"literal",
"character",
"at",
"the",
"current",
"buffer",
"position",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L138-L142 |
geertj/gruvi | lib/gruvi/http.py | expect_lit | def expect_lit(char, buf, pos):
"""Expect a literal character at the current buffer position."""
if pos >= len(buf) or buf[pos] != char:
return None, len(buf)
return char, pos+1 | python | def expect_lit(char, buf, pos):
"""Expect a literal character at the current buffer position."""
if pos >= len(buf) or buf[pos] != char:
return None, len(buf)
return char, pos+1 | [
"def",
"expect_lit",
"(",
"char",
",",
"buf",
",",
"pos",
")",
":",
"if",
"pos",
">=",
"len",
"(",
"buf",
")",
"or",
"buf",
"[",
"pos",
"]",
"!=",
"char",
":",
"return",
"None",
",",
"len",
"(",
"buf",
")",
"return",
"char",
",",
"pos",
"+",
... | Expect a literal character at the current buffer position. | [
"Expect",
"a",
"literal",
"character",
"at",
"the",
"current",
"buffer",
"position",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L144-L148 |
geertj/gruvi | lib/gruvi/http.py | accept_re | def accept_re(regexp, buf, pos):
"""Accept a regular expression at the current buffer position."""
match = regexp.match(buf, pos)
if not match:
return None, pos
return buf[match.start(1):match.end(1)], match.end(0) | python | def accept_re(regexp, buf, pos):
"""Accept a regular expression at the current buffer position."""
match = regexp.match(buf, pos)
if not match:
return None, pos
return buf[match.start(1):match.end(1)], match.end(0) | [
"def",
"accept_re",
"(",
"regexp",
",",
"buf",
",",
"pos",
")",
":",
"match",
"=",
"regexp",
".",
"match",
"(",
"buf",
",",
"pos",
")",
"if",
"not",
"match",
":",
"return",
"None",
",",
"pos",
"return",
"buf",
"[",
"match",
".",
"start",
"(",
"1"... | Accept a regular expression at the current buffer position. | [
"Accept",
"a",
"regular",
"expression",
"at",
"the",
"current",
"buffer",
"position",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L150-L155 |
geertj/gruvi | lib/gruvi/http.py | expect_re | def expect_re(regexp, buf, pos):
"""Require a regular expression at the current buffer position."""
match = regexp.match(buf, pos)
if not match:
return None, len(buf)
return buf[match.start(1):match.end(1)], match.end(0) | python | def expect_re(regexp, buf, pos):
"""Require a regular expression at the current buffer position."""
match = regexp.match(buf, pos)
if not match:
return None, len(buf)
return buf[match.start(1):match.end(1)], match.end(0) | [
"def",
"expect_re",
"(",
"regexp",
",",
"buf",
",",
"pos",
")",
":",
"match",
"=",
"regexp",
".",
"match",
"(",
"buf",
",",
"pos",
")",
"if",
"not",
"match",
":",
"return",
"None",
",",
"len",
"(",
"buf",
")",
"return",
"buf",
"[",
"match",
".",
... | Require a regular expression at the current buffer position. | [
"Require",
"a",
"regular",
"expression",
"at",
"the",
"current",
"buffer",
"position",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L157-L162 |
geertj/gruvi | lib/gruvi/http.py | parse_content_type | def parse_content_type(header):
"""Parse the "Content-Type" header."""
typ = subtyp = None; options = {}
typ, pos = expect_re(re_token, header, 0)
_, pos = expect_lit('/', header, pos)
subtyp, pos = expect_re(re_token, header, pos)
ctype = header[:pos] if subtyp else ''
while pos < len(heade... | python | def parse_content_type(header):
"""Parse the "Content-Type" header."""
typ = subtyp = None; options = {}
typ, pos = expect_re(re_token, header, 0)
_, pos = expect_lit('/', header, pos)
subtyp, pos = expect_re(re_token, header, pos)
ctype = header[:pos] if subtyp else ''
while pos < len(heade... | [
"def",
"parse_content_type",
"(",
"header",
")",
":",
"typ",
"=",
"subtyp",
"=",
"None",
"options",
"=",
"{",
"}",
"typ",
",",
"pos",
"=",
"expect_re",
"(",
"re_token",
",",
"header",
",",
"0",
")",
"_",
",",
"pos",
"=",
"expect_lit",
"(",
"'/'",
"... | Parse the "Content-Type" header. | [
"Parse",
"the",
"Content",
"-",
"Type",
"header",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L165-L186 |
geertj/gruvi | lib/gruvi/http.py | parse_te | def parse_te(header):
"""Parse the "TE" header."""
pos = 0
names = []
while pos < len(header):
name, pos = expect_re(re_token, header, pos)
_, pos = accept_ws(header, pos)
_, pos = accept_lit(';', header, pos)
_, pos = accept_ws(header, pos)
qvalue, pos = accept_r... | python | def parse_te(header):
"""Parse the "TE" header."""
pos = 0
names = []
while pos < len(header):
name, pos = expect_re(re_token, header, pos)
_, pos = accept_ws(header, pos)
_, pos = accept_lit(';', header, pos)
_, pos = accept_ws(header, pos)
qvalue, pos = accept_r... | [
"def",
"parse_te",
"(",
"header",
")",
":",
"pos",
"=",
"0",
"names",
"=",
"[",
"]",
"while",
"pos",
"<",
"len",
"(",
"header",
")",
":",
"name",
",",
"pos",
"=",
"expect_re",
"(",
"re_token",
",",
"header",
",",
"pos",
")",
"_",
",",
"pos",
"=... | Parse the "TE" header. | [
"Parse",
"the",
"TE",
"header",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L188-L203 |
geertj/gruvi | lib/gruvi/http.py | parse_trailer | def parse_trailer(header):
"""Parse the "Trailer" header."""
pos = 0
names = []
while pos < len(header):
name, pos = expect_re(re_token, header, pos)
if name:
names.append(name)
_, pos = accept_ws(header, pos)
_, pos = expect_lit(',', header, pos)
_, p... | python | def parse_trailer(header):
"""Parse the "Trailer" header."""
pos = 0
names = []
while pos < len(header):
name, pos = expect_re(re_token, header, pos)
if name:
names.append(name)
_, pos = accept_ws(header, pos)
_, pos = expect_lit(',', header, pos)
_, p... | [
"def",
"parse_trailer",
"(",
"header",
")",
":",
"pos",
"=",
"0",
"names",
"=",
"[",
"]",
"while",
"pos",
"<",
"len",
"(",
"header",
")",
":",
"name",
",",
"pos",
"=",
"expect_re",
"(",
"re_token",
",",
"header",
",",
"pos",
")",
"if",
"name",
":... | Parse the "Trailer" header. | [
"Parse",
"the",
"Trailer",
"header",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L205-L216 |
geertj/gruvi | lib/gruvi/http.py | rfc1123_date | def rfc1123_date(timestamp=None):
"""Create a RFC1123 style Date header for *timestamp*."""
if timestamp is None:
timestamp = time.time()
timestamp = int(timestamp)
global _cached_timestamp, _cached_datestring
if timestamp != _cached_timestamp:
# The time stamp must be GMT, and canno... | python | def rfc1123_date(timestamp=None):
"""Create a RFC1123 style Date header for *timestamp*."""
if timestamp is None:
timestamp = time.time()
timestamp = int(timestamp)
global _cached_timestamp, _cached_datestring
if timestamp != _cached_timestamp:
# The time stamp must be GMT, and canno... | [
"def",
"rfc1123_date",
"(",
"timestamp",
"=",
"None",
")",
":",
"if",
"timestamp",
"is",
"None",
":",
"timestamp",
"=",
"time",
".",
"time",
"(",
")",
"timestamp",
"=",
"int",
"(",
"timestamp",
")",
"global",
"_cached_timestamp",
",",
"_cached_datestring",
... | Create a RFC1123 style Date header for *timestamp*. | [
"Create",
"a",
"RFC1123",
"style",
"Date",
"header",
"for",
"*",
"timestamp",
"*",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L227-L240 |
geertj/gruvi | lib/gruvi/http.py | parse_url | def parse_url(url, default_scheme='http', is_connect=False):
"""Parse an URL and return its components.
The *default_scheme* argument specifies the scheme in case URL is
an otherwise valid absolute URL but with a missing scheme.
The *is_connect* argument must be set to ``True`` if the URL was requeste... | python | def parse_url(url, default_scheme='http', is_connect=False):
"""Parse an URL and return its components.
The *default_scheme* argument specifies the scheme in case URL is
an otherwise valid absolute URL but with a missing scheme.
The *is_connect* argument must be set to ``True`` if the URL was requeste... | [
"def",
"parse_url",
"(",
"url",
",",
"default_scheme",
"=",
"'http'",
",",
"is_connect",
"=",
"False",
")",
":",
"# If this is not in origin-form, authority-form or asterisk-form and no",
"# scheme is present, assume it's in absolute-form with a missing scheme.",
"# See RFC7230 secti... | Parse an URL and return its components.
The *default_scheme* argument specifies the scheme in case URL is
an otherwise valid absolute URL but with a missing scheme.
The *is_connect* argument must be set to ``True`` if the URL was requested
with the HTTP CONNECT method. These URLs have a different form... | [
"Parse",
"an",
"URL",
"and",
"return",
"its",
"components",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L303-L327 |
geertj/gruvi | lib/gruvi/http.py | get_header | def get_header(headers, name, default=None):
"""Return the value of header *name*.
The *headers* argument must be a list of ``(name, value)`` tuples. If the
header is found its associated value is returned, otherwise *default* is
returned. Header names are matched case insensitively.
"""
name =... | python | def get_header(headers, name, default=None):
"""Return the value of header *name*.
The *headers* argument must be a list of ``(name, value)`` tuples. If the
header is found its associated value is returned, otherwise *default* is
returned. Header names are matched case insensitively.
"""
name =... | [
"def",
"get_header",
"(",
"headers",
",",
"name",
",",
"default",
"=",
"None",
")",
":",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"for",
"header",
"in",
"headers",
":",
"if",
"header",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"==",
"name",
":",... | Return the value of header *name*.
The *headers* argument must be a list of ``(name, value)`` tuples. If the
header is found its associated value is returned, otherwise *default* is
returned. Header names are matched case insensitively. | [
"Return",
"the",
"value",
"of",
"header",
"*",
"name",
"*",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L350-L361 |
geertj/gruvi | lib/gruvi/http.py | remove_headers | def remove_headers(headers, name):
"""Remove all headers with name *name*.
The list is modified in-place and the updated list is returned.
"""
i = 0
name = name.lower()
for j in range(len(headers)):
if headers[j][0].lower() != name:
if i != j:
headers[i] = he... | python | def remove_headers(headers, name):
"""Remove all headers with name *name*.
The list is modified in-place and the updated list is returned.
"""
i = 0
name = name.lower()
for j in range(len(headers)):
if headers[j][0].lower() != name:
if i != j:
headers[i] = he... | [
"def",
"remove_headers",
"(",
"headers",
",",
"name",
")",
":",
"i",
"=",
"0",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"for",
"j",
"in",
"range",
"(",
"len",
"(",
"headers",
")",
")",
":",
"if",
"headers",
"[",
"j",
"]",
"[",
"0",
"]",
"... | Remove all headers with name *name*.
The list is modified in-place and the updated list is returned. | [
"Remove",
"all",
"headers",
"with",
"name",
"*",
"name",
"*",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L363-L376 |
geertj/gruvi | lib/gruvi/http.py | create_chunk | def create_chunk(buf):
"""Create a chunk for the HTTP "chunked" transfer encoding."""
chunk = []
chunk.append(s2b('{:X}\r\n'.format(len(buf))))
chunk.append(buf)
chunk.append(b'\r\n')
return b''.join(chunk) | python | def create_chunk(buf):
"""Create a chunk for the HTTP "chunked" transfer encoding."""
chunk = []
chunk.append(s2b('{:X}\r\n'.format(len(buf))))
chunk.append(buf)
chunk.append(b'\r\n')
return b''.join(chunk) | [
"def",
"create_chunk",
"(",
"buf",
")",
":",
"chunk",
"=",
"[",
"]",
"chunk",
".",
"append",
"(",
"s2b",
"(",
"'{:X}\\r\\n'",
".",
"format",
"(",
"len",
"(",
"buf",
")",
")",
")",
")",
"chunk",
".",
"append",
"(",
"buf",
")",
"chunk",
".",
"appen... | Create a chunk for the HTTP "chunked" transfer encoding. | [
"Create",
"a",
"chunk",
"for",
"the",
"HTTP",
"chunked",
"transfer",
"encoding",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L379-L385 |
geertj/gruvi | lib/gruvi/http.py | create_chunked_body_end | def create_chunked_body_end(trailers=None):
"""Create the ending that terminates a chunked body."""
chunk = []
chunk.append('0\r\n')
if trailers:
for name, value in trailers:
chunk.append(name)
chunk.append(': ')
chunk.append(value)
chunk.append('\... | python | def create_chunked_body_end(trailers=None):
"""Create the ending that terminates a chunked body."""
chunk = []
chunk.append('0\r\n')
if trailers:
for name, value in trailers:
chunk.append(name)
chunk.append(': ')
chunk.append(value)
chunk.append('\... | [
"def",
"create_chunked_body_end",
"(",
"trailers",
"=",
"None",
")",
":",
"chunk",
"=",
"[",
"]",
"chunk",
".",
"append",
"(",
"'0\\r\\n'",
")",
"if",
"trailers",
":",
"for",
"name",
",",
"value",
"in",
"trailers",
":",
"chunk",
".",
"append",
"(",
"na... | Create the ending that terminates a chunked body. | [
"Create",
"the",
"ending",
"that",
"terminates",
"a",
"chunked",
"body",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L388-L399 |
geertj/gruvi | lib/gruvi/http.py | create_request | def create_request(version, method, url, headers):
"""Create a HTTP request header."""
# According to my measurements using b''.join is faster that constructing a
# bytearray.
message = []
message.append('{} {} HTTP/{}\r\n'.format(method, url, version))
for name, value in headers:
messag... | python | def create_request(version, method, url, headers):
"""Create a HTTP request header."""
# According to my measurements using b''.join is faster that constructing a
# bytearray.
message = []
message.append('{} {} HTTP/{}\r\n'.format(method, url, version))
for name, value in headers:
messag... | [
"def",
"create_request",
"(",
"version",
",",
"method",
",",
"url",
",",
"headers",
")",
":",
"# According to my measurements using b''.join is faster that constructing a",
"# bytearray.",
"message",
"=",
"[",
"]",
"message",
".",
"append",
"(",
"'{} {} HTTP/{}\\r\\n'",
... | Create a HTTP request header. | [
"Create",
"a",
"HTTP",
"request",
"header",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L402-L414 |
geertj/gruvi | lib/gruvi/http.py | create_response | def create_response(version, status, headers):
"""Create a HTTP response header."""
message = []
message.append('HTTP/{} {}\r\n'.format(version, status))
for name, value in headers:
message.append(name)
message.append(': ')
message.append(value)
message.append('\r\n')
... | python | def create_response(version, status, headers):
"""Create a HTTP response header."""
message = []
message.append('HTTP/{} {}\r\n'.format(version, status))
for name, value in headers:
message.append(name)
message.append(': ')
message.append(value)
message.append('\r\n')
... | [
"def",
"create_response",
"(",
"version",
",",
"status",
",",
"headers",
")",
":",
"message",
"=",
"[",
"]",
"message",
".",
"append",
"(",
"'HTTP/{} {}\\r\\n'",
".",
"format",
"(",
"version",
",",
"status",
")",
")",
"for",
"name",
",",
"value",
"in",
... | Create a HTTP response header. | [
"Create",
"a",
"HTTP",
"response",
"header",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L417-L427 |
geertj/gruvi | lib/gruvi/http.py | ParsedUrl.addr | def addr(self):
"""Address tuple that can be used with :func:`~gruvi.create_connection`."""
port = self.port
if port:
port = int(port)
else:
port = default_ports.get(self.scheme or 'http')
return (self.host, port) | python | def addr(self):
"""Address tuple that can be used with :func:`~gruvi.create_connection`."""
port = self.port
if port:
port = int(port)
else:
port = default_ports.get(self.scheme or 'http')
return (self.host, port) | [
"def",
"addr",
"(",
"self",
")",
":",
"port",
"=",
"self",
".",
"port",
"if",
"port",
":",
"port",
"=",
"int",
"(",
"port",
")",
"else",
":",
"port",
"=",
"default_ports",
".",
"get",
"(",
"self",
".",
"scheme",
"or",
"'http'",
")",
"return",
"("... | Address tuple that can be used with :func:`~gruvi.create_connection`. | [
"Address",
"tuple",
"that",
"can",
"be",
"used",
"with",
":",
"func",
":",
"~gruvi",
".",
"create_connection",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L277-L284 |
geertj/gruvi | lib/gruvi/http.py | ParsedUrl.target | def target(self):
"""The "target" i.e. local part of the URL, consisting of the path and query."""
target = self.path or '/'
if self.query:
target = '{}?{}'.format(target, self.query)
return target | python | def target(self):
"""The "target" i.e. local part of the URL, consisting of the path and query."""
target = self.path or '/'
if self.query:
target = '{}?{}'.format(target, self.query)
return target | [
"def",
"target",
"(",
"self",
")",
":",
"target",
"=",
"self",
".",
"path",
"or",
"'/'",
"if",
"self",
".",
"query",
":",
"target",
"=",
"'{}?{}'",
".",
"format",
"(",
"target",
",",
"self",
".",
"query",
")",
"return",
"target"
] | The "target" i.e. local part of the URL, consisting of the path and query. | [
"The",
"target",
"i",
".",
"e",
".",
"local",
"part",
"of",
"the",
"URL",
"consisting",
"of",
"the",
"path",
"and",
"query",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L292-L297 |
geertj/gruvi | lib/gruvi/http.py | HttpRequest.start_request | def start_request(self, method, url, headers=None, bodylen=None):
"""Start a new HTTP request.
The optional *headers* argument contains the headers to send. It must
be a sequence of ``(name, value)`` tuples.
The optional *bodylen* parameter is a hint that specifies the length of
... | python | def start_request(self, method, url, headers=None, bodylen=None):
"""Start a new HTTP request.
The optional *headers* argument contains the headers to send. It must
be a sequence of ``(name, value)`` tuples.
The optional *bodylen* parameter is a hint that specifies the length of
... | [
"def",
"start_request",
"(",
"self",
",",
"method",
",",
"url",
",",
"headers",
"=",
"None",
",",
"bodylen",
"=",
"None",
")",
":",
"self",
".",
"_headers",
"=",
"headers",
"or",
"[",
"]",
"agent",
"=",
"host",
"=",
"clen",
"=",
"trailer",
"=",
"No... | Start a new HTTP request.
The optional *headers* argument contains the headers to send. It must
be a sequence of ``(name, value)`` tuples.
The optional *bodylen* parameter is a hint that specifies the length of
the body that will follow. A length of -1 indicates no body, 0 means an
... | [
"Start",
"a",
"new",
"HTTP",
"request",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L513-L581 |
geertj/gruvi | lib/gruvi/http.py | HttpRequest.write | def write(self, buf):
"""Write *buf* to the request body."""
if not isinstance(buf, six.binary_type):
raise TypeError('buf: must be a bytes instance')
# Be careful not to write zero-length chunks as they indicate the end of a body.
if len(buf) == 0:
return
... | python | def write(self, buf):
"""Write *buf* to the request body."""
if not isinstance(buf, six.binary_type):
raise TypeError('buf: must be a bytes instance')
# Be careful not to write zero-length chunks as they indicate the end of a body.
if len(buf) == 0:
return
... | [
"def",
"write",
"(",
"self",
",",
"buf",
")",
":",
"if",
"not",
"isinstance",
"(",
"buf",
",",
"six",
".",
"binary_type",
")",
":",
"raise",
"TypeError",
"(",
"'buf: must be a bytes instance'",
")",
"# Be careful not to write zero-length chunks as they indicate the en... | Write *buf* to the request body. | [
"Write",
"*",
"buf",
"*",
"to",
"the",
"request",
"body",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L584-L597 |
geertj/gruvi | lib/gruvi/http.py | HttpRequest.end_request | def end_request(self):
"""End the request body."""
if not self._chunked:
return
trailers = [(n, get_header(self._headers, n)) for n in self._trailer] \
if self._trailer else None
ending = create_chunked_body_end(trailers)
self._protocol.writer.... | python | def end_request(self):
"""End the request body."""
if not self._chunked:
return
trailers = [(n, get_header(self._headers, n)) for n in self._trailer] \
if self._trailer else None
ending = create_chunked_body_end(trailers)
self._protocol.writer.... | [
"def",
"end_request",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_chunked",
":",
"return",
"trailers",
"=",
"[",
"(",
"n",
",",
"get_header",
"(",
"self",
".",
"_headers",
",",
"n",
")",
")",
"for",
"n",
"in",
"self",
".",
"_trailer",
"]",
... | End the request body. | [
"End",
"the",
"request",
"body",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L600-L607 |
geertj/gruvi | lib/gruvi/http.py | HttpProtocol.request | def request(self, method, url, headers=None, body=None):
"""Make a new HTTP request.
The *method* argument is the HTTP method as a string, for example
``'GET'`` or ``'POST'``. The *url* argument specifies the URL.
The optional *headers* argument specifies extra HTTP headers to use in
... | python | def request(self, method, url, headers=None, body=None):
"""Make a new HTTP request.
The *method* argument is the HTTP method as a string, for example
``'GET'`` or ``'POST'``. The *url* argument specifies the URL.
The optional *headers* argument specifies extra HTTP headers to use in
... | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"url",
",",
"headers",
"=",
"None",
",",
"body",
"=",
"None",
")",
":",
"if",
"self",
".",
"_error",
":",
"raise",
"compat",
".",
"saved_exc",
"(",
"self",
".",
"_error",
")",
"elif",
"self",
".",
... | Make a new HTTP request.
The *method* argument is the HTTP method as a string, for example
``'GET'`` or ``'POST'``. The *url* argument specifies the URL.
The optional *headers* argument specifies extra HTTP headers to use in
the request. It must be a sequence of ``(name, value)`` tuple... | [
"Make",
"a",
"new",
"HTTP",
"request",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L1093-L1138 |
geertj/gruvi | lib/gruvi/http.py | HttpProtocol.getresponse | def getresponse(self):
"""Wait for and return a HTTP response.
The return value will be a :class:`HttpMessage`. When this method
returns only the response header has been read. The response body can
be read using :meth:`~gruvi.Stream.read` and similar methods on
the message :att... | python | def getresponse(self):
"""Wait for and return a HTTP response.
The return value will be a :class:`HttpMessage`. When this method
returns only the response header has been read. The response body can
be read using :meth:`~gruvi.Stream.read` and similar methods on
the message :att... | [
"def",
"getresponse",
"(",
"self",
")",
":",
"if",
"self",
".",
"_error",
":",
"raise",
"compat",
".",
"saved_exc",
"(",
"self",
".",
"_error",
")",
"elif",
"self",
".",
"_transport",
"is",
"None",
":",
"raise",
"HttpError",
"(",
"'not connected'",
")",
... | Wait for and return a HTTP response.
The return value will be a :class:`HttpMessage`. When this method
returns only the response header has been read. The response body can
be read using :meth:`~gruvi.Stream.read` and similar methods on
the message :attr:`~HttpMessage.body`.
No... | [
"Wait",
"for",
"and",
"return",
"a",
"HTTP",
"response",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L1141-L1160 |
unique1o1/Meta-Music | Metamusic/decoder.py | unique_hash | def unique_hash(filepath: str, blocksize: int=80)->str:
""" Small function to generate a hash to uniquely generate a file.
Default blocksize is `500`
"""
s = sha1()
with open(filepath, "rb") as f:
buf = f.read(blocksize)
s.update(buf)
return s.hexdigest() | python | def unique_hash(filepath: str, blocksize: int=80)->str:
""" Small function to generate a hash to uniquely generate a file.
Default blocksize is `500`
"""
s = sha1()
with open(filepath, "rb") as f:
buf = f.read(blocksize)
s.update(buf)
return s.hexdigest() | [
"def",
"unique_hash",
"(",
"filepath",
":",
"str",
",",
"blocksize",
":",
"int",
"=",
"80",
")",
"->",
"str",
":",
"s",
"=",
"sha1",
"(",
")",
"with",
"open",
"(",
"filepath",
",",
"\"rb\"",
")",
"as",
"f",
":",
"buf",
"=",
"f",
".",
"read",
"(... | Small function to generate a hash to uniquely generate a file.
Default blocksize is `500` | [
"Small",
"function",
"to",
"generate",
"a",
"hash",
"to",
"uniquely",
"generate",
"a",
"file",
".",
"Default",
"blocksize",
"is",
"500"
] | train | https://github.com/unique1o1/Meta-Music/blob/8cd1b04011ae3671ece44cc6338d748f8d095eaf/Metamusic/decoder.py#L8-L16 |
unique1o1/Meta-Music | Metamusic/decoder.py | read | def read(filename: str, limit: Optional[int]=None) -> Tuple[list, int]:
"""
Reads any file supported by pydub (ffmpeg) and returns the data contained
within.
returns: (channels, samplerate)
"""
audiofile = AudioSegment.from_file(filename)
if limit:
audiofile = audiofile[:limit * 10... | python | def read(filename: str, limit: Optional[int]=None) -> Tuple[list, int]:
"""
Reads any file supported by pydub (ffmpeg) and returns the data contained
within.
returns: (channels, samplerate)
"""
audiofile = AudioSegment.from_file(filename)
if limit:
audiofile = audiofile[:limit * 10... | [
"def",
"read",
"(",
"filename",
":",
"str",
",",
"limit",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
")",
"->",
"Tuple",
"[",
"list",
",",
"int",
"]",
":",
"audiofile",
"=",
"AudioSegment",
".",
"from_file",
"(",
"filename",
")",
"if",
"limit",
... | Reads any file supported by pydub (ffmpeg) and returns the data contained
within.
returns: (channels, samplerate) | [
"Reads",
"any",
"file",
"supported",
"by",
"pydub",
"(",
"ffmpeg",
")",
"and",
"returns",
"the",
"data",
"contained",
"within",
".",
"returns",
":",
"(",
"channels",
"samplerate",
")"
] | train | https://github.com/unique1o1/Meta-Music/blob/8cd1b04011ae3671ece44cc6338d748f8d095eaf/Metamusic/decoder.py#L19-L39 |
unique1o1/Meta-Music | Metamusic/decoder.py | path_to_songname | def path_to_songname(path: str)->str:
"""
Extracts song name from a filepath. Used to identify which songs
have already been fingerprinted on disk.
"""
return os.path.splitext(os.path.basename(path))[0] | python | def path_to_songname(path: str)->str:
"""
Extracts song name from a filepath. Used to identify which songs
have already been fingerprinted on disk.
"""
return os.path.splitext(os.path.basename(path))[0] | [
"def",
"path_to_songname",
"(",
"path",
":",
"str",
")",
"->",
"str",
":",
"return",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
")",
"[",
"0",
"]"
] | Extracts song name from a filepath. Used to identify which songs
have already been fingerprinted on disk. | [
"Extracts",
"song",
"name",
"from",
"a",
"filepath",
".",
"Used",
"to",
"identify",
"which",
"songs",
"have",
"already",
"been",
"fingerprinted",
"on",
"disk",
"."
] | train | https://github.com/unique1o1/Meta-Music/blob/8cd1b04011ae3671ece44cc6338d748f8d095eaf/Metamusic/decoder.py#L42-L47 |
geertj/gruvi | lib/gruvi/endpoints.py | create_connection | def create_connection(protocol_factory, address, ssl=False, server_hostname=None,
local_address=None, family=0, flags=0, ipc=False, timeout=None,
mode='rw'):
"""Create a new client connection.
This method creates a new :class:`pyuv.Handle`, connects it to *address*,
... | python | def create_connection(protocol_factory, address, ssl=False, server_hostname=None,
local_address=None, family=0, flags=0, ipc=False, timeout=None,
mode='rw'):
"""Create a new client connection.
This method creates a new :class:`pyuv.Handle`, connects it to *address*,
... | [
"def",
"create_connection",
"(",
"protocol_factory",
",",
"address",
",",
"ssl",
"=",
"False",
",",
"server_hostname",
"=",
"None",
",",
"local_address",
"=",
"None",
",",
"family",
"=",
"0",
",",
"flags",
"=",
"0",
",",
"ipc",
"=",
"False",
",",
"timeou... | Create a new client connection.
This method creates a new :class:`pyuv.Handle`, connects it to *address*,
and then waits for the connection to be established. When the connection is
established, the handle is wrapped in a transport, and a new protocol
instance is created by calling *protocol_factory*. ... | [
"Create",
"a",
"new",
"client",
"connection",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/endpoints.py#L33-L158 |
geertj/gruvi | lib/gruvi/endpoints.py | create_server | def create_server(protocol_factory, address=None, ssl=False, family=0, flags=0,
ipc=False, backlog=128):
"""
Create a new network server.
This creates one or more :class:`pyuv.Handle` instances bound to *address*,
puts them in listen mode and starts accepting new connections. For each... | python | def create_server(protocol_factory, address=None, ssl=False, family=0, flags=0,
ipc=False, backlog=128):
"""
Create a new network server.
This creates one or more :class:`pyuv.Handle` instances bound to *address*,
puts them in listen mode and starts accepting new connections. For each... | [
"def",
"create_server",
"(",
"protocol_factory",
",",
"address",
"=",
"None",
",",
"ssl",
"=",
"False",
",",
"family",
"=",
"0",
",",
"flags",
"=",
"0",
",",
"ipc",
"=",
"False",
",",
"backlog",
"=",
"128",
")",
":",
"server",
"=",
"Server",
"(",
"... | Create a new network server.
This creates one or more :class:`pyuv.Handle` instances bound to *address*,
puts them in listen mode and starts accepting new connections. For each
accepted connection, a new transport is created which is connected to a new
protocol instance obtained by calling *protocol_fa... | [
"Create",
"a",
"new",
"network",
"server",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/endpoints.py#L162-L203 |
geertj/gruvi | lib/gruvi/endpoints.py | Client.connect | def connect(self, address, **kwargs):
"""Connect to *address* and wait for the connection to be established.
See :func:`~gruvi.create_connection` for a description of *address*
and the supported keyword arguments.
"""
if self._transport:
raise RuntimeError('already c... | python | def connect(self, address, **kwargs):
"""Connect to *address* and wait for the connection to be established.
See :func:`~gruvi.create_connection` for a description of *address*
and the supported keyword arguments.
"""
if self._transport:
raise RuntimeError('already c... | [
"def",
"connect",
"(",
"self",
",",
"address",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_transport",
":",
"raise",
"RuntimeError",
"(",
"'already connected'",
")",
"kwargs",
".",
"setdefault",
"(",
"'timeout'",
",",
"self",
".",
"_timeout",
... | Connect to *address* and wait for the connection to be established.
See :func:`~gruvi.create_connection` for a description of *address*
and the supported keyword arguments. | [
"Connect",
"to",
"*",
"address",
"*",
"and",
"wait",
"for",
"the",
"connection",
"to",
"be",
"established",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/endpoints.py#L250-L263 |
geertj/gruvi | lib/gruvi/endpoints.py | Client.close | def close(self):
"""Close the connection."""
if self._transport is None:
return
self._transport.close()
self._transport._closed.wait()
self._transport = None
self._protocol = None | python | def close(self):
"""Close the connection."""
if self._transport is None:
return
self._transport.close()
self._transport._closed.wait()
self._transport = None
self._protocol = None | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_transport",
"is",
"None",
":",
"return",
"self",
".",
"_transport",
".",
"close",
"(",
")",
"self",
".",
"_transport",
".",
"_closed",
".",
"wait",
"(",
")",
"self",
".",
"_transport",
"=",
... | Close the connection. | [
"Close",
"the",
"connection",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/endpoints.py#L266-L273 |
geertj/gruvi | lib/gruvi/endpoints.py | Server.handle_connection | def handle_connection(self, client, ssl):
"""Handle a new connection with handle *client*.
This method exists so that it can be overridden in subclass. It is not
intended to be called directly.
"""
if ssl:
context = ssl if hasattr(ssl, 'set_ciphers') \
... | python | def handle_connection(self, client, ssl):
"""Handle a new connection with handle *client*.
This method exists so that it can be overridden in subclass. It is not
intended to be called directly.
"""
if ssl:
context = ssl if hasattr(ssl, 'set_ciphers') \
... | [
"def",
"handle_connection",
"(",
"self",
",",
"client",
",",
"ssl",
")",
":",
"if",
"ssl",
":",
"context",
"=",
"ssl",
"if",
"hasattr",
"(",
"ssl",
",",
"'set_ciphers'",
")",
"else",
"ssl",
"(",
"client",
")",
"if",
"callable",
"(",
"ssl",
")",
"else... | Handle a new connection with handle *client*.
This method exists so that it can be overridden in subclass. It is not
intended to be called directly. | [
"Handle",
"a",
"new",
"connection",
"with",
"handle",
"*",
"client",
"*",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/endpoints.py#L331-L355 |
geertj/gruvi | lib/gruvi/endpoints.py | Server.listen | def listen(self, address, ssl=False, family=0, flags=0, ipc=False, backlog=128):
"""Create a new transport, bind it to *address*, and start listening
for new connections.
See :func:`create_server` for a description of *address* and the
supported keyword arguments.
"""
ha... | python | def listen(self, address, ssl=False, family=0, flags=0, ipc=False, backlog=128):
"""Create a new transport, bind it to *address*, and start listening
for new connections.
See :func:`create_server` for a description of *address* and the
supported keyword arguments.
"""
ha... | [
"def",
"listen",
"(",
"self",
",",
"address",
",",
"ssl",
"=",
"False",
",",
"family",
"=",
"0",
",",
"flags",
"=",
"0",
",",
"ipc",
"=",
"False",
",",
"backlog",
"=",
"128",
")",
":",
"handles",
"=",
"[",
"]",
"handle_args",
"=",
"(",
")",
"if... | Create a new transport, bind it to *address*, and start listening
for new connections.
See :func:`create_server` for a description of *address* and the
supported keyword arguments. | [
"Create",
"a",
"new",
"transport",
"bind",
"it",
"to",
"*",
"address",
"*",
"and",
"start",
"listening",
"for",
"new",
"connections",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/endpoints.py#L371-L414 |
geertj/gruvi | lib/gruvi/endpoints.py | Server.close | def close(self):
"""Close the listening sockets and all accepted connections."""
for handle in self._handles:
if not handle.closed:
handle.close()
del self._handles[:]
for transport, _ in self.connections:
transport.close()
self._all_closed... | python | def close(self):
"""Close the listening sockets and all accepted connections."""
for handle in self._handles:
if not handle.closed:
handle.close()
del self._handles[:]
for transport, _ in self.connections:
transport.close()
self._all_closed... | [
"def",
"close",
"(",
"self",
")",
":",
"for",
"handle",
"in",
"self",
".",
"_handles",
":",
"if",
"not",
"handle",
".",
"closed",
":",
"handle",
".",
"close",
"(",
")",
"del",
"self",
".",
"_handles",
"[",
":",
"]",
"for",
"transport",
",",
"_",
... | Close the listening sockets and all accepted connections. | [
"Close",
"the",
"listening",
"sockets",
"and",
"all",
"accepted",
"connections",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/endpoints.py#L417-L425 |
welbornprod/colr | colr/__main__.py | main | def main(argd=None):
""" Main entry point, expects doctopt arg dict as argd. """
global DEBUG, debug
# The argd parameter for main() is for testing purposes only.
argd = argd or docopt(
USAGESTR,
version=VERSIONSTR,
script=SCRIPT,
# Example usage of colr_docopt colors.
... | python | def main(argd=None):
""" Main entry point, expects doctopt arg dict as argd. """
global DEBUG, debug
# The argd parameter for main() is for testing purposes only.
argd = argd or docopt(
USAGESTR,
version=VERSIONSTR,
script=SCRIPT,
# Example usage of colr_docopt colors.
... | [
"def",
"main",
"(",
"argd",
"=",
"None",
")",
":",
"global",
"DEBUG",
",",
"debug",
"# The argd parameter for main() is for testing purposes only.",
"argd",
"=",
"argd",
"or",
"docopt",
"(",
"USAGESTR",
",",
"version",
"=",
"VERSIONSTR",
",",
"script",
"=",
"SCR... | Main entry point, expects doctopt arg dict as argd. | [
"Main",
"entry",
"point",
"expects",
"doctopt",
"arg",
"dict",
"as",
"argd",
"."
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L152-L219 |
welbornprod/colr | colr/__main__.py | debug | def debug(*args, **kwargs):
""" Just prints to stderr, unless printdebug is installed. Then it
will be replaced in `main()` by `printdebug.debug`.
"""
if kwargs.get('file', None) is None:
kwargs['file'] = sys.stderr
msg = kwargs.get('sep', ' ').join(str(a) for a in args)
print('debug... | python | def debug(*args, **kwargs):
""" Just prints to stderr, unless printdebug is installed. Then it
will be replaced in `main()` by `printdebug.debug`.
"""
if kwargs.get('file', None) is None:
kwargs['file'] = sys.stderr
msg = kwargs.get('sep', ' ').join(str(a) for a in args)
print('debug... | [
"def",
"debug",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
".",
"get",
"(",
"'file'",
",",
"None",
")",
"is",
"None",
":",
"kwargs",
"[",
"'file'",
"]",
"=",
"sys",
".",
"stderr",
"msg",
"=",
"kwargs",
".",
"get",
"(",... | Just prints to stderr, unless printdebug is installed. Then it
will be replaced in `main()` by `printdebug.debug`. | [
"Just",
"prints",
"to",
"stderr",
"unless",
"printdebug",
"is",
"installed",
".",
"Then",
"it",
"will",
"be",
"replaced",
"in",
"main",
"()",
"by",
"printdebug",
".",
"debug",
"."
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L222-L229 |
welbornprod/colr | colr/__main__.py | dict_pop_or | def dict_pop_or(d, key, default=None):
""" Try popping a key from a dict.
Instead of raising KeyError, just return the default value.
"""
val = default
with suppress(KeyError):
val = d.pop(key)
return val | python | def dict_pop_or(d, key, default=None):
""" Try popping a key from a dict.
Instead of raising KeyError, just return the default value.
"""
val = default
with suppress(KeyError):
val = d.pop(key)
return val | [
"def",
"dict_pop_or",
"(",
"d",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"val",
"=",
"default",
"with",
"suppress",
"(",
"KeyError",
")",
":",
"val",
"=",
"d",
".",
"pop",
"(",
"key",
")",
"return",
"val"
] | Try popping a key from a dict.
Instead of raising KeyError, just return the default value. | [
"Try",
"popping",
"a",
"key",
"from",
"a",
"dict",
".",
"Instead",
"of",
"raising",
"KeyError",
"just",
"return",
"the",
"default",
"value",
"."
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L232-L239 |
welbornprod/colr | colr/__main__.py | get_colr | def get_colr(txt, argd):
""" Return a Colr instance based on user args. """
fore = parse_colr_arg(
get_name_arg(argd, '--fore', 'FORE', default=None),
rgb_mode=argd['--truecolor'],
)
back = parse_colr_arg(
get_name_arg(argd, '--back', 'BACK', default=None),
rgb_mode=argd[... | python | def get_colr(txt, argd):
""" Return a Colr instance based on user args. """
fore = parse_colr_arg(
get_name_arg(argd, '--fore', 'FORE', default=None),
rgb_mode=argd['--truecolor'],
)
back = parse_colr_arg(
get_name_arg(argd, '--back', 'BACK', default=None),
rgb_mode=argd[... | [
"def",
"get_colr",
"(",
"txt",
",",
"argd",
")",
":",
"fore",
"=",
"parse_colr_arg",
"(",
"get_name_arg",
"(",
"argd",
",",
"'--fore'",
",",
"'FORE'",
",",
"default",
"=",
"None",
")",
",",
"rgb_mode",
"=",
"argd",
"[",
"'--truecolor'",
"]",
",",
")",
... | Return a Colr instance based on user args. | [
"Return",
"a",
"Colr",
"instance",
"based",
"on",
"user",
"args",
"."
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L242-L285 |
welbornprod/colr | colr/__main__.py | get_name_arg | def get_name_arg(argd, *argnames, default=None):
""" Return the first argument value given in a docopt arg dict.
When not given, return default.
"""
val = None
for argname in argnames:
if argd[argname]:
val = argd[argname].lower().strip()
break
return val if v... | python | def get_name_arg(argd, *argnames, default=None):
""" Return the first argument value given in a docopt arg dict.
When not given, return default.
"""
val = None
for argname in argnames:
if argd[argname]:
val = argd[argname].lower().strip()
break
return val if v... | [
"def",
"get_name_arg",
"(",
"argd",
",",
"*",
"argnames",
",",
"default",
"=",
"None",
")",
":",
"val",
"=",
"None",
"for",
"argname",
"in",
"argnames",
":",
"if",
"argd",
"[",
"argname",
"]",
":",
"val",
"=",
"argd",
"[",
"argname",
"]",
".",
"low... | Return the first argument value given in a docopt arg dict.
When not given, return default. | [
"Return",
"the",
"first",
"argument",
"value",
"given",
"in",
"a",
"docopt",
"arg",
"dict",
".",
"When",
"not",
"given",
"return",
"default",
"."
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L288-L297 |
welbornprod/colr | colr/__main__.py | handle_err | def handle_err(*args):
""" Handle fatal errors, caught in __main__ scope.
If DEBUG is set, print a real traceback.
Otherwise, `print_err` any arguments passed.
"""
if DEBUG:
print_err(traceback.format_exc(), color=False)
else:
print_err(*args, newline=True) | python | def handle_err(*args):
""" Handle fatal errors, caught in __main__ scope.
If DEBUG is set, print a real traceback.
Otherwise, `print_err` any arguments passed.
"""
if DEBUG:
print_err(traceback.format_exc(), color=False)
else:
print_err(*args, newline=True) | [
"def",
"handle_err",
"(",
"*",
"args",
")",
":",
"if",
"DEBUG",
":",
"print_err",
"(",
"traceback",
".",
"format_exc",
"(",
")",
",",
"color",
"=",
"False",
")",
"else",
":",
"print_err",
"(",
"*",
"args",
",",
"newline",
"=",
"True",
")"
] | Handle fatal errors, caught in __main__ scope.
If DEBUG is set, print a real traceback.
Otherwise, `print_err` any arguments passed. | [
"Handle",
"fatal",
"errors",
"caught",
"in",
"__main__",
"scope",
".",
"If",
"DEBUG",
"is",
"set",
"print",
"a",
"real",
"traceback",
".",
"Otherwise",
"print_err",
"any",
"arguments",
"passed",
"."
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L300-L308 |
welbornprod/colr | colr/__main__.py | justify | def justify(clr, argd):
""" Justify str/Colr based on user args. """
methodmap = {
'--ljust': clr.ljust,
'--rjust': clr.rjust,
'--center': clr.center,
}
for flag in methodmap:
if argd[flag]:
if argd[flag] in ('0', '-'):
val = get_terminal_size(... | python | def justify(clr, argd):
""" Justify str/Colr based on user args. """
methodmap = {
'--ljust': clr.ljust,
'--rjust': clr.rjust,
'--center': clr.center,
}
for flag in methodmap:
if argd[flag]:
if argd[flag] in ('0', '-'):
val = get_terminal_size(... | [
"def",
"justify",
"(",
"clr",
",",
"argd",
")",
":",
"methodmap",
"=",
"{",
"'--ljust'",
":",
"clr",
".",
"ljust",
",",
"'--rjust'",
":",
"clr",
".",
"rjust",
",",
"'--center'",
":",
"clr",
".",
"center",
",",
"}",
"for",
"flag",
"in",
"methodmap",
... | Justify str/Colr based on user args. | [
"Justify",
"str",
"/",
"Colr",
"based",
"on",
"user",
"args",
"."
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L311-L330 |
welbornprod/colr | colr/__main__.py | list_known_codes | def list_known_codes(s, unique=True, rgb_mode=False):
""" Find and print all known escape codes in a string,
using get_known_codes.
"""
total = 0
for codedesc in get_known_codes(s, unique=unique, rgb_mode=rgb_mode):
total += 1
print(codedesc)
plural = 'code' if total == 1 els... | python | def list_known_codes(s, unique=True, rgb_mode=False):
""" Find and print all known escape codes in a string,
using get_known_codes.
"""
total = 0
for codedesc in get_known_codes(s, unique=unique, rgb_mode=rgb_mode):
total += 1
print(codedesc)
plural = 'code' if total == 1 els... | [
"def",
"list_known_codes",
"(",
"s",
",",
"unique",
"=",
"True",
",",
"rgb_mode",
"=",
"False",
")",
":",
"total",
"=",
"0",
"for",
"codedesc",
"in",
"get_known_codes",
"(",
"s",
",",
"unique",
"=",
"unique",
",",
"rgb_mode",
"=",
"rgb_mode",
")",
":",... | Find and print all known escape codes in a string,
using get_known_codes. | [
"Find",
"and",
"print",
"all",
"known",
"escape",
"codes",
"in",
"a",
"string",
"using",
"get_known_codes",
"."
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L333-L344 |
welbornprod/colr | colr/__main__.py | list_names | def list_names():
""" List all known color names. """
names = get_all_names()
# This is 375 right now. Probably won't ever change, but I'm not sure.
nameslen = len(names)
print('\nListing {} names:\n'.format(nameslen))
# Using 3 columns of names, still alphabetically sorted from the top down.
... | python | def list_names():
""" List all known color names. """
names = get_all_names()
# This is 375 right now. Probably won't ever change, but I'm not sure.
nameslen = len(names)
print('\nListing {} names:\n'.format(nameslen))
# Using 3 columns of names, still alphabetically sorted from the top down.
... | [
"def",
"list_names",
"(",
")",
":",
"names",
"=",
"get_all_names",
"(",
")",
"# This is 375 right now. Probably won't ever change, but I'm not sure.",
"nameslen",
"=",
"len",
"(",
"names",
")",
"print",
"(",
"'\\nListing {} names:\\n'",
".",
"format",
"(",
"nameslen",
... | List all known color names. | [
"List",
"all",
"known",
"color",
"names",
"."
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L347-L387 |
welbornprod/colr | colr/__main__.py | parse_gradient_rgb_args | def parse_gradient_rgb_args(args):
""" Parse one or two rgb args given with --gradientrgb.
Raises InvalidArg for invalid rgb values.
Returns a tuple of (start_rgb, stop_rgb), where the stop_rgb may be
None if only one arg value was given and start_rgb may be None if
no values were gi... | python | def parse_gradient_rgb_args(args):
""" Parse one or two rgb args given with --gradientrgb.
Raises InvalidArg for invalid rgb values.
Returns a tuple of (start_rgb, stop_rgb), where the stop_rgb may be
None if only one arg value was given and start_rgb may be None if
no values were gi... | [
"def",
"parse_gradient_rgb_args",
"(",
"args",
")",
":",
"arglen",
"=",
"len",
"(",
"args",
")",
"if",
"arglen",
"<",
"1",
"or",
"arglen",
">",
"2",
":",
"raise",
"InvalidArg",
"(",
"arglen",
",",
"label",
"=",
"'Expecting 1 or 2 \\'-G\\' flags, got'",
")",
... | Parse one or two rgb args given with --gradientrgb.
Raises InvalidArg for invalid rgb values.
Returns a tuple of (start_rgb, stop_rgb), where the stop_rgb may be
None if only one arg value was given and start_rgb may be None if
no values were given. | [
"Parse",
"one",
"or",
"two",
"rgb",
"args",
"given",
"with",
"--",
"gradientrgb",
".",
"Raises",
"InvalidArg",
"for",
"invalid",
"rgb",
"values",
".",
"Returns",
"a",
"tuple",
"of",
"(",
"start_rgb",
"stop_rgb",
")",
"where",
"the",
"stop_rgb",
"may",
"be"... | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L410-L422 |
welbornprod/colr | colr/__main__.py | print_err | def print_err(*args, **kwargs):
""" A wrapper for print() that uses stderr by default. """
if kwargs.get('file', None) is None:
kwargs['file'] = sys.stderr
color = dict_pop_or(kwargs, 'color', True)
# Use color if asked, but only if the file is a tty.
if color and kwargs['file'].isatty():
... | python | def print_err(*args, **kwargs):
""" A wrapper for print() that uses stderr by default. """
if kwargs.get('file', None) is None:
kwargs['file'] = sys.stderr
color = dict_pop_or(kwargs, 'color', True)
# Use color if asked, but only if the file is a tty.
if color and kwargs['file'].isatty():
... | [
"def",
"print_err",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
".",
"get",
"(",
"'file'",
",",
"None",
")",
"is",
"None",
":",
"kwargs",
"[",
"'file'",
"]",
"=",
"sys",
".",
"stderr",
"color",
"=",
"dict_pop_or",
"(",
"k... | A wrapper for print() that uses stderr by default. | [
"A",
"wrapper",
"for",
"print",
"()",
"that",
"uses",
"stderr",
"by",
"default",
"."
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L425-L447 |
welbornprod/colr | colr/__main__.py | read_stdin | def read_stdin():
""" Read text from stdin, and print a helpful message for ttys. """
if sys.stdin.isatty() and sys.stdout.isatty():
print('\nReading from stdin until end of file (Ctrl + D)...')
return sys.stdin.read() | python | def read_stdin():
""" Read text from stdin, and print a helpful message for ttys. """
if sys.stdin.isatty() and sys.stdout.isatty():
print('\nReading from stdin until end of file (Ctrl + D)...')
return sys.stdin.read() | [
"def",
"read_stdin",
"(",
")",
":",
"if",
"sys",
".",
"stdin",
".",
"isatty",
"(",
")",
"and",
"sys",
".",
"stdout",
".",
"isatty",
"(",
")",
":",
"print",
"(",
"'\\nReading from stdin until end of file (Ctrl + D)...'",
")",
"return",
"sys",
".",
"stdin",
... | Read text from stdin, and print a helpful message for ttys. | [
"Read",
"text",
"from",
"stdin",
"and",
"print",
"a",
"helpful",
"message",
"for",
"ttys",
"."
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L450-L455 |
welbornprod/colr | colr/__main__.py | translate | def translate(usercodes, rgb_mode=False):
""" Translate one or more hex, term, or rgb value into the others.
Yields strings with the results for each code translated.
"""
for code in usercodes:
code = code.strip().lower()
if code.isalpha() and (code in codes['fore']):
# B... | python | def translate(usercodes, rgb_mode=False):
""" Translate one or more hex, term, or rgb value into the others.
Yields strings with the results for each code translated.
"""
for code in usercodes:
code = code.strip().lower()
if code.isalpha() and (code in codes['fore']):
# B... | [
"def",
"translate",
"(",
"usercodes",
",",
"rgb_mode",
"=",
"False",
")",
":",
"for",
"code",
"in",
"usercodes",
":",
"code",
"=",
"code",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"if",
"code",
".",
"isalpha",
"(",
")",
"and",
"(",
"code",
... | Translate one or more hex, term, or rgb value into the others.
Yields strings with the results for each code translated. | [
"Translate",
"one",
"or",
"more",
"hex",
"term",
"or",
"rgb",
"value",
"into",
"the",
"others",
".",
"Yields",
"strings",
"with",
"the",
"results",
"for",
"each",
"code",
"translated",
"."
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L458-L479 |
welbornprod/colr | colr/__main__.py | translate_basic | def translate_basic(usercode):
""" Translate a basic color name to color with explanation. """
codenum = get_code_num(codes['fore'][usercode])
colorcode = codeformat(codenum)
msg = 'Name: {:>10}, Number: {:>3}, EscapeCode: {!r}'.format(
usercode,
codenum,
colorcode
)
if d... | python | def translate_basic(usercode):
""" Translate a basic color name to color with explanation. """
codenum = get_code_num(codes['fore'][usercode])
colorcode = codeformat(codenum)
msg = 'Name: {:>10}, Number: {:>3}, EscapeCode: {!r}'.format(
usercode,
codenum,
colorcode
)
if d... | [
"def",
"translate_basic",
"(",
"usercode",
")",
":",
"codenum",
"=",
"get_code_num",
"(",
"codes",
"[",
"'fore'",
"]",
"[",
"usercode",
"]",
")",
"colorcode",
"=",
"codeformat",
"(",
"codenum",
")",
"msg",
"=",
"'Name: {:>10}, Number: {:>3}, EscapeCode: {!r}'",
... | Translate a basic color name to color with explanation. | [
"Translate",
"a",
"basic",
"color",
"name",
"to",
"color",
"with",
"explanation",
"."
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L482-L493 |
welbornprod/colr | colr/__main__.py | try_float | def try_float(s, default=None, minimum=None):
""" Try parsing a string into a float.
If None is passed, default is returned.
On failure, InvalidFloat is raised.
"""
if not s:
return default
try:
val = float(s)
except (TypeError, ValueError):
raise InvalidNumbe... | python | def try_float(s, default=None, minimum=None):
""" Try parsing a string into a float.
If None is passed, default is returned.
On failure, InvalidFloat is raised.
"""
if not s:
return default
try:
val = float(s)
except (TypeError, ValueError):
raise InvalidNumbe... | [
"def",
"try_float",
"(",
"s",
",",
"default",
"=",
"None",
",",
"minimum",
"=",
"None",
")",
":",
"if",
"not",
"s",
":",
"return",
"default",
"try",
":",
"val",
"=",
"float",
"(",
"s",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
... | Try parsing a string into a float.
If None is passed, default is returned.
On failure, InvalidFloat is raised. | [
"Try",
"parsing",
"a",
"string",
"into",
"a",
"float",
".",
"If",
"None",
"is",
"passed",
"default",
"is",
"returned",
".",
"On",
"failure",
"InvalidFloat",
"is",
"raised",
"."
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L496-L509 |
welbornprod/colr | colr/__main__.py | try_int | def try_int(s, default=None, minimum=None):
""" Try parsing a string into an integer.
If None is passed, default is returned.
On failure, InvalidNumber is raised.
"""
if not s:
return default
try:
val = int(s)
except (TypeError, ValueError):
raise InvalidNumbe... | python | def try_int(s, default=None, minimum=None):
""" Try parsing a string into an integer.
If None is passed, default is returned.
On failure, InvalidNumber is raised.
"""
if not s:
return default
try:
val = int(s)
except (TypeError, ValueError):
raise InvalidNumbe... | [
"def",
"try_int",
"(",
"s",
",",
"default",
"=",
"None",
",",
"minimum",
"=",
"None",
")",
":",
"if",
"not",
"s",
":",
"return",
"default",
"try",
":",
"val",
"=",
"int",
"(",
"s",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"ra... | Try parsing a string into an integer.
If None is passed, default is returned.
On failure, InvalidNumber is raised. | [
"Try",
"parsing",
"a",
"string",
"into",
"an",
"integer",
".",
"If",
"None",
"is",
"passed",
"default",
"is",
"returned",
".",
"On",
"failure",
"InvalidNumber",
"is",
"raised",
"."
] | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L512-L525 |
welbornprod/colr | colr/__main__.py | try_rgb | def try_rgb(s, default=None):
""" Try parsing a string into an rgb value (int, int, int),
where the ints are 0-255 inclusive.
If None is passed, default is returned.
On failure, InvalidArg is raised.
"""
if not s:
return default
try:
r, g, b = (int(x.strip()) for ... | python | def try_rgb(s, default=None):
""" Try parsing a string into an rgb value (int, int, int),
where the ints are 0-255 inclusive.
If None is passed, default is returned.
On failure, InvalidArg is raised.
"""
if not s:
return default
try:
r, g, b = (int(x.strip()) for ... | [
"def",
"try_rgb",
"(",
"s",
",",
"default",
"=",
"None",
")",
":",
"if",
"not",
"s",
":",
"return",
"default",
"try",
":",
"r",
",",
"g",
",",
"b",
"=",
"(",
"int",
"(",
"x",
".",
"strip",
"(",
")",
")",
"for",
"x",
"in",
"s",
".",
"split",... | Try parsing a string into an rgb value (int, int, int),
where the ints are 0-255 inclusive.
If None is passed, default is returned.
On failure, InvalidArg is raised. | [
"Try",
"parsing",
"a",
"string",
"into",
"an",
"rgb",
"value",
"(",
"int",
"int",
"int",
")",
"where",
"the",
"ints",
"are",
"0",
"-",
"255",
"inclusive",
".",
"If",
"None",
"is",
"passed",
"default",
"is",
"returned",
".",
"On",
"failure",
"InvalidArg... | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L528-L543 |
welbornprod/colr | colr/__main__.py | entry_point | def entry_point():
""" An entry point for setuptools. This is required because
`if __name__ == '__main__'` is not fired when the entry point
is 'main()'. This just wraps the old behavior in a function so
it can be called from setuptools.
"""
try:
mainret = main()
except (... | python | def entry_point():
""" An entry point for setuptools. This is required because
`if __name__ == '__main__'` is not fired when the entry point
is 'main()'. This just wraps the old behavior in a function so
it can be called from setuptools.
"""
try:
mainret = main()
except (... | [
"def",
"entry_point",
"(",
")",
":",
"try",
":",
"mainret",
"=",
"main",
"(",
")",
"except",
"(",
"EOFError",
",",
"KeyboardInterrupt",
")",
":",
"print_err",
"(",
"'\\nUser cancelled.\\n'",
")",
"mainret",
"=",
"2",
"except",
"BrokenPipeError",
":",
"print_... | An entry point for setuptools. This is required because
`if __name__ == '__main__'` is not fired when the entry point
is 'main()'. This just wraps the old behavior in a function so
it can be called from setuptools. | [
"An",
"entry",
"point",
"for",
"setuptools",
".",
"This",
"is",
"required",
"because",
"if",
"__name__",
"==",
"__main__",
"is",
"not",
"fired",
"when",
"the",
"entry",
"point",
"is",
"main",
"()",
".",
"This",
"just",
"wraps",
"the",
"old",
"behavior",
... | train | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L557-L578 |
geertj/gruvi | lib/gruvi/sslcompat.py | create_default_context | def create_default_context(purpose=None, **kwargs):
"""Create a new SSL context in the most secure way available on the current
Python version. See :func:`ssl.create_default_context`."""
if hasattr(ssl, 'create_default_context'):
# Python 2.7.9+, Python 3.4+: take a server_side boolean or None, in
... | python | def create_default_context(purpose=None, **kwargs):
"""Create a new SSL context in the most secure way available on the current
Python version. See :func:`ssl.create_default_context`."""
if hasattr(ssl, 'create_default_context'):
# Python 2.7.9+, Python 3.4+: take a server_side boolean or None, in
... | [
"def",
"create_default_context",
"(",
"purpose",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"hasattr",
"(",
"ssl",
",",
"'create_default_context'",
")",
":",
"# Python 2.7.9+, Python 3.4+: take a server_side boolean or None, in",
"# addition to the ssl.Purpose.XX... | Create a new SSL context in the most secure way available on the current
Python version. See :func:`ssl.create_default_context`. | [
"Create",
"a",
"new",
"SSL",
"context",
"in",
"the",
"most",
"secure",
"way",
"available",
"on",
"the",
"current",
"Python",
"version",
".",
"See",
":",
"func",
":",
"ssl",
".",
"create_default_context",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/sslcompat.py#L171-L187 |
geertj/gruvi | lib/gruvi/logging.py | get_logger | def get_logger(context=None, name=None):
"""Return a logger for *context*.
Return a :class:`ContextLogger` instance. The instance implements the
standard library's :class:`logging.Logger` interface.
"""
# Many class instances have their own logger. Share them to save memory if
# possible, i.e. ... | python | def get_logger(context=None, name=None):
"""Return a logger for *context*.
Return a :class:`ContextLogger` instance. The instance implements the
standard library's :class:`logging.Logger` interface.
"""
# Many class instances have their own logger. Share them to save memory if
# possible, i.e. ... | [
"def",
"get_logger",
"(",
"context",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"# Many class instances have their own logger. Share them to save memory if",
"# possible, i.e. when *context* is not set.",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"_logger_name",
... | Return a logger for *context*.
Return a :class:`ContextLogger` instance. The instance implements the
standard library's :class:`logging.Logger` interface. | [
"Return",
"a",
"logger",
"for",
"*",
"context",
"*",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/logging.py#L37-L55 |
geertj/gruvi | lib/gruvi/logging.py | ContextLogger.thread_info | def thread_info(self):
"""Return a string identifying the current thread and fiber."""
tid = threading.current_thread().name
if tid == 'MainThread':
tid = 'Main'
current = fibers.current()
fid = getattr(current, 'name') if current.parent else 'Root'
return '{}... | python | def thread_info(self):
"""Return a string identifying the current thread and fiber."""
tid = threading.current_thread().name
if tid == 'MainThread':
tid = 'Main'
current = fibers.current()
fid = getattr(current, 'name') if current.parent else 'Root'
return '{}... | [
"def",
"thread_info",
"(",
"self",
")",
":",
"tid",
"=",
"threading",
".",
"current_thread",
"(",
")",
".",
"name",
"if",
"tid",
"==",
"'MainThread'",
":",
"tid",
"=",
"'Main'",
"current",
"=",
"fibers",
".",
"current",
"(",
")",
"fid",
"=",
"getattr",... | Return a string identifying the current thread and fiber. | [
"Return",
"a",
"string",
"identifying",
"the",
"current",
"thread",
"and",
"fiber",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/logging.py#L79-L86 |
geertj/gruvi | lib/gruvi/logging.py | ContextLogger.frame_info | def frame_info(self):
"""Return a string identifying the current frame."""
if not self._logger.isEnabledFor(logging.DEBUG):
return ''
f = sys._getframe(3)
fname = os.path.split(f.f_code.co_filename)[1]
return '{}:{}'.format(fname, f.f_lineno) | python | def frame_info(self):
"""Return a string identifying the current frame."""
if not self._logger.isEnabledFor(logging.DEBUG):
return ''
f = sys._getframe(3)
fname = os.path.split(f.f_code.co_filename)[1]
return '{}:{}'.format(fname, f.f_lineno) | [
"def",
"frame_info",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_logger",
".",
"isEnabledFor",
"(",
"logging",
".",
"DEBUG",
")",
":",
"return",
"''",
"f",
"=",
"sys",
".",
"_getframe",
"(",
"3",
")",
"fname",
"=",
"os",
".",
"path",
".",
... | Return a string identifying the current frame. | [
"Return",
"a",
"string",
"identifying",
"the",
"current",
"frame",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/logging.py#L88-L94 |
geertj/gruvi | lib/gruvi/stream.py | StreamBuffer.set_buffer_limits | def set_buffer_limits(self, high=None, low=None):
"""Set the low and high watermarks for the read buffer."""
if high is None:
high = self.default_buffer_size
if low is None:
low = high // 2
self._buffer_high = high
self._buffer_low = low | python | def set_buffer_limits(self, high=None, low=None):
"""Set the low and high watermarks for the read buffer."""
if high is None:
high = self.default_buffer_size
if low is None:
low = high // 2
self._buffer_high = high
self._buffer_low = low | [
"def",
"set_buffer_limits",
"(",
"self",
",",
"high",
"=",
"None",
",",
"low",
"=",
"None",
")",
":",
"if",
"high",
"is",
"None",
":",
"high",
"=",
"self",
".",
"default_buffer_size",
"if",
"low",
"is",
"None",
":",
"low",
"=",
"high",
"//",
"2",
"... | Set the low and high watermarks for the read buffer. | [
"Set",
"the",
"low",
"and",
"high",
"watermarks",
"for",
"the",
"read",
"buffer",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/stream.py#L63-L70 |
geertj/gruvi | lib/gruvi/stream.py | StreamBuffer.feed | def feed(self, data):
"""Add *data* to the buffer."""
self._buffers.append(data)
self._buffer_size += len(data)
self._maybe_pause_transport()
self._can_read.set() | python | def feed(self, data):
"""Add *data* to the buffer."""
self._buffers.append(data)
self._buffer_size += len(data)
self._maybe_pause_transport()
self._can_read.set() | [
"def",
"feed",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_buffers",
".",
"append",
"(",
"data",
")",
"self",
".",
"_buffer_size",
"+=",
"len",
"(",
"data",
")",
"self",
".",
"_maybe_pause_transport",
"(",
")",
"self",
".",
"_can_read",
".",
"... | Add *data* to the buffer. | [
"Add",
"*",
"data",
"*",
"to",
"the",
"buffer",
"."
] | train | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/stream.py#L72-L77 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.