index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
50,860 |
parameterized.parameterized
|
parameterized_class
|
Parameterizes a test class by setting attributes on the class.
Can be used in two ways:
1) With a list of dictionaries containing attributes to override::
@parameterized_class([
{ "username": "foo" },
{ "username": "bar", "access_level": 2 },
])
class TestUserAccessLevel(TestCase):
...
2) With a tuple of attributes, then a list of tuples of values:
@parameterized_class(("username", "access_level"), [
("foo", 1),
("bar", 2)
])
class TestUserAccessLevel(TestCase):
...
|
def parameterized_class(attrs, input_values=None, class_name_func=None, classname_func=None):
""" Parameterizes a test class by setting attributes on the class.
Can be used in two ways:
1) With a list of dictionaries containing attributes to override::
@parameterized_class([
{ "username": "foo" },
{ "username": "bar", "access_level": 2 },
])
class TestUserAccessLevel(TestCase):
...
2) With a tuple of attributes, then a list of tuples of values:
@parameterized_class(("username", "access_level"), [
("foo", 1),
("bar", 2)
])
class TestUserAccessLevel(TestCase):
...
"""
if isinstance(attrs, string_types):
attrs = [attrs]
input_dicts = (
attrs if input_values is None else
[dict(zip(attrs, vals)) for vals in input_values]
)
class_name_func = class_name_func or default_class_name_func
if classname_func:
warnings.warn(
"classname_func= is deprecated; use class_name_func= instead. "
"See: https://github.com/wolever/parameterized/pull/74#issuecomment-613577057",
DeprecationWarning,
stacklevel=2,
)
class_name_func = lambda cls, idx, input: classname_func(cls, idx, input_dicts)
def decorator(base_class):
test_class_module = sys.modules[base_class.__module__].__dict__
for idx, input_dict in enumerate(input_dicts):
test_class_dict = dict(base_class.__dict__)
test_class_dict.update(input_dict)
name = class_name_func(base_class, idx, input_dict)
test_class_module[name] = type(name, (base_class, ), test_class_dict)
# We need to leave the base class in place (see issue #73), but if we
# leave the test_ methods in place, the test runner will try to pick
# them up and run them... which doesn't make sense, since no parameters
# will have been applied.
# Address this by iterating over the base class and remove all test
# methods.
for method_name in list(base_class.__dict__):
if method_name.startswith("test"):
delattr(base_class, method_name)
return base_class
return decorator
|
(attrs, input_values=None, class_name_func=None, classname_func=None)
|
50,861 |
k_diffusion.layers
|
Denoiser
|
A Karras et al. preconditioner for denoising diffusion models.
|
class Denoiser(nn.Module):
"""A Karras et al. preconditioner for denoising diffusion models."""
def __init__(self, inner_model, sigma_data=1., weighting='karras', scales=1):
super().__init__()
self.inner_model = inner_model
self.sigma_data = sigma_data
self.scales = scales
if callable(weighting):
self.weighting = weighting
if weighting == 'karras':
self.weighting = torch.ones_like
elif weighting == 'soft-min-snr':
self.weighting = self._weighting_soft_min_snr
elif weighting == 'snr':
self.weighting = self._weighting_snr
else:
raise ValueError(f'Unknown weighting type {weighting}')
def _weighting_soft_min_snr(self, sigma):
return (sigma * self.sigma_data) ** 2 / (sigma ** 2 + self.sigma_data ** 2) ** 2
def _weighting_snr(self, sigma):
return self.sigma_data ** 2 / (sigma ** 2 + self.sigma_data ** 2)
def get_scalings(self, sigma):
c_skip = self.sigma_data ** 2 / (sigma ** 2 + self.sigma_data ** 2)
c_out = sigma * self.sigma_data / (sigma ** 2 + self.sigma_data ** 2) ** 0.5
c_in = 1 / (sigma ** 2 + self.sigma_data ** 2) ** 0.5
return c_skip, c_out, c_in
def loss(self, input, noise, sigma, **kwargs):
c_skip, c_out, c_in = [utils.append_dims(x, input.ndim) for x in self.get_scalings(sigma)]
c_weight = self.weighting(sigma)
noised_input = input + noise * utils.append_dims(sigma, input.ndim)
model_output = self.inner_model(noised_input * c_in, sigma, **kwargs)
target = (input - c_skip * noised_input) / c_out
if self.scales == 1:
return ((model_output - target) ** 2).flatten(1).mean(1) * c_weight
sq_error = dct(model_output - target) ** 2
f_weight = freq_weight_nd(sq_error.shape[2:], self.scales, dtype=sq_error.dtype, device=sq_error.device)
return (sq_error * f_weight).flatten(1).mean(1) * c_weight
def forward(self, input, sigma, **kwargs):
c_skip, c_out, c_in = [utils.append_dims(x, input.ndim) for x in self.get_scalings(sigma)]
return self.inner_model(input * c_in, sigma, **kwargs) * c_out + input * c_skip
|
(inner_model, sigma_data=1.0, weighting='karras', scales=1)
|
50,867 |
k_diffusion.layers
|
__init__
| null |
def __init__(self, inner_model, sigma_data=1., weighting='karras', scales=1):
super().__init__()
self.inner_model = inner_model
self.sigma_data = sigma_data
self.scales = scales
if callable(weighting):
self.weighting = weighting
if weighting == 'karras':
self.weighting = torch.ones_like
elif weighting == 'soft-min-snr':
self.weighting = self._weighting_soft_min_snr
elif weighting == 'snr':
self.weighting = self._weighting_snr
else:
raise ValueError(f'Unknown weighting type {weighting}')
|
(self, inner_model, sigma_data=1.0, weighting='karras', scales=1)
|
50,884 |
k_diffusion.layers
|
_weighting_snr
| null |
def _weighting_snr(self, sigma):
return self.sigma_data ** 2 / (sigma ** 2 + self.sigma_data ** 2)
|
(self, sigma)
|
50,885 |
k_diffusion.layers
|
_weighting_soft_min_snr
| null |
def _weighting_soft_min_snr(self, sigma):
return (sigma * self.sigma_data) ** 2 / (sigma ** 2 + self.sigma_data ** 2) ** 2
|
(self, sigma)
|
50,899 |
k_diffusion.layers
|
forward
| null |
def forward(self, input, sigma, **kwargs):
c_skip, c_out, c_in = [utils.append_dims(x, input.ndim) for x in self.get_scalings(sigma)]
return self.inner_model(input * c_in, sigma, **kwargs) * c_out + input * c_skip
|
(self, input, sigma, **kwargs)
|
50,903 |
k_diffusion.layers
|
get_scalings
| null |
def get_scalings(self, sigma):
c_skip = self.sigma_data ** 2 / (sigma ** 2 + self.sigma_data ** 2)
c_out = sigma * self.sigma_data / (sigma ** 2 + self.sigma_data ** 2) ** 0.5
c_in = 1 / (sigma ** 2 + self.sigma_data ** 2) ** 0.5
return c_skip, c_out, c_in
|
(self, sigma)
|
50,908 |
k_diffusion.layers
|
loss
| null |
def loss(self, input, noise, sigma, **kwargs):
c_skip, c_out, c_in = [utils.append_dims(x, input.ndim) for x in self.get_scalings(sigma)]
c_weight = self.weighting(sigma)
noised_input = input + noise * utils.append_dims(sigma, input.ndim)
model_output = self.inner_model(noised_input * c_in, sigma, **kwargs)
target = (input - c_skip * noised_input) / c_out
if self.scales == 1:
return ((model_output - target) ** 2).flatten(1).mean(1) * c_weight
sq_error = dct(model_output - target) ** 2
f_weight = freq_weight_nd(sq_error.shape[2:], self.scales, dtype=sq_error.dtype, device=sq_error.device)
return (sq_error * f_weight).flatten(1).mean(1) * c_weight
|
(self, input, noise, sigma, **kwargs)
|
50,944 |
memeoverflow.imgflip
|
ImgFlip
|
Wrapper class for imgflip API interaction
:type username: str
:param username: imgflip account username
:type password: str
:param password: imgflip account password
|
class ImgFlip:
"""
Wrapper class for imgflip API interaction
:type username: str
:param username: imgflip account username
:type password: str
:param password: imgflip account password
"""
def __init__(self, *, username, password):
self._username = username
self._password = password
def __repr__(self):
return f"<ImgFlip username='{self.username}'>"
@property
def username(self):
return self._username
def make_meme(self, *, meme, text_parts):
"Generate a meme with the supplied text, and return its URL"
data = {
'username': self._username,
'password': self._password,
'template_id': MEMES[meme]['id'],
'text0': text_parts[0],
'text1': text_parts[1],
}
r = requests.post(API_URL, data=data)
try:
r.raise_for_status()
img_url = r.json()['data']['url']
return img_url
except (RequestException, JSONDecodeError, KeyError) as e:
raise ImgFlipError("Failed to make meme") from e
|
(*, username, password)
|
50,945 |
memeoverflow.imgflip
|
__init__
| null |
def __init__(self, *, username, password):
self._username = username
self._password = password
|
(self, *, username, password)
|
50,946 |
memeoverflow.imgflip
|
__repr__
| null |
def __repr__(self):
return f"<ImgFlip username='{self.username}'>"
|
(self)
|
50,947 |
memeoverflow.imgflip
|
make_meme
|
Generate a meme with the supplied text, and return its URL
|
def make_meme(self, *, meme, text_parts):
"Generate a meme with the supplied text, and return its URL"
data = {
'username': self._username,
'password': self._password,
'template_id': MEMES[meme]['id'],
'text0': text_parts[0],
'text1': text_parts[1],
}
r = requests.post(API_URL, data=data)
try:
r.raise_for_status()
img_url = r.json()['data']['url']
return img_url
except (RequestException, JSONDecodeError, KeyError) as e:
raise ImgFlipError("Failed to make meme") from e
|
(self, *, meme, text_parts)
|
50,948 |
memeoverflow.db
|
MemeDatabase
|
Wrapper for Meme database interface (sqlite)
:type site: str
:param site:
The name of the StackExchange site as an identifier (used as the table
name)
:type db_path: str
:param db_path: Path to the sqlite database file
|
class MemeDatabase:
"""
Wrapper for Meme database interface (sqlite)
:type site: str
:param site:
The name of the StackExchange site as an identifier (used as the table
name)
:type db_path: str
:param db_path: Path to the sqlite database file
"""
def __init__(self, site, db_path):
self.site = site
self.conn = sqlite3.connect(db_path)
cursor = self.conn.cursor()
cursor.execute(
f"create table if not exists {site} (question_id int unique)"
)
cursor.close()
def __repr__(self):
return f"<MemeDatabase site='{self.site}'>"
def __enter__(self):
return self
def __exit__(self, *args):
pass
def insert_question(self, id):
"Insert a question ID"
cursor = self.conn.cursor()
cursor.execute(f"insert into {self.site} values (?)", (id, ))
self.conn.commit()
cursor.close()
def question_is_known(self, id):
"""
Return True if the provided question ID is already in the database,
otherwise return False
"""
cursor = self.conn.cursor()
cursor.execute(
f"select 1 from {self.site} where question_id = ?",
(id, )
)
result = bool(cursor.fetchone())
cursor.close()
return result
|
(site, db_path)
|
50,950 |
memeoverflow.db
|
__exit__
| null |
def __exit__(self, *args):
pass
|
(self, *args)
|
50,951 |
memeoverflow.db
|
__init__
| null |
def __init__(self, site, db_path):
self.site = site
self.conn = sqlite3.connect(db_path)
cursor = self.conn.cursor()
cursor.execute(
f"create table if not exists {site} (question_id int unique)"
)
cursor.close()
|
(self, site, db_path)
|
50,952 |
memeoverflow.db
|
__repr__
| null |
def __repr__(self):
return f"<MemeDatabase site='{self.site}'>"
|
(self)
|
50,953 |
memeoverflow.db
|
insert_question
|
Insert a question ID
|
def insert_question(self, id):
"Insert a question ID"
cursor = self.conn.cursor()
cursor.execute(f"insert into {self.site} values (?)", (id, ))
self.conn.commit()
cursor.close()
|
(self, id)
|
50,954 |
memeoverflow.db
|
question_is_known
|
Return True if the provided question ID is already in the database,
otherwise return False
|
def question_is_known(self, id):
"""
Return True if the provided question ID is already in the database,
otherwise return False
"""
cursor = self.conn.cursor()
cursor.execute(
f"select 1 from {self.site} where question_id = ?",
(id, )
)
result = bool(cursor.fetchone())
cursor.close()
return result
|
(self, id)
|
50,955 |
memeoverflow.memeoverflow
|
MemeOverflow
|
Class for generating and tweeting memes of questions from a given
StackExchange site
:type twitter: dict
:param twitter:
Expected keys: con_key, con_sec, acc_tok, acc_sec (Twitter API keys)
:type imgflip: dict
:param imgflip:
Expected keys: user, pass (imgflip account)
:type stackexchange: dict
:param stackexchange:
Expected key: site (Stack Exchange site name)
Optional keys: key, user_id (Stack Exchange API key & User ID)
:type db_path: str
:param db_path:
Path to the sqlite database file
|
class MemeOverflow:
"""
Class for generating and tweeting memes of questions from a given
StackExchange site
:type twitter: dict
:param twitter:
Expected keys: con_key, con_sec, acc_tok, acc_sec (Twitter API keys)
:type imgflip: dict
:param imgflip:
Expected keys: user, pass (imgflip account)
:type stackexchange: dict
:param stackexchange:
Expected key: site (Stack Exchange site name)
Optional keys: key, user_id (Stack Exchange API key & User ID)
:type db_path: str
:param db_path:
Path to the sqlite database file
"""
def __init__(self, twitter, imgflip, stackexchange, db_path):
self.site = stackexchange['site']
self.stackexchange = StackExchange(**stackexchange)
self.imgflip = ImgFlip(**imgflip)
self.twitter = Twitter(**twitter)
self.db = MemeDatabase(site=self.site, db_path=db_path)
def __repr__(self):
return f"<MemeOverflow site='{self.site}'>"
def __call__(self):
"""
Main loop - get questions, make memes and tweet them, with sensible
pauses
"""
questions = self.get_se_questions()
if questions:
for q in questions:
tweeted = self.generate_meme_and_tweet(q)
if tweeted:
sleep(60*5)
else:
sleep(60)
else:
sleep(60*5)
def get_se_questions(self, n=100):
"""
Retreive n questions from the StackExchange site and return as a list,
filtering out any known questions.
"""
try:
questions = self.stackexchange.get_questions(n=n)
except StackExchangeError as e:
logger.exception(e)
return
return [
q
for q in questions
if not self.db.question_is_known(q['question_id'])
]
def choose_meme_template(self, text):
"""
Choose a meme for the supplied text. If the text fits one of the
templates well, it will use that one, otherwise it will be random. If
text does not work with randomly chosen template, this method will be
called again. Some templates move text to the second row or add their
own second row of text to complete the meme.
Return (meme_name, text_parts)
"""
if text.lower().startswith("is this "):
meme = 'IS_THIS_A_PIGEON'
text = text[8:]
elif 'possible' in text.lower() and text.endswith('?'):
meme = 'WELL_YES_BUT_ACTUALLY_NO'
elif text.count('"') == 2:
meme = 'DR_EVIL_LASER'
elif text.lower().startswith('if') and text.endswith('?'):
meme = 'PHILOSORAPTOR'
else:
# don't allow these to be picked at random
special_memes = {
'IS_THIS_A_PIGEON',
'WELL_YES_BUT_ACTUALLY_NO',
'DR_EVIL_LASER',
'PHILOSORAPTOR',
}
if text.endswith('?'):
special_memes |= {
'BUT_THATS_NONE_OF_MY_BUSINESS',
'CHANGE_MY_MIND',
'ANCIENT_ALIENS',
'AND_EVERYBODY_LOSES_THEIR_MINDS',
}
else:
special_memes |= {
'GRUMPY_CAT',
}
meme = random.choice(list(set(MEMES.keys()) - special_memes))
text_parts = self.place_text(meme, text)
return (meme, text_parts)
def place_text(self, meme, text):
"""
Decide where the given text should go on the given meme template, including any
template-specific text. Return a 2-tuple of strings.
"""
meme_dict = copy.deepcopy(MEMES[meme])
text_location = meme_dict['text_location']
meme_dict[text_location] = text
return (meme_dict['text0'], meme_dict['text1'])
def generate_meme_and_tweet(self, question):
"""
For the given question, if it's not known:
- generate meme
- tweet it
- add to database
Return True on success, False on fail or question was known
"""
question_title = html.unescape(question['title'])
question_url = self.stackexchange.get_question_url(question['link'])
question_id = question['question_id']
tags = tags_to_hashtags(question['tags'])
status = f"{question_title} {question_url} {tags}"
if len(status) > 240:
status = f"{question_title} {question_url}"
logger.info("Tweet too long - removing tags")
meme, text_parts = self.choose_meme_template(question_title)
try:
img_url = self.imgflip.make_meme(meme=meme, text_parts=text_parts)
except ImgFlipError as e:
logger.exception(e)
return False
try:
img_bytes = download_image_bytes(img_url)
except RequestException:
logger.exception("Failed to download image")
return False
try:
self.twitter.tweet_with_image(status, img_bytes)
logger.info(f"Tweeted: {question_title} [{meme}]")
except TwitterError:
logger.exception(e)
return False
self.db.insert_question(question_id)
return True
|
(twitter, imgflip, stackexchange, db_path)
|
50,956 |
memeoverflow.memeoverflow
|
__call__
|
Main loop - get questions, make memes and tweet them, with sensible
pauses
|
def __call__(self):
"""
Main loop - get questions, make memes and tweet them, with sensible
pauses
"""
questions = self.get_se_questions()
if questions:
for q in questions:
tweeted = self.generate_meme_and_tweet(q)
if tweeted:
sleep(60*5)
else:
sleep(60)
else:
sleep(60*5)
|
(self)
|
50,957 |
memeoverflow.memeoverflow
|
__init__
| null |
def __init__(self, twitter, imgflip, stackexchange, db_path):
self.site = stackexchange['site']
self.stackexchange = StackExchange(**stackexchange)
self.imgflip = ImgFlip(**imgflip)
self.twitter = Twitter(**twitter)
self.db = MemeDatabase(site=self.site, db_path=db_path)
|
(self, twitter, imgflip, stackexchange, db_path)
|
50,958 |
memeoverflow.memeoverflow
|
__repr__
| null |
def __repr__(self):
return f"<MemeOverflow site='{self.site}'>"
|
(self)
|
50,959 |
memeoverflow.memeoverflow
|
choose_meme_template
|
Choose a meme for the supplied text. If the text fits one of the
templates well, it will use that one, otherwise it will be random. If
text does not work with randomly chosen template, this method will be
called again. Some templates move text to the second row or add their
own second row of text to complete the meme.
Return (meme_name, text_parts)
|
def choose_meme_template(self, text):
"""
Choose a meme for the supplied text. If the text fits one of the
templates well, it will use that one, otherwise it will be random. If
text does not work with randomly chosen template, this method will be
called again. Some templates move text to the second row or add their
own second row of text to complete the meme.
Return (meme_name, text_parts)
"""
if text.lower().startswith("is this "):
meme = 'IS_THIS_A_PIGEON'
text = text[8:]
elif 'possible' in text.lower() and text.endswith('?'):
meme = 'WELL_YES_BUT_ACTUALLY_NO'
elif text.count('"') == 2:
meme = 'DR_EVIL_LASER'
elif text.lower().startswith('if') and text.endswith('?'):
meme = 'PHILOSORAPTOR'
else:
# don't allow these to be picked at random
special_memes = {
'IS_THIS_A_PIGEON',
'WELL_YES_BUT_ACTUALLY_NO',
'DR_EVIL_LASER',
'PHILOSORAPTOR',
}
if text.endswith('?'):
special_memes |= {
'BUT_THATS_NONE_OF_MY_BUSINESS',
'CHANGE_MY_MIND',
'ANCIENT_ALIENS',
'AND_EVERYBODY_LOSES_THEIR_MINDS',
}
else:
special_memes |= {
'GRUMPY_CAT',
}
meme = random.choice(list(set(MEMES.keys()) - special_memes))
text_parts = self.place_text(meme, text)
return (meme, text_parts)
|
(self, text)
|
50,960 |
memeoverflow.memeoverflow
|
generate_meme_and_tweet
|
For the given question, if it's not known:
- generate meme
- tweet it
- add to database
Return True on success, False on fail or question was known
|
def generate_meme_and_tweet(self, question):
"""
For the given question, if it's not known:
- generate meme
- tweet it
- add to database
Return True on success, False on fail or question was known
"""
question_title = html.unescape(question['title'])
question_url = self.stackexchange.get_question_url(question['link'])
question_id = question['question_id']
tags = tags_to_hashtags(question['tags'])
status = f"{question_title} {question_url} {tags}"
if len(status) > 240:
status = f"{question_title} {question_url}"
logger.info("Tweet too long - removing tags")
meme, text_parts = self.choose_meme_template(question_title)
try:
img_url = self.imgflip.make_meme(meme=meme, text_parts=text_parts)
except ImgFlipError as e:
logger.exception(e)
return False
try:
img_bytes = download_image_bytes(img_url)
except RequestException:
logger.exception("Failed to download image")
return False
try:
self.twitter.tweet_with_image(status, img_bytes)
logger.info(f"Tweeted: {question_title} [{meme}]")
except TwitterError:
logger.exception(e)
return False
self.db.insert_question(question_id)
return True
|
(self, question)
|
50,961 |
memeoverflow.memeoverflow
|
get_se_questions
|
Retreive n questions from the StackExchange site and return as a list,
filtering out any known questions.
|
def get_se_questions(self, n=100):
"""
Retreive n questions from the StackExchange site and return as a list,
filtering out any known questions.
"""
try:
questions = self.stackexchange.get_questions(n=n)
except StackExchangeError as e:
logger.exception(e)
return
return [
q
for q in questions
if not self.db.question_is_known(q['question_id'])
]
|
(self, n=100)
|
50,962 |
memeoverflow.memeoverflow
|
place_text
|
Decide where the given text should go on the given meme template, including any
template-specific text. Return a 2-tuple of strings.
|
def place_text(self, meme, text):
"""
Decide where the given text should go on the given meme template, including any
template-specific text. Return a 2-tuple of strings.
"""
meme_dict = copy.deepcopy(MEMES[meme])
text_location = meme_dict['text_location']
meme_dict[text_location] = text
return (meme_dict['text0'], meme_dict['text1'])
|
(self, meme, text)
|
50,963 |
memeoverflow.stackexchange
|
StackExchange
|
Wrapper class for Stack Exchange API calls
:type site: str
:param site: Stack Exchange site name
:type key: str or None
:param key:
Stack Exchange API key (optional) - if not provided, a stricter usage
limit will apply
:type user_id: str or None
:param user_id:
Stack Exchange user ID (optional) - if provided, will be used to create
URLs with a referral code
|
class StackExchange:
"""
Wrapper class for Stack Exchange API calls
:type site: str
:param site: Stack Exchange site name
:type key: str or None
:param key:
Stack Exchange API key (optional) - if not provided, a stricter usage
limit will apply
:type user_id: str or None
:param user_id:
Stack Exchange user ID (optional) - if provided, will be used to create
URLs with a referral code
"""
def __init__(self, *, site, key=None, user_id=None):
self.site = site
self.key = key
self.user_id = user_id
if self.key is None:
warnings.warn(
"No StackExchange API key provided, limited use may apply",
StackExchangeNoKeyWarning,
)
def __repr__(self):
return f"<StackExchange site='{self.site}'>"
def get_questions(self, n=100):
"Retreive n questions from the StackExchange site and return as a list"
params = {
'pagesize': n,
'site': self.site,
'key': self.key,
}
r = requests.get(API_URL, params)
try:
r.raise_for_status()
return r.json()['items']
except (RequestException, JSONDecodeError, KeyError) as e:
raise StackExchangeError(
"Failed to retrieve questions from Stack Exchange"
) from e
def get_question_url(self, url):
"""
Return the URL with referral code if provided, otherwise return the
normal link
e.g. with referral: /questions/98765/12345
without: /questions/98765/question-title
"""
if self.user_id:
return '/'.join(url.split('/')[:-1] + [str(self.user_id)])
return url
|
(*, site, key=None, user_id=None)
|
50,964 |
memeoverflow.stackexchange
|
__init__
| null |
def __init__(self, *, site, key=None, user_id=None):
self.site = site
self.key = key
self.user_id = user_id
if self.key is None:
warnings.warn(
"No StackExchange API key provided, limited use may apply",
StackExchangeNoKeyWarning,
)
|
(self, *, site, key=None, user_id=None)
|
50,965 |
memeoverflow.stackexchange
|
__repr__
| null |
def __repr__(self):
return f"<StackExchange site='{self.site}'>"
|
(self)
|
50,966 |
memeoverflow.stackexchange
|
get_question_url
|
Return the URL with referral code if provided, otherwise return the
normal link
e.g. with referral: /questions/98765/12345
without: /questions/98765/question-title
|
def get_question_url(self, url):
"""
Return the URL with referral code if provided, otherwise return the
normal link
e.g. with referral: /questions/98765/12345
without: /questions/98765/question-title
"""
if self.user_id:
return '/'.join(url.split('/')[:-1] + [str(self.user_id)])
return url
|
(self, url)
|
50,967 |
memeoverflow.stackexchange
|
get_questions
|
Retreive n questions from the StackExchange site and return as a list
|
def get_questions(self, n=100):
"Retreive n questions from the StackExchange site and return as a list"
params = {
'pagesize': n,
'site': self.site,
'key': self.key,
}
r = requests.get(API_URL, params)
try:
r.raise_for_status()
return r.json()['items']
except (RequestException, JSONDecodeError, KeyError) as e:
raise StackExchangeError(
"Failed to retrieve questions from Stack Exchange"
) from e
|
(self, n=100)
|
50,968 |
memeoverflow.twitter
|
Twitter
|
Wrapper class for Twitter API calls
:type con_key: str
:param con_key: Twitter API consumer key
:type con_sec: str
:param con_sec: Twitter API consumer secret
:type acc_key: str
:param acc_key: Twitter API access key
:type acc_sec: str
:param acc_sec: Twitter API access secret
|
class Twitter:
"""
Wrapper class for Twitter API calls
:type con_key: str
:param con_key: Twitter API consumer key
:type con_sec: str
:param con_sec: Twitter API consumer secret
:type acc_key: str
:param acc_key: Twitter API access key
:type acc_sec: str
:param acc_sec: Twitter API access secret
"""
def __init__(self, con_key, con_sec, acc_tok, acc_sec):
self.twython = Twython(con_key, con_sec, acc_tok, acc_sec)
def __repr__(self):
return "<Twitter>"
def tweet_with_image(self, status, img_bytes):
"Tweet status with the image attached"
try:
response = self.twython.upload_media(media=img_bytes)
media_ids = [response['media_id']]
self.twython.update_status(status=status, media_ids=media_ids)
except TwythonError as e:
raise TwitterError from e
|
(con_key, con_sec, acc_tok, acc_sec)
|
50,969 |
memeoverflow.twitter
|
__init__
| null |
def __init__(self, con_key, con_sec, acc_tok, acc_sec):
self.twython = Twython(con_key, con_sec, acc_tok, acc_sec)
|
(self, con_key, con_sec, acc_tok, acc_sec)
|
50,970 |
memeoverflow.twitter
|
__repr__
| null |
def __repr__(self):
return "<Twitter>"
|
(self)
|
50,971 |
memeoverflow.twitter
|
tweet_with_image
|
Tweet status with the image attached
|
def tweet_with_image(self, status, img_bytes):
"Tweet status with the image attached"
try:
response = self.twython.upload_media(media=img_bytes)
media_ids = [response['media_id']]
self.twython.update_status(status=status, media_ids=media_ids)
except TwythonError as e:
raise TwitterError from e
|
(self, status, img_bytes)
|
50,979 |
Cython.Shadow
|
ArrayType
| null |
class ArrayType(PointerType):
def __init__(self, value=None):
if value is None:
self._items = [None] * self._n
else:
super(ArrayType, self).__init__(value)
|
(value=None)
|
50,980 |
Cython.Shadow
|
__eq__
| null |
def __eq__(self, value):
if value is None and not self._items:
return True
elif type(self) != type(value):
return False
else:
return not self._items and not value._items
|
(self, value)
|
50,981 |
Cython.Shadow
|
__getitem__
| null |
def __getitem__(self, ix):
if ix < 0:
raise IndexError("negative indexing not allowed in C")
return self._items[ix]
|
(self, ix)
|
50,982 |
Cython.Shadow
|
__init__
| null |
def __init__(self, value=None):
if value is None:
self._items = [None] * self._n
else:
super(ArrayType, self).__init__(value)
|
(self, value=None)
|
50,983 |
Cython.Shadow
|
__repr__
| null |
def __repr__(self):
return "%s *" % (self._basetype,)
|
(self)
|
50,984 |
Cython.Shadow
|
__setitem__
| null |
def __setitem__(self, ix, value):
if ix < 0:
raise IndexError("negative indexing not allowed in C")
self._items[ix] = cast(self._basetype, value)
|
(self, ix, value)
|
50,985 |
Cython.Shadow
|
_pointer
| null |
def _pointer(self, n=1):
for i in range(n):
self = pointer(self)
return self
|
(self, n=1)
|
50,986 |
Cython.Shadow
|
CythonCImports
|
Simplistic module mock to make cimports sort-of work in Python code.
|
class CythonCImports(object):
"""
Simplistic module mock to make cimports sort-of work in Python code.
"""
def __init__(self, module):
self.__path__ = []
self.__file__ = None
self.__name__ = module
self.__package__ = module
def __getattr__(self, item):
if item.startswith('__') and item.endswith('__'):
raise AttributeError(item)
try:
return __import__(item)
except ImportError:
import sys
ex = AttributeError(item)
if sys.version_info >= (3, 0):
ex.__cause__ = None
raise ex
|
(module)
|
50,987 |
Cython.Shadow
|
__getattr__
| null |
def __getattr__(self, item):
if item.startswith('__') and item.endswith('__'):
raise AttributeError(item)
try:
return __import__(item)
except ImportError:
import sys
ex = AttributeError(item)
if sys.version_info >= (3, 0):
ex.__cause__ = None
raise ex
|
(self, item)
|
50,988 |
Cython.Shadow
|
__init__
| null |
def __init__(self, module):
self.__path__ = []
self.__file__ = None
self.__name__ = module
self.__package__ = module
|
(self, module)
|
50,989 |
Cython.Shadow
|
CythonDotImportedFromElsewhere
|
cython.dataclasses just shadows the standard library modules of the same name
|
class CythonDotImportedFromElsewhere(object):
"""
cython.dataclasses just shadows the standard library modules of the same name
"""
def __init__(self, module):
self.__path__ = []
self.__file__ = None
self.__name__ = module
self.__package__ = module
def __getattr__(self, attr):
# we typically only expect this to be called once
from importlib import import_module
import sys
try:
mod = import_module(self.__name__)
except ImportError:
# but if they don't exist (Python is not sufficiently up-to-date) then
# you can't use them
raise AttributeError("%s: the standard library module %s is not available" %
(attr, self.__name__))
sys.modules['cython.%s' % self.__name__] = mod
return getattr(mod, attr)
|
(module)
|
50,990 |
Cython.Shadow
|
__getattr__
| null |
def __getattr__(self, attr):
# we typically only expect this to be called once
from importlib import import_module
import sys
try:
mod = import_module(self.__name__)
except ImportError:
# but if they don't exist (Python is not sufficiently up-to-date) then
# you can't use them
raise AttributeError("%s: the standard library module %s is not available" %
(attr, self.__name__))
sys.modules['cython.%s' % self.__name__] = mod
return getattr(mod, attr)
|
(self, attr)
|
50,992 |
Cython.Shadow
|
CythonDotParallel
|
The cython.parallel module.
|
class CythonDotParallel(object):
"""
The cython.parallel module.
"""
__all__ = ['parallel', 'prange', 'threadid']
def parallel(self, num_threads=None):
return nogil
def prange(self, start=0, stop=None, step=1, nogil=False, schedule=None, chunksize=None, num_threads=None):
if stop is None:
stop = start
start = 0
return range(start, stop, step)
def threadid(self):
return 0
# def threadsavailable(self):
# return 1
|
()
|
50,993 |
Cython.Shadow
|
parallel
| null |
def parallel(self, num_threads=None):
return nogil
|
(self, num_threads=None)
|
50,994 |
Cython.Shadow
|
prange
| null |
def prange(self, start=0, stop=None, step=1, nogil=False, schedule=None, chunksize=None, num_threads=None):
if stop is None:
stop = start
start = 0
return range(start, stop, step)
|
(self, start=0, stop=None, step=1, nogil=False, schedule=None, chunksize=None, num_threads=None)
|
50,995 |
Cython.Shadow
|
threadid
| null |
def threadid(self):
return 0
# def threadsavailable(self):
# return 1
|
(self)
|
50,996 |
Cython.Shadow
|
CythonMetaType
| null |
class CythonMetaType(type):
def __getitem__(type, ix):
return array(type, ix)
| null |
50,997 |
Cython.Shadow
|
__getitem__
| null |
def __getitem__(type, ix):
return array(type, ix)
|
(type, ix)
|
50,998 |
Cython.Shadow
|
CythonType
| null |
class CythonType(CythonTypeObject):
def _pointer(self, n=1):
for i in range(n):
self = pointer(self)
return self
|
()
|
51,000 |
Cython.Shadow
|
CythonTypeObject
| null |
from Cython.Shadow import CythonTypeObject
|
()
|
51,001 |
Cython.Shadow
|
PointerType
| null |
class PointerType(CythonType):
def __init__(self, value=None):
if isinstance(value, (ArrayType, PointerType)):
self._items = [cast(self._basetype, a) for a in value._items]
elif isinstance(value, list):
self._items = [cast(self._basetype, a) for a in value]
elif value is None or value == 0:
self._items = []
else:
raise ValueError
def __getitem__(self, ix):
if ix < 0:
raise IndexError("negative indexing not allowed in C")
return self._items[ix]
def __setitem__(self, ix, value):
if ix < 0:
raise IndexError("negative indexing not allowed in C")
self._items[ix] = cast(self._basetype, value)
def __eq__(self, value):
if value is None and not self._items:
return True
elif type(self) != type(value):
return False
else:
return not self._items and not value._items
def __repr__(self):
return "%s *" % (self._basetype,)
|
(value=None)
|
51,004 |
Cython.Shadow
|
__init__
| null |
def __init__(self, value=None):
if isinstance(value, (ArrayType, PointerType)):
self._items = [cast(self._basetype, a) for a in value._items]
elif isinstance(value, list):
self._items = [cast(self._basetype, a) for a in value]
elif value is None or value == 0:
self._items = []
else:
raise ValueError
|
(self, value=None)
|
51,008 |
Cython.Shadow
|
StructType
| null |
class StructType(CythonType):
def __init__(self, *posargs, **data):
if not (posargs or data):
return
if posargs and data:
raise ValueError('Cannot accept both positional and keyword arguments.')
# Allow 'cast_from' as single positional or keyword argument.
if data and len(data) == 1 and 'cast_from' in data:
cast_from = data.pop('cast_from')
elif len(posargs) == 1 and type(posargs[0]) is type(self):
cast_from, posargs = posargs[0], ()
elif posargs:
for key, arg in zip(self._members, posargs):
setattr(self, key, arg)
return
else:
for key, value in data.items():
if key not in self._members:
raise ValueError("Invalid struct attribute for %s: %s" % (
self.__class__.__name__, key))
setattr(self, key, value)
return
# do cast
if data:
raise ValueError('Cannot accept keyword arguments when casting.')
if type(cast_from) is not type(self):
raise ValueError('Cannot cast from %s' % cast_from)
for key, value in cast_from.__dict__.items():
setattr(self, key, value)
def __setattr__(self, key, value):
if key in self._members:
self.__dict__[key] = cast(self._members[key], value)
else:
raise AttributeError("Struct has no member '%s'" % key)
|
(*posargs, **data)
|
51,009 |
Cython.Shadow
|
__init__
| null |
def __init__(self, *posargs, **data):
if not (posargs or data):
return
if posargs and data:
raise ValueError('Cannot accept both positional and keyword arguments.')
# Allow 'cast_from' as single positional or keyword argument.
if data and len(data) == 1 and 'cast_from' in data:
cast_from = data.pop('cast_from')
elif len(posargs) == 1 and type(posargs[0]) is type(self):
cast_from, posargs = posargs[0], ()
elif posargs:
for key, arg in zip(self._members, posargs):
setattr(self, key, arg)
return
else:
for key, value in data.items():
if key not in self._members:
raise ValueError("Invalid struct attribute for %s: %s" % (
self.__class__.__name__, key))
setattr(self, key, value)
return
# do cast
if data:
raise ValueError('Cannot accept keyword arguments when casting.')
if type(cast_from) is not type(self):
raise ValueError('Cannot cast from %s' % cast_from)
for key, value in cast_from.__dict__.items():
setattr(self, key, value)
|
(self, *posargs, **data)
|
51,010 |
Cython.Shadow
|
__setattr__
| null |
def __setattr__(self, key, value):
if key in self._members:
self.__dict__[key] = cast(self._members[key], value)
else:
raise AttributeError("Struct has no member '%s'" % key)
|
(self, key, value)
|
51,012 |
Cython.Shadow
|
UnionType
| null |
class UnionType(CythonType):
def __init__(self, cast_from=_Unspecified, **data):
if cast_from is not _Unspecified:
# do type cast
if len(data) > 0:
raise ValueError('Cannot accept keyword arguments when casting.')
if isinstance(cast_from, dict):
datadict = cast_from
elif type(cast_from) is type(self):
datadict = cast_from.__dict__
else:
raise ValueError('Cannot cast from %s' % cast_from)
else:
datadict = data
if len(datadict) > 1:
raise AttributeError("Union can only store one field at a time.")
for key, value in datadict.items():
setattr(self, key, value)
def __setattr__(self, key, value):
if key == '__dict__':
CythonType.__setattr__(self, key, value)
elif key in self._members:
self.__dict__ = {key: cast(self._members[key], value)}
else:
raise AttributeError("Union has no member '%s'" % key)
|
(cast_from=<object object at 0x7f478e311940>, **data)
|
51,013 |
Cython.Shadow
|
__init__
| null |
def __init__(self, cast_from=_Unspecified, **data):
if cast_from is not _Unspecified:
# do type cast
if len(data) > 0:
raise ValueError('Cannot accept keyword arguments when casting.')
if isinstance(cast_from, dict):
datadict = cast_from
elif type(cast_from) is type(self):
datadict = cast_from.__dict__
else:
raise ValueError('Cannot cast from %s' % cast_from)
else:
datadict = data
if len(datadict) > 1:
raise AttributeError("Union can only store one field at a time.")
for key, value in datadict.items():
setattr(self, key, value)
|
(self, cast_from=<object object at 0x7f478e311940>, **data)
|
51,014 |
Cython.Shadow
|
__setattr__
| null |
def __setattr__(self, key, value):
if key == '__dict__':
CythonType.__setattr__(self, key, value)
elif key in self._members:
self.__dict__ = {key: cast(self._members[key], value)}
else:
raise AttributeError("Union has no member '%s'" % key)
|
(self, key, value)
|
51,016 |
Cython.Shadow
|
address
| null |
def address(arg):
return pointer(type(arg))([arg])
|
(arg)
|
51,017 |
Cython.Shadow
|
<lambda>
| null |
lambda _: _EmptyDecoratorAndManager()
|
(_)
|
51,020 |
Cython.Shadow
|
array
| null |
def array(basetype, n):
class ArrayInstance(ArrayType):
_basetype = basetype
_n = n
return ArrayInstance
|
(basetype, n)
|
51,024 |
Cython.Shadow
|
<lambda>
| null |
binding = lambda _: _empty_decorator
|
(_)
|
51,028 |
Cython.Shadow
|
cast
| null |
def cast(t, *args, **kwargs):
kwargs.pop('typecheck', None)
assert not kwargs
if isinstance(t, typedef):
return t(*args)
elif isinstance(t, type): # Doesn't work with old-style classes of Python 2.x
if len(args) != 1 or not (args[0] is None or isinstance(args[0], t)):
return t(*args)
return args[0]
|
(t, *args, **kwargs)
|
51,029 |
Cython.Shadow
|
cdiv
| null |
def cdiv(a, b):
if a < 0:
a = -a
b = -b
if b < 0:
return (a + b + 1) // b
return a // b
|
(a, b)
|
51,032 |
Cython.Shadow
|
cmod
| null |
def cmod(a, b):
r = a % b
if (a * b) < 0 and r:
r -= b
return r
|
(a, b)
|
51,033 |
Cython.Shadow
|
compile
| null |
def compile(f):
from Cython.Build.Inline import RuntimeCompiledFunction
return RuntimeCompiledFunction(f)
|
(f)
|
51,036 |
Cython.Shadow
|
declare
| null |
def declare(t=None, value=_Unspecified, **kwds):
if value is not _Unspecified:
return cast(t, value)
elif _is_value_type(t):
return t()
else:
return None
|
(t=None, value=<object object at 0x7f478e311940>, **kwds)
|
51,038 |
Cython.Shadow
|
<lambda>
| null |
exceptval = lambda _=None, check=True: _EmptyDecoratorAndManager()
|
(_=None, check=True)
|
51,039 |
Cython.Shadow
|
<lambda>
| null |
fast_getattr = lambda _: _EmptyDecoratorAndManager()
|
(_)
|
51,040 |
Cython.Shadow
|
_empty_decorator
| null |
def _empty_decorator(x):
return x
|
(x)
|
51,042 |
Cython.Shadow
|
fused_type
| null |
def fused_type(*args):
if not args:
raise TypeError("Expected at least one type as argument")
# Find the numeric type with biggest rank if all types are numeric
rank = -1
for type in args:
if type not in (py_int, py_long, py_float, py_complex):
break
if type_ordering.index(type) > rank:
result_type = type
else:
return result_type
# Not a simple numeric type, return a fused type instance. The result
# isn't really meant to be used, as we can't keep track of the context in
# pure-mode. Casting won't do anything in this case.
return _FusedType()
|
(*args)
|
51,043 |
Cython.Shadow
|
index_type
|
Support array type creation by slicing, e.g. double[:, :] specifies
a 2D strided array of doubles. The syntax is the same as for
Cython memoryviews.
|
def index_type(base_type, item):
"""
Support array type creation by slicing, e.g. double[:, :] specifies
a 2D strided array of doubles. The syntax is the same as for
Cython memoryviews.
"""
class InvalidTypeSpecification(Exception):
pass
def verify_slice(s):
if s.start or s.stop or s.step not in (None, 1):
raise InvalidTypeSpecification(
"Only a step of 1 may be provided to indicate C or "
"Fortran contiguity")
if isinstance(item, tuple):
step_idx = None
for idx, s in enumerate(item):
verify_slice(s)
if s.step and (step_idx or idx not in (0, len(item) - 1)):
raise InvalidTypeSpecification(
"Step may only be provided once, and only in the "
"first or last dimension.")
if s.step == 1:
step_idx = idx
return _ArrayType(base_type, len(item),
is_c_contig=step_idx == len(item) - 1,
is_f_contig=step_idx == 0)
elif isinstance(item, slice):
verify_slice(item)
return _ArrayType(base_type, 1, is_c_contig=bool(item.step))
else:
# int[8] etc.
assert int(item) == item # array size must be a plain integer
return array(base_type, item)
|
(base_type, item)
|
51,046 |
Cython.Shadow
|
inline
| null |
def inline(f, *args, **kwds):
if isinstance(f, basestring):
global _cython_inline
if _cython_inline is None:
from Cython.Build.Inline import cython_inline as _cython_inline
return _cython_inline(f, *args, **kwds)
else:
assert len(args) == len(kwds) == 0
return f
|
(f, *args, **kwds)
|
51,050 |
Cython
|
load_ipython_extension
|
Load the extension in IPython.
|
def load_ipython_extension(ip):
"""Load the extension in IPython."""
from .Build.IpythonMagic import CythonMagics # pylint: disable=cyclic-import
ip.register_magics(CythonMagics)
|
(ip)
|
51,051 |
Cython.Shadow
|
locals
| null |
def locals(**arg_types):
return _empty_decorator
|
(**arg_types)
|
51,055 |
Cython.Shadow
|
<lambda>
| null |
overflowcheck = lambda _: _EmptyDecoratorAndManager()
|
(_)
|
51,056 |
Cython.Shadow
|
PointerInstance
| null |
def pointer(basetype):
class PointerInstance(PointerType):
_basetype = basetype
return PointerInstance
|
(value=None)
|
51,734 |
Cython.Shadow
|
sizeof
| null |
def sizeof(arg):
return 1
|
(arg)
|
51,735 |
Cython.Shadow
|
struct
| null |
def struct(**members):
class StructInstance(StructType):
_members = members
for key in members:
setattr(StructInstance, key, None)
return StructInstance
|
(**members)
|
51,736 |
Cython.Shadow
|
test_assert_path_exists
| null |
def test_assert_path_exists(*paths):
return _empty_decorator
|
(*paths)
|
51,737 |
Cython.Shadow
|
test_fail_if_path_exists
| null |
def test_fail_if_path_exists(*paths):
return _empty_decorator
|
(*paths)
|
51,741 |
Cython.Shadow
|
typedef
| null |
class typedef(CythonType):
def __init__(self, type, name=None):
self._basetype = type
self.name = name
def __call__(self, *arg):
value = cast(self._basetype, *arg)
return value
def __repr__(self):
return self.name or str(self._basetype)
__getitem__ = index_type
|
(type, name=None)
|
51,742 |
Cython.Shadow
|
__call__
| null |
def __call__(self, *arg):
value = cast(self._basetype, *arg)
return value
|
(self, *arg)
|
51,744 |
Cython.Shadow
|
__init__
| null |
def __init__(self, type, name=None):
self._basetype = type
self.name = name
|
(self, type, name=None)
|
51,745 |
Cython.Shadow
|
__repr__
| null |
def __repr__(self):
return self.name or str(self._basetype)
|
(self)
|
51,747 |
Cython.Shadow
|
typeof
| null |
def typeof(arg):
return arg.__class__.__name__
# return type(arg)
|
(arg)
|
51,749 |
Cython.Shadow
|
union
| null |
def union(**members):
class UnionInstance(UnionType):
_members = members
for key in members:
setattr(UnionInstance, key, None)
return UnionInstance
|
(**members)
|
51,751 |
Cython.Shadow
|
warn
| null |
class warn:
undeclared = unreachable = maybe_uninitialized = unused = \
unused_arg = unused_result = \
lambda _: _EmptyDecoratorAndManager()
|
()
|
51,759 |
dictknife.accessing
|
Accessor
| null |
class Accessor:
def __init__(self, make_dict=make_dict, zero_value=None):
self.make_dict = make_dict
self.zero_value = zero_value
def assign(self, d, path, value):
original = d
for name in path[:-1]:
try:
d = d[name]
except IndexError:
for i in range(len(d), int(name) + 1):
d.append(self.make_dict())
d = d[name]
except KeyError:
d[name] = self.make_dict()
d = d[name]
try:
d[path[-1]] = value
except TypeError:
d = self.make_dict()
self.assign(original, path[:-1], d)
d[path[-1]] = value
except IndexError:
for i in range(len(d), path[-1] + 1):
d.append(self.zero_value)
d[path[-1]] = value
def access(self, d, path):
for name in path:
try:
d = d[name]
except TypeError:
if not isinstance(d, (list, tuple)):
raise
d = d[int(name)]
return d
def maybe_remove(self, d, path):
container = self.maybe_access_container(d, path)
if container is not None:
container.pop(path[-1])
def exists(self, d, path):
return self.maybe_access_container(d, path) is not None
def maybe_access(self, d, path, *, default=None):
if d is None:
return default
d = self.maybe_access_container(d, path, default=default)
if d is default:
return default
return d[path[-1]]
def maybe_access_container(self, d, path, *, default=None):
for name in path[:-1]:
try:
d = d[name]
except KeyError:
return default
except TypeError:
if d is None:
return default
if not isinstance(d, (list, tuple)):
raise
d = d[int(name)]
try:
d[path[-1]]
return d
except (KeyError, IndexError):
return default
except TypeError:
if d is None:
return default
if not isinstance(d, (list, tuple)):
raise
return default
|
(make_dict=<class 'dict'>, zero_value=None)
|
51,760 |
dictknife.accessing
|
__init__
| null |
def __init__(self, make_dict=make_dict, zero_value=None):
self.make_dict = make_dict
self.zero_value = zero_value
|
(self, make_dict=<class 'dict'>, zero_value=None)
|
51,761 |
dictknife.accessing
|
access
| null |
def access(self, d, path):
for name in path:
try:
d = d[name]
except TypeError:
if not isinstance(d, (list, tuple)):
raise
d = d[int(name)]
return d
|
(self, d, path)
|
51,762 |
dictknife.accessing
|
assign
| null |
def assign(self, d, path, value):
original = d
for name in path[:-1]:
try:
d = d[name]
except IndexError:
for i in range(len(d), int(name) + 1):
d.append(self.make_dict())
d = d[name]
except KeyError:
d[name] = self.make_dict()
d = d[name]
try:
d[path[-1]] = value
except TypeError:
d = self.make_dict()
self.assign(original, path[:-1], d)
d[path[-1]] = value
except IndexError:
for i in range(len(d), path[-1] + 1):
d.append(self.zero_value)
d[path[-1]] = value
|
(self, d, path, value)
|
51,763 |
dictknife.accessing
|
exists
| null |
def exists(self, d, path):
return self.maybe_access_container(d, path) is not None
|
(self, d, path)
|
51,764 |
dictknife.accessing
|
maybe_access
| null |
def maybe_access(self, d, path, *, default=None):
if d is None:
return default
d = self.maybe_access_container(d, path, default=default)
if d is default:
return default
return d[path[-1]]
|
(self, d, path, *, default=None)
|
51,765 |
dictknife.accessing
|
maybe_access_container
| null |
def maybe_access_container(self, d, path, *, default=None):
for name in path[:-1]:
try:
d = d[name]
except KeyError:
return default
except TypeError:
if d is None:
return default
if not isinstance(d, (list, tuple)):
raise
d = d[int(name)]
try:
d[path[-1]]
return d
except (KeyError, IndexError):
return default
except TypeError:
if d is None:
return default
if not isinstance(d, (list, tuple)):
raise
return default
|
(self, d, path, *, default=None)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.