Search is not available for this dataset
text stringlengths 75 104k |
|---|
def from_str(cls, s):
# type: (Union[Text, bytes]) -> FmtStr
r"""
Return a FmtStr representing input.
The str() of a FmtStr is guaranteed to produced the same FmtStr.
Other input with escape sequences may not be preserved.
>>> fmtstr("|"+fmtstr("hey", fg='red', bg='blue... |
def copy_with_new_str(self, new_str):
"""Copies the current FmtStr's attributes while changing its string."""
# What to do when there are multiple Chunks with conflicting atts?
old_atts = dict((att, value) for bfs in self.chunks
for (att, value) in bfs.atts.items())
r... |
def setitem(self, startindex, fs):
"""Shim for easily converting old __setitem__ calls"""
return self.setslice_with_length(startindex, startindex+1, fs, len(self)) |
def setslice_with_length(self, startindex, endindex, fs, length):
"""Shim for easily converting old __setitem__ calls"""
if len(self) < startindex:
fs = ' '*(startindex - len(self)) + fs
if len(self) > endindex:
fs = fs + ' '*(endindex - startindex - len(fs))
... |
def splice(self, new_str, start, end=None):
"""Returns a new FmtStr with the input string spliced into the
the original FmtStr at start and end.
If end is provided, new_str will replace the substring self.s[start:end-1].
"""
if len(new_str) == 0:
return self
n... |
def copy_with_new_atts(self, **attributes):
"""Returns a new FmtStr with the same content but new formatting"""
return FmtStr(*[Chunk(bfs.s, bfs.atts.extend(attributes))
for bfs in self.chunks]) |
def join(self, iterable):
"""Joins an iterable yielding strings or FmtStrs with self as separator"""
before = []
chunks = []
for i, s in enumerate(iterable):
chunks.extend(before)
before = self.chunks
if isinstance(s, FmtStr):
chunks.ex... |
def split(self, sep=None, maxsplit=None, regex=False):
"""Split based on seperator, optionally using a regex
Capture groups are ignored in regex, the whole pattern is matched
and used to split the original FmtStr."""
if maxsplit is not None:
raise NotImplementedError('no max... |
def splitlines(self, keepends=False):
"""Return a list of lines, split on newline characters,
include line boundaries, if keepends is true."""
lines = self.split('\n')
return [line+'\n' for line in lines] if keepends else (
lines if lines[-1] else lines[:-1]) |
def ljust(self, width, fillchar=None):
"""S.ljust(width[, fillchar]) -> string
If a fillchar is provided, less formatting information will be preserved
"""
if fillchar is not None:
return fmtstr(self.s.ljust(width, fillchar), **self.shared_atts)
to_add = ' ' * (width... |
def width(self):
"""The number of columns it would take to display this string"""
if self._width is not None:
return self._width
self._width = sum(fs.width for fs in self.chunks)
return self._width |
def width_at_offset(self, n):
"""Returns the horizontal position of character n of the string"""
#TODO make more efficient?
width = wcswidth(self.s[:n])
assert width != -1
return width |
def shared_atts(self):
"""Gets atts shared among all nonzero length component Chunk"""
#TODO cache this, could get ugly for large FmtStrs
atts = {}
first = self.chunks[0]
for att in sorted(first.atts):
#TODO how to write this without the '???'?
if all(fs.a... |
def new_with_atts_removed(self, *attributes):
"""Returns a new FmtStr with the same content but some attributes removed"""
return FmtStr(*[Chunk(bfs.s, bfs.atts.remove(*attributes))
for bfs in self.chunks]) |
def divides(self):
"""List of indices of divisions between the constituent chunks."""
acc = [0]
for s in self.chunks:
acc.append(acc[-1] + len(s))
return acc |
def width_aware_slice(self, index):
"""Slice based on the number of columns it would take to display the substring."""
if wcswidth(self.s) == -1:
raise ValueError('bad values for width aware slicing')
index = normalize_slice(self.width, index)
counter = 0
parts = []
... |
def width_aware_splitlines(self, columns):
# type: (int) -> Iterator[FmtStr]
"""Split into lines, pushing doublewidth characters at the end of a line to the next line.
When a double-width character is pushed to the next line, a space is added to pad out the line.
"""
if columns ... |
def _getitem_normalized(self, index):
"""Builds the more compact fmtstrs by using fromstr( of the control sequences)"""
index = normalize_slice(len(self), index)
counter = 0
output = ''
for fs in self.chunks:
if index.start < counter + len(fs) and index.stop > counter... |
def _calculate_block_structure(self, inequalities, equalities,
momentinequalities, momentequalities,
extramomentmatrix, removeequalities,
block_struct=None):
"""Calculates the block_struct array for the outp... |
def main():
"""Ideally we shouldn't lose the first second of events"""
time.sleep(1)
with Input() as input_generator:
for e in input_generator:
print(repr(e)) |
def _process_monomial(self, monomial, n_vars):
"""Process a single monomial when building the moment matrix.
"""
coeff, monomial = monomial.as_coeff_Mul()
k = 0
# Have we seen this monomial before?
conjugate = False
try:
# If yes, then we improve spars... |
def __get_trace_facvar(self, polynomial):
"""Return dense vector representation of a polynomial. This function is
nearly identical to __push_facvar_sparse, but instead of pushing
sparse entries to the constraint matrices, it returns a dense
vector.
"""
facvar = [0] * (sel... |
def set_objective(self, objective, extraobjexpr=None):
"""Set or change the objective function of the polynomial optimization
problem.
:param objective: Describes the objective function.
:type objective: :class:`sympy.core.expr.Expr`
:param extraobjexpr: Optional parameter of a ... |
def _calculate_block_structure(self, inequalities, equalities,
momentinequalities, momentequalities,
extramomentmatrix, removeequalities,
block_struct=None):
"""Calculates the block_struct array for the outp... |
def write_to_file(self, filename, filetype=None):
"""Write the relaxation to a file.
:param filename: The name of the file to write to. The type can be
autodetected from the extension: .dat-s for SDPA,
.task for mosek, .csv for human readable format, or... |
def get_outerframe_skip_importlib_frame(level):
"""
There's a bug in Python3.4+, see http://bugs.python.org/issue23773,
remove this and use sys._getframe(3) when bug is fixed
"""
if sys.version_info < (3, 4):
return sys._getframe(level)
else:
curre... |
def public_api(self,url):
''' template function of public api'''
try :
url in api_urls
return ast.literal_eval(requests.get(base_url + api_urls.get(url)).text)
except Exception as e:
print(e) |
def parse(s):
r"""
Returns a list of strings or format dictionaries to describe the strings.
May raise a ValueError if it can't be parsed.
>>> parse(">>> []")
['>>> []']
>>> #parse("\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\... |
def peel_off_esc_code(s):
r"""Returns processed text, the next token, and unprocessed text
>>> front, d, rest = peel_off_esc_code('some[2Astuff')
>>> front, rest
('some', 'stuff')
>>> d == {'numbers': [2], 'command': 'A', 'intermed': '', 'private': '', 'csi': '\x1b[', 'seq': '\x1b[2A'}
True
... |
def get_key(bytes_, encoding, keynames='curtsies', full=False):
"""Return key pressed from bytes_ or None
Return a key name or None meaning it's an incomplete sequence of bytes
(more bytes needed to determine the key pressed)
encoding is how the bytes should be translated to unicode - it should
ma... |
def could_be_unfinished_char(seq, encoding):
"""Whether seq bytes might create a char in encoding if more bytes were added"""
if decodable(seq, encoding):
return False # any sensible encoding surely doesn't require lookahead (right?)
# (if seq bytes encoding a character, adding another byte shou... |
def pp_event(seq):
"""Returns pretty representation of an Event or keypress"""
if isinstance(seq, Event):
return str(seq)
# Get the original sequence back if seq is a pretty name already
rev_curses = dict((v, k) for k, v in CURSES_NAMES.items())
rev_curtsies = dict((v, k) for k, v in CURTS... |
def create_nouns(max=2):
"""
Return a string of random nouns up to max number
"""
nouns = []
for noun in range(0, max):
nouns.append(random.choice(noun_list))
return " ".join(nouns) |
def create_date(past=False, max_years_future=10, max_years_past=10):
"""
Create a random valid date
If past, then dates can be in the past
If into the future, then no more than max_years into the future
If it's not, then it can't be any older than max_years_past
"""
if past:
start = ... |
def create_birthday(min_age=18, max_age=80):
"""
Create a random birthday fomr someone between the ages of min_age and max_age
"""
age = random.randint(min_age, max_age)
start = datetime.date.today() - datetime.timedelta(days=random.randint(0, 365))
return start - datetime.timedelta(days=age * 3... |
def create_pw(length=8, digits=2, upper=2, lower=2):
"""Create a random password
From Stackoverflow:
http://stackoverflow.com/questions/7479442/high-quality-simple-random-password-generator
Create a random password with the specified length and no. of
digit, upper and lower case letters.
:para... |
def show_examples():
""" Run through some simple examples
"""
first, last = create_name()
add = create_street()
zip, city, state = create_city_state_zip()
phone = create_phone(zip)
print(first, last)
print(add)
print("{0:s} {1:s} {2:s}".format(city, state, zip))
print(phone)
... |
def convert_to_mosek_index(block_struct, row_offsets, block_offsets, row):
"""MOSEK requires a specific sparse format to define the lower-triangular
part of a symmetric matrix. This function does the conversion from the
sparse upper triangular matrix format of Ncpol2SDPA.
"""
block_index, i, j = con... |
def convert_to_mosek_matrix(sdp):
"""Converts the entire sparse representation of the Fi constraint matrices
to sparse MOSEK matrices.
"""
barci = []
barcj = []
barcval = []
barai = []
baraj = []
baraval = []
for k in range(sdp.n_vars):
barai.append([])
baraj.appe... |
def convert_to_mosek(sdp):
"""Convert an SDP relaxation to a MOSEK task.
:param sdp: The SDP relaxation to convert.
:type sdp: :class:`ncpol2sdpa.sdp`.
:returns: :class:`mosek.Task`.
"""
import mosek
# Cheat when variables are complex and convert with PICOS
if sdp.complex_matrix:
... |
def _add_text(self, text):
"""
If ``text`` is not empty, append a new Text node to the most recent
pending node, if there is any, or to the new nodes, if there are no
pending nodes.
"""
if text:
if self.pending_nodes:
self.pending_nodes[-1].app... |
def version():
"""Return version string."""
with open(os.path.join('curtsies', '__init__.py')) as input_file:
for line in input_file:
if line.startswith('__version__'):
return ast.parse(line).body[0].value.s |
def fsarray(strings, *args, **kwargs):
"""fsarray(list_of_FmtStrs_or_strings, width=None) -> FSArray
Returns a new FSArray of width of the maximum size of the provided
strings, or width provided, and height of the number of strings provided.
If a width is provided, raises a ValueError if any of the str... |
def diff(cls, a, b, ignore_formatting=False):
"""Returns two FSArrays with differences underlined"""
def underline(x): return u'\x1b[4m%s\x1b[0m' % (x,)
def blink(x): return u'\x1b[5m%s\x1b[0m' % (x,)
a_rows = []
b_rows = []
max_width = max([len(row) for row in a] + [len(... |
def create(self,rate, amount, order_type, pair):
''' create new order function
:param rate: float
:param amount: float
:param order_type: str; set 'buy' or 'sell'
:param pair: str; set 'btc_jpy'
'''
nonce = nounce()
payload = { 'rate': rate,
... |
def cancel(self,order_id):
''' cancel the specified order
:param order_id: order_id to be canceled
'''
url= 'https://coincheck.com/api/exchange/orders/' + order_id
headers = make_header(url,access_key=self.access_key,secret_key=self.secret_key)
r = requests.delete(url,hea... |
def history(self):
''' show payment history
'''
url= 'https://coincheck.com/api/exchange/orders/transactions'
headers = make_header(url,access_key=self.access_key,secret_key=self.secret_key)
r = requests.get(url,headers=headers)
return json.loads(r.text) |
def _length_hint(obj):
"""Returns the length hint of an object."""
try:
return len(obj)
except TypeError:
try:
get_hint = type(obj).__length_hint__
except AttributeError:
return None
try:
hint = get_hint(obj)
except TypeError:
... |
def pager(text, color=None):
"""Decide what method to use for paging through text."""
stdout = _default_text_stdout()
if not isatty(sys.stdin) or not isatty(stdout):
return _nullpager(stdout, text, color)
if 'PAGER' in os.environ:
if WIN:
return _tempfilepager(text, os.enviro... |
def from_int(cls, retries, redirect=True, default=None):
""" Backwards-compatibility for the old retries format."""
if retries is None:
retries = default if default is not None else cls.DEFAULT
if isinstance(retries, Retry):
return retries
redirect = bool(redire... |
def get_backoff_time(self):
""" Formula for computing the current backoff
:rtype: float
"""
if self._observed_errors <= 1:
return 0
backoff_value = self.backoff_factor * (2 ** (self._observed_errors - 1))
return min(self.BACKOFF_MAX, backoff_value) |
def is_forced_retry(self, method, status_code):
""" Is this method/status code retryable? (Based on method/codes whitelists)
"""
if self.method_whitelist and method.upper() not in self.method_whitelist:
return False
return self.status_forcelist and status_code in self.status... |
def convert_type(ty, default=None):
"""Converts a callable or python ty into the most appropriate param
ty.
"""
if isinstance(ty, tuple):
return Tuple(ty)
if isinstance(ty, ParamType):
return ty
guessed_type = False
if ty is None and default is not None:
ty = type(def... |
def wrap_text(text, width=78, initial_indent='', subsequent_indent='',
preserve_paragraphs=False):
"""A helper function that intelligently wraps text. By default, it
assumes that it operates on a single paragraph of text but if the
`preserve_paragraphs` parameter is provided it will intellige... |
def write_usage(self, prog, args='', prefix='Usage: '):
"""Writes a usage line into the buffer.
:param prog: the program name.
:param args: whitespace separated list of arguments.
:param prefix: the prefix for the first line.
"""
prefix = '%*s%s' % (self.current_indent, ... |
def in_(ctx, topics, yes, as_, enter):
"""Set the current topics to `topics`
Environment:
BE_PROJECT: First topic
BE_CWD: Current `be` working directory
BE_TOPICS: Arguments to `in`
BE_DEVELOPMENTDIR: Absolute path to current development directory
BE_PROJECTROOT: Absolut... |
def new(preset, name, silent, update):
"""Create new default preset
\b
Usage:
$ be new ad
"blue_unicorn" created
$ be new film --name spiderman
"spiderman" created
"""
if self.isactive():
lib.echo("Please exit current preset before starting a new")
... |
def update(preset, clean):
"""Update a local preset
This command will cause `be` to pull a preset already
available locally.
\b
Usage:
$ be update ad
Updating "ad"..
"""
if self.isactive():
lib.echo("ERROR: Exit current project first")
sys.exit(lib.USER_ER... |
def tab(topics, complete):
"""Utility sub-command for tabcompletion
This command is meant to be called by a tab completion
function and is given a the currently entered topics,
along with a boolean indicating whether or not the
last entered argument is complete.
"""
# Discard `be tab`
... |
def activate():
"""Enter into an environment with support for tab-completion
This command drops you into a subshell, similar to the one
generated via `be in ...`, except no topic is present and
instead it enables tab-completion for supported shells.
See documentation for further information.
h... |
def ls(topics):
"""List contents of current context
\b
Usage:
$ be ls
- spiderman
- hulk
$ be ls spiderman
- peter
- mjay
$ be ls spiderman seq01
- 1000
- 2000
- 2500
Return codes:
0 Normal
2 When insuffici... |
def mkdir(dir, enter):
"""Create directory with template for topic of the current environment
"""
if not os.path.exists(dir):
os.makedirs(dir) |
def preset_ls(remote):
"""List presets
\b
Usage:
$ be preset ls
- ad
- game
- film
"""
if self.isactive():
lib.echo("ERROR: Exit current project first")
sys.exit(lib.USER_ERROR)
if remote:
presets = _extern.github_presets()
else:
... |
def preset_find(query):
"""Find preset from hub
\b
$ be find ad
https://github.com/mottosso/be-ad.git
"""
if self.isactive():
lib.echo("ERROR: Exit current project first")
sys.exit(lib.USER_ERROR)
found = _extern.github_presets().get(query)
if found:
lib.echo(... |
def dump():
"""Print current environment
Environment is outputted in a YAML-friendly format
\b
Usage:
$ be dump
Prefixed:
- BE_TOPICS=hulk bruce animation
- ...
"""
if not self.isactive():
lib.echo("ERROR: Enter a project first")
sys.exit(lib.U... |
def what():
"""Print current topics"""
if not self.isactive():
lib.echo("No topic")
sys.exit(lib.USER_ERROR)
lib.echo(os.environ.get("BE_TOPICS", "This is a bug")) |
def get_netrc_auth(url):
"""Returns the Requests tuple auth for a given url from netrc."""
try:
from netrc import netrc, NetrcParseError
netrc_path = None
for f in NETRC_FILES:
try:
loc = os.path.expanduser('~/{0}'.format(f))
except KeyError:
... |
def add_dict_to_cookiejar(cj, cookie_dict):
"""Returns a CookieJar from a key/value dictionary.
:param cj: CookieJar to insert cookies into.
:param cookie_dict: Dict of key/values to insert into CookieJar.
"""
cj2 = cookiejar_from_dict(cookie_dict)
cj.update(cj2)
return cj |
def should_bypass_proxies(url):
"""
Returns whether we should bypass proxies or not.
"""
get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())
# First check whether no_proxy is defined. If it is, check that the URL
# we're getting isn't in the no_proxy list.
no_proxy = get_pr... |
def default_user_agent(name="python-requests"):
"""Return a string representing the default user agent."""
_implementation = platform.python_implementation()
if _implementation == 'CPython':
_implementation_version = platform.python_version()
elif _implementation == 'PyPy':
_implementat... |
def to_native_string(string, encoding='ascii'):
"""
Given a string object, regardless of type, returns a representation of that
string in the native string type, encoding and decoding where necessary.
This assumes ASCII unless told otherwise.
"""
out = None
if isinstance(string, builtin_str... |
def _bashcomplete(cmd, prog_name, complete_var=None):
"""Internal handler for the bash completion support."""
if complete_var is None:
complete_var = '_%s_COMPLETE' % (prog_name.replace('-', '_')).upper()
complete_instr = os.environ.get(complete_var)
if not complete_instr:
return
fr... |
def invoke(*args, **kwargs):
"""Invokes a command callback in exactly the way it expects. There
are two ways to invoke this method:
1. the first argument can be a callback and all other arguments and
keyword arguments are forwarded directly to the function.
2. the first a... |
def make_context(self, info_name, args, parent=None, **extra):
"""This function when given an info name and arguments will kick
off the parsing and create a new :class:`Context`. It does not
invoke the actual command callback though.
:param info_name: the info name for this invokation.... |
def main(self, args=None, prog_name=None, complete_var=None,
standalone_mode=True, **extra):
"""This is the way to invoke a script with all the bells and
whistles as a command line application. This will always terminate
the application after a call. If this is not wanted, ``Syste... |
def make_parser(self, ctx):
"""Creates the underlying option parser for this command."""
parser = OptionParser(ctx)
parser.allow_interspersed_args = ctx.allow_interspersed_args
parser.ignore_unknown_options = ctx.ignore_unknown_options
for param in self.get_params(ctx):
... |
def format_help_text(self, ctx, formatter):
"""Writes the help text to the formatter if it exists."""
if self.help:
formatter.write_paragraph()
with formatter.indentation():
formatter.write_text(self.help) |
def add_command(self, cmd, name=None):
"""Registers another :class:`Command` with this group. If the name
is not provided, the name of the command is used.
"""
name = name or cmd.name
if name is None:
raise TypeError('Command has no name.')
self.commands[name... |
def pass_obj(f):
"""Similar to :func:`pass_context`, but only pass the object on the
context onwards (:attr:`Context.obj`). This is useful if that object
represents the state of a nested system.
"""
@pass_context
def new_func(*args, **kwargs):
ctx = args[0]
return ctx.invoke(f, ... |
def option(*param_decls, **attrs):
"""Attaches an option to the command. All positional arguments are
passed as parameter declarations to :class:`Option`; all keyword
arguments are forwarded unchanged (except ``cls``).
This is equivalent to creating an :class:`Option` instance manually
and attachin... |
def version_option(version=None, *param_decls, **attrs):
"""Adds a ``--version`` option which immediately ends the program
printing out the version number. This is implemented as an eager
option that prints the version and exits the program in the callback.
:param version: the version number to show. ... |
def _basic_auth_str(username, password):
"""Returns a Basic Auth string."""
authstr = 'Basic ' + to_native_string(
b64encode(('%s:%s' % (username, password)).encode('latin1')).strip()
)
return authstr |
def ls(*topic, **kwargs):
"""List topic from external datastore
Arguments:
topic (str): One or more topics, e.g. ("project", "item", "task")
root (str, optional): Absolute path to where projects reside,
defaults to os.getcwd()
backend (callable, optional): Function to call w... |
def dump(context=os.environ):
"""Dump current environment as a dictionary
Arguments:
context (dict, optional): Current context, defaults
to the current environment.
"""
output = {}
for key, value in context.iteritems():
if not key.startswith("BE_"):
continu... |
def cwd():
"""Return the be current working directory"""
cwd = os.environ.get("BE_CWD")
if cwd and not os.path.isdir(cwd):
sys.stderr.write("ERROR: %s is not a directory" % cwd)
sys.exit(lib.USER_ERROR)
return cwd or os.getcwd().replace("\\", "/") |
def write_script(script, tempdir):
"""Write script to a temporary directory
Arguments:
script (list): Commands which to put into a file
Returns:
Absolute path to script
"""
name = "script" + self.suffix
path = os.path.join(tempdir, name)
with open(path, "w") as f:
... |
def write_aliases(aliases, tempdir):
"""Write aliases to temporary directory
Arguments:
aliases (dict): {name: value} dict of aliases
tempdir (str): Absolute path to where aliases will be stored
"""
platform = lib.platform()
if platform == "unix":
home_alias = "cd $BE_DEVE... |
def presets_dir():
"""Return presets directory"""
default_presets_dir = os.path.join(
os.path.expanduser("~"), ".be", "presets")
presets_dir = os.environ.get(BE_PRESETSDIR) or default_presets_dir
if not os.path.exists(presets_dir):
os.makedirs(presets_dir)
return presets_dir |
def remove_preset(preset):
"""Physically delete local preset
Arguments:
preset (str): Name of preset
"""
preset_dir = os.path.join(presets_dir(), preset)
try:
shutil.rmtree(preset_dir)
except IOError:
lib.echo("\"%s\" did not exist" % preset) |
def get(path, **kwargs):
"""requests.get wrapper"""
token = os.environ.get(BE_GITHUB_API_TOKEN)
if token:
kwargs["headers"] = {
"Authorization": "token %s" % token
}
try:
response = requests.get(path, verify=False, **kwargs)
if response.status_code == 403:
... |
def _gist_is_preset(repo):
"""Evaluate whether gist is a be package
Arguments:
gist (str): username/id pair e.g. mottosso/2bb4651a05af85711cde
"""
_, gistid = repo.split("/")
gist_template = "https://api.github.com/gists/{}"
gist_path = gist_template.format(gistid)
response = ge... |
def _repo_is_preset(repo):
"""Evaluate whether GitHub repository is a be package
Arguments:
gist (str): username/id pair e.g. mottosso/be-ad
"""
package_template = "https://raw.githubusercontent.com"
package_template += "/{repo}/master/package.json"
package_path = package_template.for... |
def github_presets():
"""Return remote presets hosted on GitHub"""
addr = ("https://raw.githubusercontent.com"
"/mottosso/be-presets/master/presets.json")
response = get(addr)
if response.status_code == 404:
lib.echo("Could not connect with preset database")
sys.exit(lib.PRO... |
def copy_preset(preset_dir, project_dir):
"""Copy contents of preset into new project
If package.json contains the key "contents", limit
the files copied to those present in this list.
Arguments:
preset_dir (str): Absolute path to preset
project_dir (str): Absolute path to new project
... |
def _resolve_references(templates):
"""Resolve {@} occurences by expansion
Given a dictionary {"a": "{@b}/x", "b": "{key}/y"}
Return {"a", "{key}/y/x", "b": "{key}/y"}
{
key: {@reference}/{variable} # pattern
}
In plain english, it looks within `pattern` for
references and replace... |
def add(self, key, val):
"""Adds a (name, value) pair, doesn't overwrite the value if it already
exists.
>>> headers = HTTPHeaderDict(foo='bar')
>>> headers.add('Foo', 'baz')
>>> headers['foo']
'bar, baz'
"""
key_lower = key.lower()
new_vals = key... |
def getlist(self, key):
"""Returns a list of all the values for the named field. Returns an
empty list if the key doesn't exist."""
try:
vals = _dict_getitem(self, key.lower())
except KeyError:
return []
else:
if isinstance(vals, tuple):
... |
def iteritems(self):
"""Iterate over all header lines, including duplicate ones."""
for key in self:
vals = _dict_getitem(self, key)
for val in vals[1:]:
yield vals[0], val |
def itermerged(self):
"""Iterate over all headers, merging duplicate ones together."""
for key in self:
val = _dict_getitem(self, key)
yield val[0], ', '.join(val[1:]) |
def from_httplib(cls, message, duplicates=('set-cookie',)): # Python 2
"""Read headers from a Python 2 httplib message object."""
ret = cls(message.items())
# ret now contains only the last header line for each duplicate.
# Importing with all duplicates would be nice, but this would
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.