repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
xapple/plumbing | plumbing/graphs.py | Graph.plot_and_save | def plot_and_save(self, **kwargs):
"""Used when the plot method defined does not create a figure nor calls save_plot
Then the plot method has to use self.fig"""
self.fig = pyplot.figure()
self.plot()
self.axes = pyplot.gca()
self.save_plot(self.fig, self.axes, **kwargs)
... | python | def plot_and_save(self, **kwargs):
"""Used when the plot method defined does not create a figure nor calls save_plot
Then the plot method has to use self.fig"""
self.fig = pyplot.figure()
self.plot()
self.axes = pyplot.gca()
self.save_plot(self.fig, self.axes, **kwargs)
... | [
"def",
"plot_and_save",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"fig",
"=",
"pyplot",
".",
"figure",
"(",
")",
"self",
".",
"plot",
"(",
")",
"self",
".",
"axes",
"=",
"pyplot",
".",
"gca",
"(",
")",
"self",
".",
"save_plot",... | Used when the plot method defined does not create a figure nor calls save_plot
Then the plot method has to use self.fig | [
"Used",
"when",
"the",
"plot",
"method",
"defined",
"does",
"not",
"create",
"a",
"figure",
"nor",
"calls",
"save_plot",
"Then",
"the",
"plot",
"method",
"has",
"to",
"use",
"self",
".",
"fig"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/graphs.py#L162-L169 |
xapple/plumbing | plumbing/graphs.py | Graph.plot | def plot(self, bins=250, **kwargs):
"""An example plot function. You have to subclass this method."""
# Data #
counts = [sum(map(len, b.contigs)) for b in self.parent.bins]
# Linear bins in logarithmic space #
if 'log' in kwargs.get('x_scale', ''):
start, stop = numpy... | python | def plot(self, bins=250, **kwargs):
"""An example plot function. You have to subclass this method."""
# Data #
counts = [sum(map(len, b.contigs)) for b in self.parent.bins]
# Linear bins in logarithmic space #
if 'log' in kwargs.get('x_scale', ''):
start, stop = numpy... | [
"def",
"plot",
"(",
"self",
",",
"bins",
"=",
"250",
",",
"*",
"*",
"kwargs",
")",
":",
"# Data #",
"counts",
"=",
"[",
"sum",
"(",
"map",
"(",
"len",
",",
"b",
".",
"contigs",
")",
")",
"for",
"b",
"in",
"self",
".",
"parent",
".",
"bins",
"... | An example plot function. You have to subclass this method. | [
"An",
"example",
"plot",
"function",
".",
"You",
"have",
"to",
"subclass",
"this",
"method",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/graphs.py#L171-L193 |
xapple/plumbing | plumbing/graphs.py | Graph.save_anim | def save_anim(self, fig, animate, init, bitrate=10000, fps=30):
"""Not functional -- TODO"""
from matplotlib import animation
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=360, interval=20)
FFMpegWriter = animation.writers['ffmpeg']
writer = FFMpegWriter(bit... | python | def save_anim(self, fig, animate, init, bitrate=10000, fps=30):
"""Not functional -- TODO"""
from matplotlib import animation
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=360, interval=20)
FFMpegWriter = animation.writers['ffmpeg']
writer = FFMpegWriter(bit... | [
"def",
"save_anim",
"(",
"self",
",",
"fig",
",",
"animate",
",",
"init",
",",
"bitrate",
"=",
"10000",
",",
"fps",
"=",
"30",
")",
":",
"from",
"matplotlib",
"import",
"animation",
"anim",
"=",
"animation",
".",
"FuncAnimation",
"(",
"fig",
",",
"anim... | Not functional -- TODO | [
"Not",
"functional",
"--",
"TODO"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/graphs.py#L195-L203 |
xapple/plumbing | plumbing/slurm/__init__.py | count_processors | def count_processors():
"""How many cores does the current computer have ?"""
if 'SLURM_NTASKS' in os.environ: return int(os.environ['SLURM_NTASKS'])
elif 'SLURM_JOB_CPUS_PER_NODE' in os.environ:
text = os.environ['SLURM_JOB_CPUS_PER_NODE']
if is_integer(text): return int(text)
el... | python | def count_processors():
"""How many cores does the current computer have ?"""
if 'SLURM_NTASKS' in os.environ: return int(os.environ['SLURM_NTASKS'])
elif 'SLURM_JOB_CPUS_PER_NODE' in os.environ:
text = os.environ['SLURM_JOB_CPUS_PER_NODE']
if is_integer(text): return int(text)
el... | [
"def",
"count_processors",
"(",
")",
":",
"if",
"'SLURM_NTASKS'",
"in",
"os",
".",
"environ",
":",
"return",
"int",
"(",
"os",
".",
"environ",
"[",
"'SLURM_NTASKS'",
"]",
")",
"elif",
"'SLURM_JOB_CPUS_PER_NODE'",
"in",
"os",
".",
"environ",
":",
"text",
"=... | How many cores does the current computer have ? | [
"How",
"many",
"cores",
"does",
"the",
"current",
"computer",
"have",
"?"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/slurm/__init__.py#L10-L19 |
xapple/plumbing | plumbing/slurm/__init__.py | guess_server_name | def guess_server_name():
"""We often use the same servers, which one are we running on now ?"""
if os.environ.get('CSCSERVICE') == 'sisu': return "sisu"
elif os.environ.get('SLURM_JOB_PARTITION') == 'halvan': return "halvan"
elif os.environ.get('SNIC_RESOURCE') == 'milou':... | python | def guess_server_name():
"""We often use the same servers, which one are we running on now ?"""
if os.environ.get('CSCSERVICE') == 'sisu': return "sisu"
elif os.environ.get('SLURM_JOB_PARTITION') == 'halvan': return "halvan"
elif os.environ.get('SNIC_RESOURCE') == 'milou':... | [
"def",
"guess_server_name",
"(",
")",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"'CSCSERVICE'",
")",
"==",
"'sisu'",
":",
"return",
"\"sisu\"",
"elif",
"os",
".",
"environ",
".",
"get",
"(",
"'SLURM_JOB_PARTITION'",
")",
"==",
"'halvan'",
":",
"r... | We often use the same servers, which one are we running on now ? | [
"We",
"often",
"use",
"the",
"same",
"servers",
"which",
"one",
"are",
"we",
"running",
"on",
"now",
"?"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/slurm/__init__.py#L22-L28 |
epandurski/flask_signalbus | flask_signalbus/atomic.py | _ModelUtilitiesMixin.get_instance | def get_instance(cls, instance_or_pk):
"""Return a model instance in ``db.session``.
:param instance_or_pk: An instance of this model class, or a
primary key. A composite primary key can be passed as a
tuple.
Example::
@db.atomic
def increase_account_ba... | python | def get_instance(cls, instance_or_pk):
"""Return a model instance in ``db.session``.
:param instance_or_pk: An instance of this model class, or a
primary key. A composite primary key can be passed as a
tuple.
Example::
@db.atomic
def increase_account_ba... | [
"def",
"get_instance",
"(",
"cls",
",",
"instance_or_pk",
")",
":",
"if",
"isinstance",
"(",
"instance_or_pk",
",",
"cls",
")",
":",
"if",
"instance_or_pk",
"in",
"cls",
".",
"_flask_signalbus_sa",
".",
"session",
":",
"return",
"instance_or_pk",
"instance_or_pk... | Return a model instance in ``db.session``.
:param instance_or_pk: An instance of this model class, or a
primary key. A composite primary key can be passed as a
tuple.
Example::
@db.atomic
def increase_account_balance(account, amount):
# Here `Acco... | [
"Return",
"a",
"model",
"instance",
"in",
"db",
".",
"session",
"."
] | train | https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/atomic.py#L21-L49 |
epandurski/flask_signalbus | flask_signalbus/atomic.py | _ModelUtilitiesMixin.lock_instance | def lock_instance(cls, instance_or_pk, read=False):
"""Return a locked model instance in ``db.session``.
:param instance_or_pk: An instance of this model class, or a
primary key. A composite primary key can be passed as a
tuple.
:param read: If `True`, a reading lock is obt... | python | def lock_instance(cls, instance_or_pk, read=False):
"""Return a locked model instance in ``db.session``.
:param instance_or_pk: An instance of this model class, or a
primary key. A composite primary key can be passed as a
tuple.
:param read: If `True`, a reading lock is obt... | [
"def",
"lock_instance",
"(",
"cls",
",",
"instance_or_pk",
",",
"read",
"=",
"False",
")",
":",
"mapper",
"=",
"inspect",
"(",
"cls",
")",
"pk_attrs",
"=",
"[",
"mapper",
".",
"get_property_by_column",
"(",
"c",
")",
".",
"class_attribute",
"for",
"c",
"... | Return a locked model instance in ``db.session``.
:param instance_or_pk: An instance of this model class, or a
primary key. A composite primary key can be passed as a
tuple.
:param read: If `True`, a reading lock is obtained instead of
a writing lock. | [
"Return",
"a",
"locked",
"model",
"instance",
"in",
"db",
".",
"session",
"."
] | train | https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/atomic.py#L52-L68 |
epandurski/flask_signalbus | flask_signalbus/atomic.py | _ModelUtilitiesMixin.get_pk_values | def get_pk_values(cls, instance_or_pk):
"""Return a primary key as a tuple.
:param instance_or_pk: An instance of this model class, or a
primary key. A composite primary key can be passed as a
tuple.
"""
if isinstance(instance_or_pk, cls):
cls._flask_si... | python | def get_pk_values(cls, instance_or_pk):
"""Return a primary key as a tuple.
:param instance_or_pk: An instance of this model class, or a
primary key. A composite primary key can be passed as a
tuple.
"""
if isinstance(instance_or_pk, cls):
cls._flask_si... | [
"def",
"get_pk_values",
"(",
"cls",
",",
"instance_or_pk",
")",
":",
"if",
"isinstance",
"(",
"instance_or_pk",
",",
"cls",
")",
":",
"cls",
".",
"_flask_signalbus_sa",
".",
"session",
".",
"flush",
"(",
")",
"instance_or_pk",
"=",
"inspect",
"(",
"cls",
"... | Return a primary key as a tuple.
:param instance_or_pk: An instance of this model class, or a
primary key. A composite primary key can be passed as a
tuple. | [
"Return",
"a",
"primary",
"key",
"as",
"a",
"tuple",
"."
] | train | https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/atomic.py#L71-L83 |
epandurski/flask_signalbus | flask_signalbus/atomic.py | AtomicProceduresMixin.atomic | def atomic(self, func):
"""A decorator that wraps a function in an atomic block.
Example::
db = CustomSQLAlchemy()
@db.atomic
def f():
write_to_db('a message')
return 'OK'
assert f() == 'OK'
This code defines the function `... | python | def atomic(self, func):
"""A decorator that wraps a function in an atomic block.
Example::
db = CustomSQLAlchemy()
@db.atomic
def f():
write_to_db('a message')
return 'OK'
assert f() == 'OK'
This code defines the function `... | [
"def",
"atomic",
"(",
"self",
",",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"session",
"=",
"self",
".",
"session",
"session_info",
"=",
"session",
".",
"info",
"if",
... | A decorator that wraps a function in an atomic block.
Example::
db = CustomSQLAlchemy()
@db.atomic
def f():
write_to_db('a message')
return 'OK'
assert f() == 'OK'
This code defines the function ``f``, which is wrapped in an
... | [
"A",
"decorator",
"that",
"wraps",
"a",
"function",
"in",
"an",
"atomic",
"block",
"."
] | train | https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/atomic.py#L129-L185 |
epandurski/flask_signalbus | flask_signalbus/atomic.py | AtomicProceduresMixin.retry_on_integrity_error | def retry_on_integrity_error(self):
"""Re-raise :class:`~sqlalchemy.exc.IntegrityError` as `DBSerializationError`.
This is mainly useful to handle race conditions in atomic
blocks. For example, even if prior to a database INSERT we
have verified that there is no existing row with the gi... | python | def retry_on_integrity_error(self):
"""Re-raise :class:`~sqlalchemy.exc.IntegrityError` as `DBSerializationError`.
This is mainly useful to handle race conditions in atomic
blocks. For example, even if prior to a database INSERT we
have verified that there is no existing row with the gi... | [
"def",
"retry_on_integrity_error",
"(",
"self",
")",
":",
"session",
"=",
"self",
".",
"session",
"assert",
"session",
".",
"info",
".",
"get",
"(",
"_ATOMIC_FLAG_SESSION_INFO_KEY",
")",
",",
"'Calls to \"retry_on_integrity_error\" must be wrapped in atomic block.'",
"ses... | Re-raise :class:`~sqlalchemy.exc.IntegrityError` as `DBSerializationError`.
This is mainly useful to handle race conditions in atomic
blocks. For example, even if prior to a database INSERT we
have verified that there is no existing row with the given
primary key, we still may get an
... | [
"Re",
"-",
"raise",
":",
"class",
":",
"~sqlalchemy",
".",
"exc",
".",
"IntegrityError",
"as",
"DBSerializationError",
"."
] | train | https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/atomic.py#L209-L243 |
intelligenia/modeltranslation | modeltranslation/translation.py | _save_translations | def _save_translations(sender, instance, *args, **kwargs):
"""
This signal saves model translations.
"""
# If we are in a site with one language there is no need of saving translations
if site_is_monolingual():
return False
cls = sender
# If its class has no "translatable_fields" then there are no translat... | python | def _save_translations(sender, instance, *args, **kwargs):
"""
This signal saves model translations.
"""
# If we are in a site with one language there is no need of saving translations
if site_is_monolingual():
return False
cls = sender
# If its class has no "translatable_fields" then there are no translat... | [
"def",
"_save_translations",
"(",
"sender",
",",
"instance",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# If we are in a site with one language there is no need of saving translations",
"if",
"site_is_monolingual",
"(",
")",
":",
"return",
"False",
"cls",
"... | This signal saves model translations. | [
"This",
"signal",
"saves",
"model",
"translations",
"."
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/translation.py#L53-L82 |
intelligenia/modeltranslation | modeltranslation/translation.py | _get_fieldtranslations | def _get_fieldtranslations(instance, field=None, lang=None):
"""
Get all the translations for this object.
"""
# Basic filtering: filter translations by module, model an object_id
_filter = {"module": instance.__module__, "model": instance.__class__.__name__, "object_id": instance.id}
if lang:
_filter["lang"]... | python | def _get_fieldtranslations(instance, field=None, lang=None):
"""
Get all the translations for this object.
"""
# Basic filtering: filter translations by module, model an object_id
_filter = {"module": instance.__module__, "model": instance.__class__.__name__, "object_id": instance.id}
if lang:
_filter["lang"]... | [
"def",
"_get_fieldtranslations",
"(",
"instance",
",",
"field",
"=",
"None",
",",
"lang",
"=",
"None",
")",
":",
"# Basic filtering: filter translations by module, model an object_id",
"_filter",
"=",
"{",
"\"module\"",
":",
"instance",
".",
"__module__",
",",
"\"mode... | Get all the translations for this object. | [
"Get",
"all",
"the",
"translations",
"for",
"this",
"object",
"."
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/translation.py#L93-L113 |
intelligenia/modeltranslation | modeltranslation/translation.py | _load_translations | def _load_translations(instance, lang=None):
"""
Loads all translations as dynamic attributes:
<attr>_<lang_code>
<attr>_<lang_code>_is_fuzzy
"""
# Gets field translations
translations = _get_fieldtranslations(instance=instance, lang=lang)
for translation_i in translations:
# Sets translated field lang for ... | python | def _load_translations(instance, lang=None):
"""
Loads all translations as dynamic attributes:
<attr>_<lang_code>
<attr>_<lang_code>_is_fuzzy
"""
# Gets field translations
translations = _get_fieldtranslations(instance=instance, lang=lang)
for translation_i in translations:
# Sets translated field lang for ... | [
"def",
"_load_translations",
"(",
"instance",
",",
"lang",
"=",
"None",
")",
":",
"# Gets field translations",
"translations",
"=",
"_get_fieldtranslations",
"(",
"instance",
"=",
"instance",
",",
"lang",
"=",
"lang",
")",
"for",
"translation_i",
"in",
"translatio... | Loads all translations as dynamic attributes:
<attr>_<lang_code>
<attr>_<lang_code>_is_fuzzy | [
"Loads",
"all",
"translations",
"as",
"dynamic",
"attributes",
":",
"<attr",
">",
"_<lang_code",
">",
"<attr",
">",
"_<lang_code",
">",
"_is_fuzzy"
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/translation.py#L118-L134 |
intelligenia/modeltranslation | modeltranslation/translation.py | _set_dict_translations | def _set_dict_translations(instance, dict_translations):
"""
Establece los atributos de traducciones a partir de una dict que
contiene todas las traducciones.
"""
# If class has no translatable fields get out
if not hasattr(instance._meta, "translatable_fields"):
return False
# If we are in a site with one l... | python | def _set_dict_translations(instance, dict_translations):
"""
Establece los atributos de traducciones a partir de una dict que
contiene todas las traducciones.
"""
# If class has no translatable fields get out
if not hasattr(instance._meta, "translatable_fields"):
return False
# If we are in a site with one l... | [
"def",
"_set_dict_translations",
"(",
"instance",
",",
"dict_translations",
")",
":",
"# If class has no translatable fields get out",
"if",
"not",
"hasattr",
"(",
"instance",
".",
"_meta",
",",
"\"translatable_fields\"",
")",
":",
"return",
"False",
"# If we are in a sit... | Establece los atributos de traducciones a partir de una dict que
contiene todas las traducciones. | [
"Establece",
"los",
"atributos",
"de",
"traducciones",
"a",
"partir",
"de",
"una",
"dict",
"que",
"contiene",
"todas",
"las",
"traducciones",
"."
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/translation.py#L139-L178 |
intelligenia/modeltranslation | modeltranslation/translation.py | add_translation | def add_translation(sender):
"""
Adds the actions to a class.
"""
# 1. Execute _save_translations when saving an object
signals.post_save.connect(_save_translations, sender=sender)
# 2. Adds get_fieldtranslations to class. Remember that this method get all the translations.
sender.add_to_class("get_fieldtranslat... | python | def add_translation(sender):
"""
Adds the actions to a class.
"""
# 1. Execute _save_translations when saving an object
signals.post_save.connect(_save_translations, sender=sender)
# 2. Adds get_fieldtranslations to class. Remember that this method get all the translations.
sender.add_to_class("get_fieldtranslat... | [
"def",
"add_translation",
"(",
"sender",
")",
":",
"# 1. Execute _save_translations when saving an object",
"signals",
".",
"post_save",
".",
"connect",
"(",
"_save_translations",
",",
"sender",
"=",
"sender",
")",
"# 2. Adds get_fieldtranslations to class. Remember that this m... | Adds the actions to a class. | [
"Adds",
"the",
"actions",
"to",
"a",
"class",
"."
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/translation.py#L216-L234 |
StorjOld/file-encryptor | file_encryptor/convergence.py | encrypt_file_inline | def encrypt_file_inline(filename, passphrase):
"""Encrypt file inline, with an optional passphrase.
If you set the passphrase to None, a default is used.
This will make you vulnerable to confirmation attacks
and learn-partial-information attacks.
:param filename: The name of the file to encrypt.
... | python | def encrypt_file_inline(filename, passphrase):
"""Encrypt file inline, with an optional passphrase.
If you set the passphrase to None, a default is used.
This will make you vulnerable to confirmation attacks
and learn-partial-information attacks.
:param filename: The name of the file to encrypt.
... | [
"def",
"encrypt_file_inline",
"(",
"filename",
",",
"passphrase",
")",
":",
"key",
"=",
"key_generators",
".",
"key_from_file",
"(",
"filename",
",",
"passphrase",
")",
"inline_transform",
"(",
"filename",
",",
"key",
")",
"return",
"key"
] | Encrypt file inline, with an optional passphrase.
If you set the passphrase to None, a default is used.
This will make you vulnerable to confirmation attacks
and learn-partial-information attacks.
:param filename: The name of the file to encrypt.
:type filename: str
:param passphrase: The pass... | [
"Encrypt",
"file",
"inline",
"with",
"an",
"optional",
"passphrase",
"."
] | train | https://github.com/StorjOld/file-encryptor/blob/245191c45dbd68e09a4a8f07c5d7331be195dc6b/file_encryptor/convergence.py#L33-L51 |
StorjOld/file-encryptor | file_encryptor/convergence.py | inline_transform | def inline_transform(filename, key):
"""Encrypt file inline.
Encrypts a given file with the given key,
and replaces it directly without any extra
space requirement.
:param filename: The name of the file to encrypt.
:type filename: str
:param key: The key used to encrypt the file.
:type... | python | def inline_transform(filename, key):
"""Encrypt file inline.
Encrypts a given file with the given key,
and replaces it directly without any extra
space requirement.
:param filename: The name of the file to encrypt.
:type filename: str
:param key: The key used to encrypt the file.
:type... | [
"def",
"inline_transform",
"(",
"filename",
",",
"key",
")",
":",
"pos",
"=",
"0",
"for",
"chunk",
",",
"fp",
"in",
"iter_transform",
"(",
"filename",
",",
"key",
")",
":",
"fp",
".",
"seek",
"(",
"pos",
")",
"fp",
".",
"write",
"(",
"chunk",
")",
... | Encrypt file inline.
Encrypts a given file with the given key,
and replaces it directly without any extra
space requirement.
:param filename: The name of the file to encrypt.
:type filename: str
:param key: The key used to encrypt the file.
:type key: str | [
"Encrypt",
"file",
"inline",
"."
] | train | https://github.com/StorjOld/file-encryptor/blob/245191c45dbd68e09a4a8f07c5d7331be195dc6b/file_encryptor/convergence.py#L85-L102 |
StorjOld/file-encryptor | file_encryptor/convergence.py | iter_transform | def iter_transform(filename, key):
"""Generate encrypted file with given key.
This generator function reads the file
in chunks and encrypts them using AES-CTR,
with the specified key.
:param filename: The name of the file to encrypt.
:type filename: str
:param key: The key used to encrypt ... | python | def iter_transform(filename, key):
"""Generate encrypted file with given key.
This generator function reads the file
in chunks and encrypts them using AES-CTR,
with the specified key.
:param filename: The name of the file to encrypt.
:type filename: str
:param key: The key used to encrypt ... | [
"def",
"iter_transform",
"(",
"filename",
",",
"key",
")",
":",
"# We are not specifying the IV here.",
"aes",
"=",
"AES",
".",
"new",
"(",
"key",
",",
"AES",
".",
"MODE_CTR",
",",
"counter",
"=",
"Counter",
".",
"new",
"(",
"128",
")",
")",
"with",
"ope... | Generate encrypted file with given key.
This generator function reads the file
in chunks and encrypts them using AES-CTR,
with the specified key.
:param filename: The name of the file to encrypt.
:type filename: str
:param key: The key used to encrypt the file.
:type key: str
:returns:... | [
"Generate",
"encrypted",
"file",
"with",
"given",
"key",
"."
] | train | https://github.com/StorjOld/file-encryptor/blob/245191c45dbd68e09a4a8f07c5d7331be195dc6b/file_encryptor/convergence.py#L105-L124 |
matllubos/django-is-core | is_core/auth/permissions.py | PermissionsSet.set | def set(self, name, permission):
"""
Adds permission with the given name to the set. Permission with the same name will be overridden.
Args:
name: name of the permission
permission: permission instance
"""
assert isinstance(permission, BasePermission), 'On... | python | def set(self, name, permission):
"""
Adds permission with the given name to the set. Permission with the same name will be overridden.
Args:
name: name of the permission
permission: permission instance
"""
assert isinstance(permission, BasePermission), 'On... | [
"def",
"set",
"(",
"self",
",",
"name",
",",
"permission",
")",
":",
"assert",
"isinstance",
"(",
"permission",
",",
"BasePermission",
")",
",",
"'Only permission instances can be added to the set'",
"self",
".",
"_permissions",
"[",
"name",
"]",
"=",
"permission"... | Adds permission with the given name to the set. Permission with the same name will be overridden.
Args:
name: name of the permission
permission: permission instance | [
"Adds",
"permission",
"with",
"the",
"given",
"name",
"to",
"the",
"set",
".",
"Permission",
"with",
"the",
"same",
"name",
"will",
"be",
"overridden",
".",
"Args",
":",
"name",
":",
"name",
"of",
"the",
"permission",
"permission",
":",
"permission",
"inst... | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/auth/permissions.py#L114-L123 |
matllubos/django-is-core | is_core/forms/boundfield.py | SmartBoundField.as_widget | def as_widget(self, widget=None, attrs=None, only_initial=False):
"""
Renders the field by rendering the passed widget, adding any HTML
attributes passed as attrs. If no widget is specified, then the
field's default widget will be used.
"""
if not widget:
wid... | python | def as_widget(self, widget=None, attrs=None, only_initial=False):
"""
Renders the field by rendering the passed widget, adding any HTML
attributes passed as attrs. If no widget is specified, then the
field's default widget will be used.
"""
if not widget:
wid... | [
"def",
"as_widget",
"(",
"self",
",",
"widget",
"=",
"None",
",",
"attrs",
"=",
"None",
",",
"only_initial",
"=",
"False",
")",
":",
"if",
"not",
"widget",
":",
"widget",
"=",
"self",
".",
"field",
".",
"widget",
"if",
"self",
".",
"field",
".",
"l... | Renders the field by rendering the passed widget, adding any HTML
attributes passed as attrs. If no widget is specified, then the
field's default widget will be used. | [
"Renders",
"the",
"field",
"by",
"rendering",
"the",
"passed",
"widget",
"adding",
"any",
"HTML",
"attributes",
"passed",
"as",
"attrs",
".",
"If",
"no",
"widget",
"is",
"specified",
"then",
"the",
"field",
"s",
"default",
"widget",
"will",
"be",
"used",
"... | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/forms/boundfield.py#L12-L41 |
epandurski/flask_signalbus | flask_signalbus/signalbus.py | _setup_schema | def _setup_schema(Base, session):
"""Create a function which adds `__marshmallow__` attribute to all signal models."""
def create_schema_class(m):
if hasattr(m, 'send_signalbus_message'):
# Signal models should not use the SQLAlchemy session.
class Meta(object):
... | python | def _setup_schema(Base, session):
"""Create a function which adds `__marshmallow__` attribute to all signal models."""
def create_schema_class(m):
if hasattr(m, 'send_signalbus_message'):
# Signal models should not use the SQLAlchemy session.
class Meta(object):
... | [
"def",
"_setup_schema",
"(",
"Base",
",",
"session",
")",
":",
"def",
"create_schema_class",
"(",
"m",
")",
":",
"if",
"hasattr",
"(",
"m",
",",
"'send_signalbus_message'",
")",
":",
"# Signal models should not use the SQLAlchemy session.",
"class",
"Meta",
"(",
"... | Create a function which adds `__marshmallow__` attribute to all signal models. | [
"Create",
"a",
"function",
"which",
"adds",
"__marshmallow__",
"attribute",
"to",
"all",
"signal",
"models",
"."
] | train | https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/signalbus.py#L272-L303 |
epandurski/flask_signalbus | flask_signalbus/signalbus.py | SignalBusMixin.signalbus | def signalbus(self):
"""The associated `SignalBus` object."""
try:
signalbus = self.__signalbus
except AttributeError:
signalbus = self.__signalbus = SignalBus(self, init_app=False)
return signalbus | python | def signalbus(self):
"""The associated `SignalBus` object."""
try:
signalbus = self.__signalbus
except AttributeError:
signalbus = self.__signalbus = SignalBus(self, init_app=False)
return signalbus | [
"def",
"signalbus",
"(",
"self",
")",
":",
"try",
":",
"signalbus",
"=",
"self",
".",
"__signalbus",
"except",
"AttributeError",
":",
"signalbus",
"=",
"self",
".",
"__signalbus",
"=",
"SignalBus",
"(",
"self",
",",
"init_app",
"=",
"False",
")",
"return",... | The associated `SignalBus` object. | [
"The",
"associated",
"SignalBus",
"object",
"."
] | train | https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/signalbus.py#L53-L60 |
epandurski/flask_signalbus | flask_signalbus/signalbus.py | SignalBus.get_signal_models | def get_signal_models(self):
"""Return all signal types in a list.
:rtype: list(`signal-model`)
"""
base = self.db.Model
return [
cls for cls in base._decl_class_registry.values() if (
isinstance(cls, type)
and issubclass(cls, base)
... | python | def get_signal_models(self):
"""Return all signal types in a list.
:rtype: list(`signal-model`)
"""
base = self.db.Model
return [
cls for cls in base._decl_class_registry.values() if (
isinstance(cls, type)
and issubclass(cls, base)
... | [
"def",
"get_signal_models",
"(",
"self",
")",
":",
"base",
"=",
"self",
".",
"db",
".",
"Model",
"return",
"[",
"cls",
"for",
"cls",
"in",
"base",
".",
"_decl_class_registry",
".",
"values",
"(",
")",
"if",
"(",
"isinstance",
"(",
"cls",
",",
"type",
... | Return all signal types in a list.
:rtype: list(`signal-model`) | [
"Return",
"all",
"signal",
"types",
"in",
"a",
"list",
"."
] | train | https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/signalbus.py#L118-L132 |
epandurski/flask_signalbus | flask_signalbus/signalbus.py | SignalBus.flush | def flush(self, models=None, wait=3.0):
"""Send all pending signals over the message bus.
:param models: If passed, flushes only signals of the specified types.
:type models: list(`signal-model`) or `None`
:param float wait: The number of seconds the method will wait
after o... | python | def flush(self, models=None, wait=3.0):
"""Send all pending signals over the message bus.
:param models: If passed, flushes only signals of the specified types.
:type models: list(`signal-model`) or `None`
:param float wait: The number of seconds the method will wait
after o... | [
"def",
"flush",
"(",
"self",
",",
"models",
"=",
"None",
",",
"wait",
"=",
"3.0",
")",
":",
"models_to_flush",
"=",
"self",
".",
"get_signal_models",
"(",
")",
"if",
"models",
"is",
"None",
"else",
"models",
"pks_to_flush",
"=",
"{",
"}",
"try",
":",
... | Send all pending signals over the message bus.
:param models: If passed, flushes only signals of the specified types.
:type models: list(`signal-model`) or `None`
:param float wait: The number of seconds the method will wait
after obtaining the list of pending signals, to allow
... | [
"Send",
"all",
"pending",
"signals",
"over",
"the",
"message",
"bus",
"."
] | train | https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/signalbus.py#L134-L161 |
epandurski/flask_signalbus | flask_signalbus/signalbus.py | SignalBus.flushmany | def flushmany(self):
"""Send a potentially huge number of pending signals over the message bus.
This method assumes that the number of pending signals might
be huge, so that they might not fit into memory. However,
`SignalBus.flushmany` is not very smart in handling concurrent
s... | python | def flushmany(self):
"""Send a potentially huge number of pending signals over the message bus.
This method assumes that the number of pending signals might
be huge, so that they might not fit into memory. However,
`SignalBus.flushmany` is not very smart in handling concurrent
s... | [
"def",
"flushmany",
"(",
"self",
")",
":",
"models_to_flush",
"=",
"self",
".",
"get_signal_models",
"(",
")",
"try",
":",
"return",
"sum",
"(",
"self",
".",
"_flushmany_signals",
"(",
"model",
")",
"for",
"model",
"in",
"models_to_flush",
")",
"finally",
... | Send a potentially huge number of pending signals over the message bus.
This method assumes that the number of pending signals might
be huge, so that they might not fit into memory. However,
`SignalBus.flushmany` is not very smart in handling concurrent
senders. It is mostly useful when... | [
"Send",
"a",
"potentially",
"huge",
"number",
"of",
"pending",
"signals",
"over",
"the",
"message",
"bus",
"."
] | train | https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/signalbus.py#L163-L180 |
sprockets/sprockets.http | examples.py | StatusHandler.get | def get(self, status_code):
"""
Returns the requested status.
:param int status_code: the status code to return
:queryparam str reason: optional reason phrase
"""
status_code = int(status_code)
if status_code >= 400:
kwargs = {'status_code': status_c... | python | def get(self, status_code):
"""
Returns the requested status.
:param int status_code: the status code to return
:queryparam str reason: optional reason phrase
"""
status_code = int(status_code)
if status_code >= 400:
kwargs = {'status_code': status_c... | [
"def",
"get",
"(",
"self",
",",
"status_code",
")",
":",
"status_code",
"=",
"int",
"(",
"status_code",
")",
"if",
"status_code",
">=",
"400",
":",
"kwargs",
"=",
"{",
"'status_code'",
":",
"status_code",
"}",
"if",
"self",
".",
"get_query_argument",
"(",
... | Returns the requested status.
:param int status_code: the status code to return
:queryparam str reason: optional reason phrase | [
"Returns",
"the",
"requested",
"status",
"."
] | train | https://github.com/sprockets/sprockets.http/blob/8baa4cdc1fa35a162ee226fd6cc4170a0ca0ecd3/examples.py#L10-L27 |
inveniosoftware/invenio-iiif | invenio_iiif/ext.py | InvenioIIIF.init_app | def init_app(self, app):
"""Flask application initialization."""
self.init_config(app)
self.iiif_ext = IIIF(app=app)
self.iiif_ext.api_decorator_handler(protect_api)
self.iiif_ext.uuid_to_image_opener_handler(image_opener)
app.extensions['invenio-iiif'] = self | python | def init_app(self, app):
"""Flask application initialization."""
self.init_config(app)
self.iiif_ext = IIIF(app=app)
self.iiif_ext.api_decorator_handler(protect_api)
self.iiif_ext.uuid_to_image_opener_handler(image_opener)
app.extensions['invenio-iiif'] = self | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"self",
".",
"init_config",
"(",
"app",
")",
"self",
".",
"iiif_ext",
"=",
"IIIF",
"(",
"app",
"=",
"app",
")",
"self",
".",
"iiif_ext",
".",
"api_decorator_handler",
"(",
"protect_api",
")",
"self"... | Flask application initialization. | [
"Flask",
"application",
"initialization",
"."
] | train | https://github.com/inveniosoftware/invenio-iiif/blob/e4f2f93eaabdc8e2efea81c239ab76d481191959/invenio_iiif/ext.py#L28-L34 |
inveniosoftware/invenio-iiif | invenio_iiif/ext.py | InvenioIIIFAPI.init_app | def init_app(self, app):
"""Flask application initialization."""
super(InvenioIIIFAPI, self).init_app(app)
api = Api(app=app)
self.iiif_ext.init_restful(api, prefix=app.config['IIIF_API_PREFIX']) | python | def init_app(self, app):
"""Flask application initialization."""
super(InvenioIIIFAPI, self).init_app(app)
api = Api(app=app)
self.iiif_ext.init_restful(api, prefix=app.config['IIIF_API_PREFIX']) | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"super",
"(",
"InvenioIIIFAPI",
",",
"self",
")",
".",
"init_app",
"(",
"app",
")",
"api",
"=",
"Api",
"(",
"app",
"=",
"app",
")",
"self",
".",
"iiif_ext",
".",
"init_restful",
"(",
"api",
",",... | Flask application initialization. | [
"Flask",
"application",
"initialization",
"."
] | train | https://github.com/inveniosoftware/invenio-iiif/blob/e4f2f93eaabdc8e2efea81c239ab76d481191959/invenio_iiif/ext.py#L46-L50 |
confirm/ansibleci | ansibleci/helper.py | Helper.get_absolute_path | def get_absolute_path(self, path):
'''
Returns the absolute path of the ``path`` argument.
If ``path`` is already absolute, nothing changes. If the ``path`` is
relative, then the BASEDIR will be prepended.
'''
if os.path.isabs(path):
return path
else:... | python | def get_absolute_path(self, path):
'''
Returns the absolute path of the ``path`` argument.
If ``path`` is already absolute, nothing changes. If the ``path`` is
relative, then the BASEDIR will be prepended.
'''
if os.path.isabs(path):
return path
else:... | [
"def",
"get_absolute_path",
"(",
"self",
",",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"path",
")",
":",
"return",
"path",
"else",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"s... | Returns the absolute path of the ``path`` argument.
If ``path`` is already absolute, nothing changes. If the ``path`` is
relative, then the BASEDIR will be prepended. | [
"Returns",
"the",
"absolute",
"path",
"of",
"the",
"path",
"argument",
"."
] | train | https://github.com/confirm/ansibleci/blob/6a53ae8c4a4653624977e146092422857f661b8f/ansibleci/helper.py#L25-L35 |
confirm/ansibleci | ansibleci/helper.py | Helper.get_roles_paths | def get_roles_paths(self):
'''
Returns all absolute paths to the roles/ directories, while considering
the ``BASEDIR`` and ``ROLES`` config variables.
'''
roles = []
for path in self.config.ROLES:
roles.append(self.get_absolute_path(path))
return ro... | python | def get_roles_paths(self):
'''
Returns all absolute paths to the roles/ directories, while considering
the ``BASEDIR`` and ``ROLES`` config variables.
'''
roles = []
for path in self.config.ROLES:
roles.append(self.get_absolute_path(path))
return ro... | [
"def",
"get_roles_paths",
"(",
"self",
")",
":",
"roles",
"=",
"[",
"]",
"for",
"path",
"in",
"self",
".",
"config",
".",
"ROLES",
":",
"roles",
".",
"append",
"(",
"self",
".",
"get_absolute_path",
"(",
"path",
")",
")",
"return",
"roles"
] | Returns all absolute paths to the roles/ directories, while considering
the ``BASEDIR`` and ``ROLES`` config variables. | [
"Returns",
"all",
"absolute",
"paths",
"to",
"the",
"roles",
"/",
"directories",
"while",
"considering",
"the",
"BASEDIR",
"and",
"ROLES",
"config",
"variables",
"."
] | train | https://github.com/confirm/ansibleci/blob/6a53ae8c4a4653624977e146092422857f661b8f/ansibleci/helper.py#L37-L47 |
confirm/ansibleci | ansibleci/helper.py | Helper.get_roles | def get_roles(self):
'''
Returns a key-value dict with a roles, while the key is the role name
and the value is the absolute role path.
'''
roles = {}
paths = self.get_roles_paths()
for path in paths:
for entry in os.listdir(path):
rol... | python | def get_roles(self):
'''
Returns a key-value dict with a roles, while the key is the role name
and the value is the absolute role path.
'''
roles = {}
paths = self.get_roles_paths()
for path in paths:
for entry in os.listdir(path):
rol... | [
"def",
"get_roles",
"(",
"self",
")",
":",
"roles",
"=",
"{",
"}",
"paths",
"=",
"self",
".",
"get_roles_paths",
"(",
")",
"for",
"path",
"in",
"paths",
":",
"for",
"entry",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"rolepath",
"=",
"os",
... | Returns a key-value dict with a roles, while the key is the role name
and the value is the absolute role path. | [
"Returns",
"a",
"key",
"-",
"value",
"dict",
"with",
"a",
"roles",
"while",
"the",
"key",
"is",
"the",
"role",
"name",
"and",
"the",
"value",
"is",
"the",
"absolute",
"role",
"path",
"."
] | train | https://github.com/confirm/ansibleci/blob/6a53ae8c4a4653624977e146092422857f661b8f/ansibleci/helper.py#L49-L63 |
confirm/ansibleci | ansibleci/helper.py | Helper.read_yaml | def read_yaml(self, filename):
'''
Reads and parses a YAML file and returns the content.
'''
with open(filename, 'r') as f:
d = re.sub(r'\{\{ *([^ ]+) *\}\}', r'\1', f.read())
y = yaml.safe_load(d)
return y if y else {} | python | def read_yaml(self, filename):
'''
Reads and parses a YAML file and returns the content.
'''
with open(filename, 'r') as f:
d = re.sub(r'\{\{ *([^ ]+) *\}\}', r'\1', f.read())
y = yaml.safe_load(d)
return y if y else {} | [
"def",
"read_yaml",
"(",
"self",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"d",
"=",
"re",
".",
"sub",
"(",
"r'\\{\\{ *([^ ]+) *\\}\\}'",
",",
"r'\\1'",
",",
"f",
".",
"read",
"(",
")",
")",
"y",
... | Reads and parses a YAML file and returns the content. | [
"Reads",
"and",
"parses",
"a",
"YAML",
"file",
"and",
"returns",
"the",
"content",
"."
] | train | https://github.com/confirm/ansibleci/blob/6a53ae8c4a4653624977e146092422857f661b8f/ansibleci/helper.py#L65-L72 |
confirm/ansibleci | ansibleci/helper.py | Helper.get_yaml_items | def get_yaml_items(self, dir_path, param=None):
'''
Loops through the dir_path and parses all YAML files inside the
directory.
If no param is defined, then all YAML items will be returned
in a list. If a param is defined, then all items will be scanned for
this param and... | python | def get_yaml_items(self, dir_path, param=None):
'''
Loops through the dir_path and parses all YAML files inside the
directory.
If no param is defined, then all YAML items will be returned
in a list. If a param is defined, then all items will be scanned for
this param and... | [
"def",
"get_yaml_items",
"(",
"self",
",",
"dir_path",
",",
"param",
"=",
"None",
")",
":",
"result",
"=",
"[",
"]",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"dir_path",
")",
":",
"return",
"[",
"]",
"for",
"filename",
"in",
"os",
".",
... | Loops through the dir_path and parses all YAML files inside the
directory.
If no param is defined, then all YAML items will be returned
in a list. If a param is defined, then all items will be scanned for
this param and a list of all those values will be returned. | [
"Loops",
"through",
"the",
"dir_path",
"and",
"parses",
"all",
"YAML",
"files",
"inside",
"the",
"directory",
"."
] | train | https://github.com/confirm/ansibleci/blob/6a53ae8c4a4653624977e146092422857f661b8f/ansibleci/helper.py#L74-L105 |
The-Politico/django-slackchat-serializer | slackchat/tasks/webhook.py | clean_response | def clean_response(response):
""" Cleans string quoting in response. """
response = re.sub("^['\"]", "", response)
response = re.sub("['\"]$", "", response)
return response | python | def clean_response(response):
""" Cleans string quoting in response. """
response = re.sub("^['\"]", "", response)
response = re.sub("['\"]$", "", response)
return response | [
"def",
"clean_response",
"(",
"response",
")",
":",
"response",
"=",
"re",
".",
"sub",
"(",
"\"^['\\\"]\"",
",",
"\"\"",
",",
"response",
")",
"response",
"=",
"re",
".",
"sub",
"(",
"\"['\\\"]$\"",
",",
"\"\"",
",",
"response",
")",
"return",
"response"... | Cleans string quoting in response. | [
"Cleans",
"string",
"quoting",
"in",
"response",
"."
] | train | https://github.com/The-Politico/django-slackchat-serializer/blob/9a41e0477d1bc7bb2ec3f8af40baddf8d4230d40/slackchat/tasks/webhook.py#L63-L67 |
epandurski/flask_signalbus | flask_signalbus/utils.py | retry_on_deadlock | def retry_on_deadlock(session, retries=6, min_wait=0.1, max_wait=10.0):
"""Return function decorator that executes the function again in case of a deadlock."""
def decorator(action):
"""Function decorator that retries `action` in case of a deadlock."""
@wraps(action)
def f(*args, **kwa... | python | def retry_on_deadlock(session, retries=6, min_wait=0.1, max_wait=10.0):
"""Return function decorator that executes the function again in case of a deadlock."""
def decorator(action):
"""Function decorator that retries `action` in case of a deadlock."""
@wraps(action)
def f(*args, **kwa... | [
"def",
"retry_on_deadlock",
"(",
"session",
",",
"retries",
"=",
"6",
",",
"min_wait",
"=",
"0.1",
",",
"max_wait",
"=",
"10.0",
")",
":",
"def",
"decorator",
"(",
"action",
")",
":",
"\"\"\"Function decorator that retries `action` in case of a deadlock.\"\"\"",
"@"... | Return function decorator that executes the function again in case of a deadlock. | [
"Return",
"function",
"decorator",
"that",
"executes",
"the",
"function",
"again",
"in",
"case",
"of",
"a",
"deadlock",
"."
] | train | https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/utils.py#L28-L54 |
xapple/plumbing | plumbing/cache.py | cached | def cached(f):
"""Decorator for functions evaluated only once."""
def memoized(*args, **kwargs):
if hasattr(memoized, '__cache__'):
return memoized.__cache__
result = f(*args, **kwargs)
memoized.__cache__ = result
return result
return memoized | python | def cached(f):
"""Decorator for functions evaluated only once."""
def memoized(*args, **kwargs):
if hasattr(memoized, '__cache__'):
return memoized.__cache__
result = f(*args, **kwargs)
memoized.__cache__ = result
return result
return memoized | [
"def",
"cached",
"(",
"f",
")",
":",
"def",
"memoized",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"hasattr",
"(",
"memoized",
",",
"'__cache__'",
")",
":",
"return",
"memoized",
".",
"__cache__",
"result",
"=",
"f",
"(",
"*",
"args... | Decorator for functions evaluated only once. | [
"Decorator",
"for",
"functions",
"evaluated",
"only",
"once",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/cache.py#L12-L20 |
xapple/plumbing | plumbing/cache.py | property_pickled | def property_pickled(f):
"""Same thing as above but the result will be stored on disk
The path of the pickle file will be determined by looking for the
`cache_dir` attribute of the instance containing the cached property.
If no `cache_dir` attribute exists the `p` attribute will be accessed with
the... | python | def property_pickled(f):
"""Same thing as above but the result will be stored on disk
The path of the pickle file will be determined by looking for the
`cache_dir` attribute of the instance containing the cached property.
If no `cache_dir` attribute exists the `p` attribute will be accessed with
the... | [
"def",
"property_pickled",
"(",
"f",
")",
":",
"# Called when you access the property #",
"def",
"retrieve_from_cache",
"(",
"self",
")",
":",
"# Is it in the cache ? #",
"if",
"'__cache__'",
"not",
"in",
"self",
".",
"__dict__",
":",
"self",
".",
"__cache__",
"=",
... | Same thing as above but the result will be stored on disk
The path of the pickle file will be determined by looking for the
`cache_dir` attribute of the instance containing the cached property.
If no `cache_dir` attribute exists the `p` attribute will be accessed with
the name of the property being cach... | [
"Same",
"thing",
"as",
"above",
"but",
"the",
"result",
"will",
"be",
"stored",
"on",
"disk",
"The",
"path",
"of",
"the",
"pickle",
"file",
"will",
"be",
"determined",
"by",
"looking",
"for",
"the",
"cache_dir",
"attribute",
"of",
"the",
"instance",
"conta... | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/cache.py#L85-L122 |
matllubos/django-is-core | is_core/forms/formsets.py | smartformset_factory | def smartformset_factory(form, formset=BaseFormSet, extra=1, can_order=False,
can_delete=False, min_num=None, max_num=None, validate_min=False, validate_max=False):
"""Return a FormSet for the given form class."""
if max_num is None:
max_num = DEFAULT_MAX_NUM
# hard limit on... | python | def smartformset_factory(form, formset=BaseFormSet, extra=1, can_order=False,
can_delete=False, min_num=None, max_num=None, validate_min=False, validate_max=False):
"""Return a FormSet for the given form class."""
if max_num is None:
max_num = DEFAULT_MAX_NUM
# hard limit on... | [
"def",
"smartformset_factory",
"(",
"form",
",",
"formset",
"=",
"BaseFormSet",
",",
"extra",
"=",
"1",
",",
"can_order",
"=",
"False",
",",
"can_delete",
"=",
"False",
",",
"min_num",
"=",
"None",
",",
"max_num",
"=",
"None",
",",
"validate_min",
"=",
"... | Return a FormSet for the given form class. | [
"Return",
"a",
"FormSet",
"for",
"the",
"given",
"form",
"class",
"."
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/forms/formsets.py#L34-L50 |
matllubos/django-is-core | is_core/generic_views/form_views.py | DefaultFormView.save_form | def save_form(self, form, **kwargs):
"""Contains formset save, prepare obj for saving"""
obj = form.save(commit=False)
change = obj.pk is not None
self.save_obj(obj, form, change)
if hasattr(form, 'save_m2m'):
form.save_m2m()
return obj | python | def save_form(self, form, **kwargs):
"""Contains formset save, prepare obj for saving"""
obj = form.save(commit=False)
change = obj.pk is not None
self.save_obj(obj, form, change)
if hasattr(form, 'save_m2m'):
form.save_m2m()
return obj | [
"def",
"save_form",
"(",
"self",
",",
"form",
",",
"*",
"*",
"kwargs",
")",
":",
"obj",
"=",
"form",
".",
"save",
"(",
"commit",
"=",
"False",
")",
"change",
"=",
"obj",
".",
"pk",
"is",
"not",
"None",
"self",
".",
"save_obj",
"(",
"obj",
",",
... | Contains formset save, prepare obj for saving | [
"Contains",
"formset",
"save",
"prepare",
"obj",
"for",
"saving"
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/generic_views/form_views.py#L109-L117 |
matllubos/django-is-core | is_core/generic_views/form_views.py | DefaultFormView.get_method_returning_field_value | def get_method_returning_field_value(self, field_name):
"""
Field values can be obtained from view or core.
"""
return (
super().get_method_returning_field_value(field_name)
or self.core.get_method_returning_field_value(field_name)
) | python | def get_method_returning_field_value(self, field_name):
"""
Field values can be obtained from view or core.
"""
return (
super().get_method_returning_field_value(field_name)
or self.core.get_method_returning_field_value(field_name)
) | [
"def",
"get_method_returning_field_value",
"(",
"self",
",",
"field_name",
")",
":",
"return",
"(",
"super",
"(",
")",
".",
"get_method_returning_field_value",
"(",
"field_name",
")",
"or",
"self",
".",
"core",
".",
"get_method_returning_field_value",
"(",
"field_na... | Field values can be obtained from view or core. | [
"Field",
"values",
"can",
"be",
"obtained",
"from",
"view",
"or",
"core",
"."
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/generic_views/form_views.py#L267-L274 |
matllubos/django-is-core | is_core/generic_views/form_views.py | DetailModelFormView._get_perm_obj_or_404 | def _get_perm_obj_or_404(self, pk=None):
"""
If is send parameter pk is returned object according this pk,
else is returned object from get_obj method, but it search only inside filtered values for current user,
finally if object is still None is returned according the input key from all... | python | def _get_perm_obj_or_404(self, pk=None):
"""
If is send parameter pk is returned object according this pk,
else is returned object from get_obj method, but it search only inside filtered values for current user,
finally if object is still None is returned according the input key from all... | [
"def",
"_get_perm_obj_or_404",
"(",
"self",
",",
"pk",
"=",
"None",
")",
":",
"if",
"pk",
":",
"obj",
"=",
"get_object_or_none",
"(",
"self",
".",
"core",
".",
"model",
",",
"pk",
"=",
"pk",
")",
"else",
":",
"try",
":",
"obj",
"=",
"self",
".",
... | If is send parameter pk is returned object according this pk,
else is returned object from get_obj method, but it search only inside filtered values for current user,
finally if object is still None is returned according the input key from all objects.
If object does not exist is raised Http404 | [
"If",
"is",
"send",
"parameter",
"pk",
"is",
"returned",
"object",
"according",
"this",
"pk",
"else",
"is",
"returned",
"object",
"from",
"get_obj",
"method",
"but",
"it",
"search",
"only",
"inside",
"filtered",
"values",
"for",
"current",
"user",
"finally",
... | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/generic_views/form_views.py#L652-L669 |
intelligenia/modeltranslation | modeltranslation/admin/views.py | view_all | def view_all(request, language, filter=None):
"""
View all translations that are in site.
"""
# Is there any filter?
if request.method == "POST":
data = request.POST.dict()
if not data["search"] or data["search"]=="":
return HttpResponseRedirect(reverse("modeltranslation:view_all_url",args=(data["language... | python | def view_all(request, language, filter=None):
"""
View all translations that are in site.
"""
# Is there any filter?
if request.method == "POST":
data = request.POST.dict()
if not data["search"] or data["search"]=="":
return HttpResponseRedirect(reverse("modeltranslation:view_all_url",args=(data["language... | [
"def",
"view_all",
"(",
"request",
",",
"language",
",",
"filter",
"=",
"None",
")",
":",
"# Is there any filter?",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"data",
"=",
"request",
".",
"POST",
".",
"dict",
"(",
")",
"if",
"not",
"data",
... | View all translations that are in site. | [
"View",
"all",
"translations",
"that",
"are",
"in",
"site",
"."
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/admin/views.py#L27-L74 |
intelligenia/modeltranslation | modeltranslation/admin/views.py | edit | def edit(request, translation):
"""
Edit a translation.
@param request: Django HttpRequest object.
@param translation: Translation id
@return Django HttpResponse object with the view or a redirection.
"""
translation = get_object_or_404(FieldTranslation, id=translation)
if request.method == 'POST':
if "cancel... | python | def edit(request, translation):
"""
Edit a translation.
@param request: Django HttpRequest object.
@param translation: Translation id
@return Django HttpResponse object with the view or a redirection.
"""
translation = get_object_or_404(FieldTranslation, id=translation)
if request.method == 'POST':
if "cancel... | [
"def",
"edit",
"(",
"request",
",",
"translation",
")",
":",
"translation",
"=",
"get_object_or_404",
"(",
"FieldTranslation",
",",
"id",
"=",
"translation",
")",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"if",
"\"cancel\"",
"in",
"request",
".",
... | Edit a translation.
@param request: Django HttpRequest object.
@param translation: Translation id
@return Django HttpResponse object with the view or a redirection. | [
"Edit",
"a",
"translation",
"."
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/admin/views.py#L80-L107 |
intelligenia/modeltranslation | modeltranslation/admin/views.py | export_translations | def export_translations(request, language):
"""
Export translations view.
"""
FieldTranslation.delete_orphan_translations()
translations = FieldTranslation.objects.filter(lang=language)
for trans in translations:
trans.source_text = trans.source_text.replace("'","\'").replace("\"","\\\"")
trans.translation = ... | python | def export_translations(request, language):
"""
Export translations view.
"""
FieldTranslation.delete_orphan_translations()
translations = FieldTranslation.objects.filter(lang=language)
for trans in translations:
trans.source_text = trans.source_text.replace("'","\'").replace("\"","\\\"")
trans.translation = ... | [
"def",
"export_translations",
"(",
"request",
",",
"language",
")",
":",
"FieldTranslation",
".",
"delete_orphan_translations",
"(",
")",
"translations",
"=",
"FieldTranslation",
".",
"objects",
".",
"filter",
"(",
"lang",
"=",
"language",
")",
"for",
"trans",
"... | Export translations view. | [
"Export",
"translations",
"view",
"."
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/admin/views.py#L182-L199 |
intelligenia/modeltranslation | modeltranslation/admin/views.py | update_translations | def update_translations(request):
"""
Update translations: delete orphan translations and creates empty translations for new objects in database.
"""
FieldTranslation.delete_orphan_translations()
num_translations = FieldTranslation.update_translations()
return render_to_response('modeltranslation/admin/update_tra... | python | def update_translations(request):
"""
Update translations: delete orphan translations and creates empty translations for new objects in database.
"""
FieldTranslation.delete_orphan_translations()
num_translations = FieldTranslation.update_translations()
return render_to_response('modeltranslation/admin/update_tra... | [
"def",
"update_translations",
"(",
"request",
")",
":",
"FieldTranslation",
".",
"delete_orphan_translations",
"(",
")",
"num_translations",
"=",
"FieldTranslation",
".",
"update_translations",
"(",
")",
"return",
"render_to_response",
"(",
"'modeltranslation/admin/update_t... | Update translations: delete orphan translations and creates empty translations for new objects in database. | [
"Update",
"translations",
":",
"delete",
"orphan",
"translations",
"and",
"creates",
"empty",
"translations",
"for",
"new",
"objects",
"in",
"database",
"."
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/admin/views.py#L205-L211 |
qba73/circleclient | circleclient/circleclient.py | CircleClient.client_get | def client_get(self, url, **kwargs):
"""Send GET request with given url."""
response = requests.get(self.make_url(url), headers=self.headers)
if not response.ok:
raise Exception(
'{status}: {reason}.\nCircleCI Status NOT OK'.format(
status=response... | python | def client_get(self, url, **kwargs):
"""Send GET request with given url."""
response = requests.get(self.make_url(url), headers=self.headers)
if not response.ok:
raise Exception(
'{status}: {reason}.\nCircleCI Status NOT OK'.format(
status=response... | [
"def",
"client_get",
"(",
"self",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"make_url",
"(",
"url",
")",
",",
"headers",
"=",
"self",
".",
"headers",
")",
"if",
"not",
"response",
".",... | Send GET request with given url. | [
"Send",
"GET",
"request",
"with",
"given",
"url",
"."
] | train | https://github.com/qba73/circleclient/blob/8bf5b093e416c899cc39e43a770c17a5466487b0/circleclient/circleclient.py#L37-L44 |
qba73/circleclient | circleclient/circleclient.py | CircleClient.client_post | def client_post(self, url, **kwargs):
"""Send POST request with given url and keyword args."""
response = requests.post(self.make_url(url),
data=json.dumps(kwargs),
headers=self.headers)
if not response.ok:
raise Excep... | python | def client_post(self, url, **kwargs):
"""Send POST request with given url and keyword args."""
response = requests.post(self.make_url(url),
data=json.dumps(kwargs),
headers=self.headers)
if not response.ok:
raise Excep... | [
"def",
"client_post",
"(",
"self",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"requests",
".",
"post",
"(",
"self",
".",
"make_url",
"(",
"url",
")",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"kwargs",
")",
",",
"headers",
... | Send POST request with given url and keyword args. | [
"Send",
"POST",
"request",
"with",
"given",
"url",
"and",
"keyword",
"args",
"."
] | train | https://github.com/qba73/circleclient/blob/8bf5b093e416c899cc39e43a770c17a5466487b0/circleclient/circleclient.py#L46-L55 |
qba73/circleclient | circleclient/circleclient.py | CircleClient.client_delete | def client_delete(self, url, **kwargs):
"""Send POST request with given url."""
response = requests.delete(self.make_url(url), headers=self.headers)
if not response.ok:
raise Exception(
'{status}: {reason}.\nCircleCI Status NOT OK'.format(
status=r... | python | def client_delete(self, url, **kwargs):
"""Send POST request with given url."""
response = requests.delete(self.make_url(url), headers=self.headers)
if not response.ok:
raise Exception(
'{status}: {reason}.\nCircleCI Status NOT OK'.format(
status=r... | [
"def",
"client_delete",
"(",
"self",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"requests",
".",
"delete",
"(",
"self",
".",
"make_url",
"(",
"url",
")",
",",
"headers",
"=",
"self",
".",
"headers",
")",
"if",
"not",
"response",
... | Send POST request with given url. | [
"Send",
"POST",
"request",
"with",
"given",
"url",
"."
] | train | https://github.com/qba73/circleclient/blob/8bf5b093e416c899cc39e43a770c17a5466487b0/circleclient/circleclient.py#L57-L64 |
qba73/circleclient | circleclient/circleclient.py | Projects.list_projects | def list_projects(self):
"""Return a list of all followed projects."""
method = 'GET'
url = '/projects?circle-token={token}'.format(
token=self.client.api_token)
json_data = self.client.request(method, url)
return json_data | python | def list_projects(self):
"""Return a list of all followed projects."""
method = 'GET'
url = '/projects?circle-token={token}'.format(
token=self.client.api_token)
json_data = self.client.request(method, url)
return json_data | [
"def",
"list_projects",
"(",
"self",
")",
":",
"method",
"=",
"'GET'",
"url",
"=",
"'/projects?circle-token={token}'",
".",
"format",
"(",
"token",
"=",
"self",
".",
"client",
".",
"api_token",
")",
"json_data",
"=",
"self",
".",
"client",
".",
"request",
... | Return a list of all followed projects. | [
"Return",
"a",
"list",
"of",
"all",
"followed",
"projects",
"."
] | train | https://github.com/qba73/circleclient/blob/8bf5b093e416c899cc39e43a770c17a5466487b0/circleclient/circleclient.py#L97-L103 |
qba73/circleclient | circleclient/circleclient.py | Build.trigger | def trigger(self, username, project, branch, **build_params):
"""Trigger new build and return a summary of the build."""
method = 'POST'
url = ('/project/{username}/{project}/tree/{branch}?'
'circle-token={token}'.format(
username=username, project=project,
... | python | def trigger(self, username, project, branch, **build_params):
"""Trigger new build and return a summary of the build."""
method = 'POST'
url = ('/project/{username}/{project}/tree/{branch}?'
'circle-token={token}'.format(
username=username, project=project,
... | [
"def",
"trigger",
"(",
"self",
",",
"username",
",",
"project",
",",
"branch",
",",
"*",
"*",
"build_params",
")",
":",
"method",
"=",
"'POST'",
"url",
"=",
"(",
"'/project/{username}/{project}/tree/{branch}?'",
"'circle-token={token}'",
".",
"format",
"(",
"use... | Trigger new build and return a summary of the build. | [
"Trigger",
"new",
"build",
"and",
"return",
"a",
"summary",
"of",
"the",
"build",
"."
] | train | https://github.com/qba73/circleclient/blob/8bf5b093e416c899cc39e43a770c17a5466487b0/circleclient/circleclient.py#L111-L124 |
qba73/circleclient | circleclient/circleclient.py | Build.cancel | def cancel(self, username, project, build_num):
"""Cancel the build and return its summary."""
method = 'POST'
url = ('/project/{username}/{project}/{build_num}/cancel?'
'circle-token={token}'.format(username=username,
project=project,
... | python | def cancel(self, username, project, build_num):
"""Cancel the build and return its summary."""
method = 'POST'
url = ('/project/{username}/{project}/{build_num}/cancel?'
'circle-token={token}'.format(username=username,
project=project,
... | [
"def",
"cancel",
"(",
"self",
",",
"username",
",",
"project",
",",
"build_num",
")",
":",
"method",
"=",
"'POST'",
"url",
"=",
"(",
"'/project/{username}/{project}/{build_num}/cancel?'",
"'circle-token={token}'",
".",
"format",
"(",
"username",
"=",
"username",
"... | Cancel the build and return its summary. | [
"Cancel",
"the",
"build",
"and",
"return",
"its",
"summary",
"."
] | train | https://github.com/qba73/circleclient/blob/8bf5b093e416c899cc39e43a770c17a5466487b0/circleclient/circleclient.py#L126-L135 |
qba73/circleclient | circleclient/circleclient.py | Build.recent_all_projects | def recent_all_projects(self, limit=30, offset=0):
"""Return information about recent builds across all projects.
Args:
limit (int), Number of builds to return, max=100, defaults=30.
offset (int): Builds returned from this point, default=0.
Returns:
A list o... | python | def recent_all_projects(self, limit=30, offset=0):
"""Return information about recent builds across all projects.
Args:
limit (int), Number of builds to return, max=100, defaults=30.
offset (int): Builds returned from this point, default=0.
Returns:
A list o... | [
"def",
"recent_all_projects",
"(",
"self",
",",
"limit",
"=",
"30",
",",
"offset",
"=",
"0",
")",
":",
"method",
"=",
"'GET'",
"url",
"=",
"(",
"'/recent-builds?circle-token={token}&limit={limit}&'",
"'offset={offset}'",
".",
"format",
"(",
"token",
"=",
"self",... | Return information about recent builds across all projects.
Args:
limit (int), Number of builds to return, max=100, defaults=30.
offset (int): Builds returned from this point, default=0.
Returns:
A list of dictionaries. | [
"Return",
"information",
"about",
"recent",
"builds",
"across",
"all",
"projects",
"."
] | train | https://github.com/qba73/circleclient/blob/8bf5b093e416c899cc39e43a770c17a5466487b0/circleclient/circleclient.py#L173-L189 |
qba73/circleclient | circleclient/circleclient.py | Build.recent | def recent(self, username, project, limit=1, offset=0, branch=None, status_filter=""):
"""Return status of recent builds for given project.
Retrieves build statuses for given project and branch. If branch is
None it retrieves most recent build.
Args:
username (str): Name o... | python | def recent(self, username, project, limit=1, offset=0, branch=None, status_filter=""):
"""Return status of recent builds for given project.
Retrieves build statuses for given project and branch. If branch is
None it retrieves most recent build.
Args:
username (str): Name o... | [
"def",
"recent",
"(",
"self",
",",
"username",
",",
"project",
",",
"limit",
"=",
"1",
",",
"offset",
"=",
"0",
",",
"branch",
"=",
"None",
",",
"status_filter",
"=",
"\"\"",
")",
":",
"method",
"=",
"'GET'",
"if",
"branch",
"is",
"not",
"None",
":... | Return status of recent builds for given project.
Retrieves build statuses for given project and branch. If branch is
None it retrieves most recent build.
Args:
username (str): Name of the user.
project (str): Name of the project.
limit (int): Number of b... | [
"Return",
"status",
"of",
"recent",
"builds",
"for",
"given",
"project",
"."
] | train | https://github.com/qba73/circleclient/blob/8bf5b093e416c899cc39e43a770c17a5466487b0/circleclient/circleclient.py#L191-L225 |
qba73/circleclient | circleclient/circleclient.py | Cache.clear | def clear(self, username, project):
"""Clear the cache for given project."""
method = 'DELETE'
url = ('/project/{username}/{project}/build-cache?'
'circle-token={token}'.format(username=username,
project=project,
... | python | def clear(self, username, project):
"""Clear the cache for given project."""
method = 'DELETE'
url = ('/project/{username}/{project}/build-cache?'
'circle-token={token}'.format(username=username,
project=project,
... | [
"def",
"clear",
"(",
"self",
",",
"username",
",",
"project",
")",
":",
"method",
"=",
"'DELETE'",
"url",
"=",
"(",
"'/project/{username}/{project}/build-cache?'",
"'circle-token={token}'",
".",
"format",
"(",
"username",
"=",
"username",
",",
"project",
"=",
"p... | Clear the cache for given project. | [
"Clear",
"the",
"cache",
"for",
"given",
"project",
"."
] | train | https://github.com/qba73/circleclient/blob/8bf5b093e416c899cc39e43a770c17a5466487b0/circleclient/circleclient.py#L233-L241 |
The-Politico/django-slackchat-serializer | slackchat/views/api/channel.py | ChannelDeserializer.post | def post(self, request, format=None):
"""
Add a new Channel.
"""
data = request.data.copy()
# Get chat type record
try:
ct = ChatType.objects.get(pk=data.pop("chat_type"))
data["chat_type"] = ct
except ChatType.DoesNotExist:
re... | python | def post(self, request, format=None):
"""
Add a new Channel.
"""
data = request.data.copy()
# Get chat type record
try:
ct = ChatType.objects.get(pk=data.pop("chat_type"))
data["chat_type"] = ct
except ChatType.DoesNotExist:
re... | [
"def",
"post",
"(",
"self",
",",
"request",
",",
"format",
"=",
"None",
")",
":",
"data",
"=",
"request",
".",
"data",
".",
"copy",
"(",
")",
"# Get chat type record",
"try",
":",
"ct",
"=",
"ChatType",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"... | Add a new Channel. | [
"Add",
"a",
"new",
"Channel",
"."
] | train | https://github.com/The-Politico/django-slackchat-serializer/blob/9a41e0477d1bc7bb2ec3f8af40baddf8d4230d40/slackchat/views/api/channel.py#L66-L103 |
The-Politico/django-slackchat-serializer | slackchat/views/api/channel.py | ChannelDeserializer.patch | def patch(self, request, format=None):
"""
Update an existing Channel
"""
data = request.data.copy()
# Get chat type record
try:
ct = ChatType.objects.get(id=data.pop("chat_type"))
data["chat_type"] = ct
except ChatType.DoesNotExist:
... | python | def patch(self, request, format=None):
"""
Update an existing Channel
"""
data = request.data.copy()
# Get chat type record
try:
ct = ChatType.objects.get(id=data.pop("chat_type"))
data["chat_type"] = ct
except ChatType.DoesNotExist:
... | [
"def",
"patch",
"(",
"self",
",",
"request",
",",
"format",
"=",
"None",
")",
":",
"data",
"=",
"request",
".",
"data",
".",
"copy",
"(",
")",
"# Get chat type record",
"try",
":",
"ct",
"=",
"ChatType",
".",
"objects",
".",
"get",
"(",
"id",
"=",
... | Update an existing Channel | [
"Update",
"an",
"existing",
"Channel"
] | train | https://github.com/The-Politico/django-slackchat-serializer/blob/9a41e0477d1bc7bb2ec3f8af40baddf8d4230d40/slackchat/views/api/channel.py#L105-L143 |
StorjOld/file-encryptor | file_encryptor/key_generators.py | sha256_file | def sha256_file(path):
"""Calculate sha256 hex digest of a file.
:param path: The path of the file you are calculating the digest of.
:type path: str
:returns: The sha256 hex digest of the specified file.
:rtype: builtin_function_or_method
"""
h = hashlib.sha256()
with open(path, 'rb')... | python | def sha256_file(path):
"""Calculate sha256 hex digest of a file.
:param path: The path of the file you are calculating the digest of.
:type path: str
:returns: The sha256 hex digest of the specified file.
:rtype: builtin_function_or_method
"""
h = hashlib.sha256()
with open(path, 'rb')... | [
"def",
"sha256_file",
"(",
"path",
")",
":",
"h",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"f",
":",
"for",
"chunk",
"in",
"iter",
"(",
"lambda",
":",
"f",
".",
"read",
"(",
"CHUNK_SIZE",
")",
... | Calculate sha256 hex digest of a file.
:param path: The path of the file you are calculating the digest of.
:type path: str
:returns: The sha256 hex digest of the specified file.
:rtype: builtin_function_or_method | [
"Calculate",
"sha256",
"hex",
"digest",
"of",
"a",
"file",
"."
] | train | https://github.com/StorjOld/file-encryptor/blob/245191c45dbd68e09a4a8f07c5d7331be195dc6b/file_encryptor/key_generators.py#L32-L46 |
StorjOld/file-encryptor | file_encryptor/key_generators.py | key_from_file | def key_from_file(filename, passphrase):
"""Calculate convergent encryption key.
This takes a filename and an optional passphrase.
If no passphrase is given, a default is used.
Using the default passphrase means you will be
vulnerable to confirmation attacks and
learn-partial-information attack... | python | def key_from_file(filename, passphrase):
"""Calculate convergent encryption key.
This takes a filename and an optional passphrase.
If no passphrase is given, a default is used.
Using the default passphrase means you will be
vulnerable to confirmation attacks and
learn-partial-information attack... | [
"def",
"key_from_file",
"(",
"filename",
",",
"passphrase",
")",
":",
"hexdigest",
"=",
"sha256_file",
"(",
"filename",
")",
"if",
"passphrase",
"is",
"None",
":",
"passphrase",
"=",
"DEFAULT_HMAC_PASSPHRASE",
"return",
"keyed_hash",
"(",
"hexdigest",
",",
"pass... | Calculate convergent encryption key.
This takes a filename and an optional passphrase.
If no passphrase is given, a default is used.
Using the default passphrase means you will be
vulnerable to confirmation attacks and
learn-partial-information attacks.
:param filename: The filename you want t... | [
"Calculate",
"convergent",
"encryption",
"key",
"."
] | train | https://github.com/StorjOld/file-encryptor/blob/245191c45dbd68e09a4a8f07c5d7331be195dc6b/file_encryptor/key_generators.py#L49-L70 |
StorjOld/file-encryptor | file_encryptor/key_generators.py | keyed_hash | def keyed_hash(digest, passphrase):
"""Calculate a HMAC/keyed hash.
:param digest: Digest used to create hash.
:type digest: str
:param passphrase: Passphrase used to generate the hash.
:type passphrase: str
:returns: HMAC/keyed hash.
:rtype: str
"""
encodedPassphrase = passphrase.e... | python | def keyed_hash(digest, passphrase):
"""Calculate a HMAC/keyed hash.
:param digest: Digest used to create hash.
:type digest: str
:param passphrase: Passphrase used to generate the hash.
:type passphrase: str
:returns: HMAC/keyed hash.
:rtype: str
"""
encodedPassphrase = passphrase.e... | [
"def",
"keyed_hash",
"(",
"digest",
",",
"passphrase",
")",
":",
"encodedPassphrase",
"=",
"passphrase",
".",
"encode",
"(",
")",
"encodedDigest",
"=",
"digest",
".",
"encode",
"(",
")",
"return",
"hmac",
".",
"new",
"(",
"encodedPassphrase",
",",
"encodedDi... | Calculate a HMAC/keyed hash.
:param digest: Digest used to create hash.
:type digest: str
:param passphrase: Passphrase used to generate the hash.
:type passphrase: str
:returns: HMAC/keyed hash.
:rtype: str | [
"Calculate",
"a",
"HMAC",
"/",
"keyed",
"hash",
"."
] | train | https://github.com/StorjOld/file-encryptor/blob/245191c45dbd68e09a4a8f07c5d7331be195dc6b/file_encryptor/key_generators.py#L73-L86 |
IwoHerka/sexpr | sexpr/utils.py | find_child | def find_child(sexpr: Sexpr, *tags: str) -> Optional[Sexpr]:
"""Search for a tag among direct children of the s-expression."""
_assert_valid_sexpr(sexpr)
for child in sexpr[1:]:
if _is_sexpr(child) and child[0] in tags:
return child
return None | python | def find_child(sexpr: Sexpr, *tags: str) -> Optional[Sexpr]:
"""Search for a tag among direct children of the s-expression."""
_assert_valid_sexpr(sexpr)
for child in sexpr[1:]:
if _is_sexpr(child) and child[0] in tags:
return child
return None | [
"def",
"find_child",
"(",
"sexpr",
":",
"Sexpr",
",",
"*",
"tags",
":",
"str",
")",
"->",
"Optional",
"[",
"Sexpr",
"]",
":",
"_assert_valid_sexpr",
"(",
"sexpr",
")",
"for",
"child",
"in",
"sexpr",
"[",
"1",
":",
"]",
":",
"if",
"_is_sexpr",
"(",
... | Search for a tag among direct children of the s-expression. | [
"Search",
"for",
"a",
"tag",
"among",
"direct",
"children",
"of",
"the",
"s",
"-",
"expression",
"."
] | train | https://github.com/IwoHerka/sexpr/blob/28e32f543a127bbbf832b2dba7cb93f9e57db3b6/sexpr/utils.py#L51-L59 |
matllubos/django-is-core | is_core/forms/widgets.py | WrapperWidget.build_attrs | def build_attrs(self, *args, **kwargs):
"Helper function for building an attribute dictionary."
self.attrs = self.widget.build_attrs(*args, **kwargs)
return self.attrs | python | def build_attrs(self, *args, **kwargs):
"Helper function for building an attribute dictionary."
self.attrs = self.widget.build_attrs(*args, **kwargs)
return self.attrs | [
"def",
"build_attrs",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"attrs",
"=",
"self",
".",
"widget",
".",
"build_attrs",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"attrs"
] | Helper function for building an attribute dictionary. | [
"Helper",
"function",
"for",
"building",
"an",
"attribute",
"dictionary",
"."
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/forms/widgets.py#L52-L55 |
matllubos/django-is-core | is_core/forms/widgets.py | ClearableFileInput.get_template_substitution_values | def get_template_substitution_values(self, value):
"""
Return value-related substitutions.
"""
return {
'initial': os.path.basename(conditional_escape(value)),
'initial_url': conditional_escape(value.url),
} | python | def get_template_substitution_values(self, value):
"""
Return value-related substitutions.
"""
return {
'initial': os.path.basename(conditional_escape(value)),
'initial_url': conditional_escape(value.url),
} | [
"def",
"get_template_substitution_values",
"(",
"self",
",",
"value",
")",
":",
"return",
"{",
"'initial'",
":",
"os",
".",
"path",
".",
"basename",
"(",
"conditional_escape",
"(",
"value",
")",
")",
",",
"'initial_url'",
":",
"conditional_escape",
"(",
"value... | Return value-related substitutions. | [
"Return",
"value",
"-",
"related",
"substitutions",
"."
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/forms/widgets.py#L109-L116 |
matllubos/django-is-core | is_core/forms/widgets.py | RestrictedSelectWidgetMixin.is_restricted | def is_restricted(self):
"""
Returns True or False according to number of objects in queryset.
If queryset contains too much objects the widget will be restricted and won't be used select box with choices.
"""
return (
not hasattr(self.choices, 'queryset') or
... | python | def is_restricted(self):
"""
Returns True or False according to number of objects in queryset.
If queryset contains too much objects the widget will be restricted and won't be used select box with choices.
"""
return (
not hasattr(self.choices, 'queryset') or
... | [
"def",
"is_restricted",
"(",
"self",
")",
":",
"return",
"(",
"not",
"hasattr",
"(",
"self",
".",
"choices",
",",
"'queryset'",
")",
"or",
"self",
".",
"choices",
".",
"queryset",
".",
"count",
"(",
")",
">",
"settings",
".",
"FOREIGN_KEY_MAX_SELECBOX_ENTR... | Returns True or False according to number of objects in queryset.
If queryset contains too much objects the widget will be restricted and won't be used select box with choices. | [
"Returns",
"True",
"or",
"False",
"according",
"to",
"number",
"of",
"objects",
"in",
"queryset",
".",
"If",
"queryset",
"contains",
"too",
"much",
"objects",
"the",
"widget",
"will",
"be",
"restricted",
"and",
"won",
"t",
"be",
"used",
"select",
"box",
"w... | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/forms/widgets.py#L412-L420 |
codeforamerica/three | three/api.py | city | def city(name=None):
"""
Store the city that will be queried against.
>>> three.city('sf')
"""
info = find_info(name)
os.environ['OPEN311_CITY_INFO'] = dumps(info)
return Three(**info) | python | def city(name=None):
"""
Store the city that will be queried against.
>>> three.city('sf')
"""
info = find_info(name)
os.environ['OPEN311_CITY_INFO'] = dumps(info)
return Three(**info) | [
"def",
"city",
"(",
"name",
"=",
"None",
")",
":",
"info",
"=",
"find_info",
"(",
"name",
")",
"os",
".",
"environ",
"[",
"'OPEN311_CITY_INFO'",
"]",
"=",
"dumps",
"(",
"info",
")",
"return",
"Three",
"(",
"*",
"*",
"info",
")"
] | Store the city that will be queried against.
>>> three.city('sf') | [
"Store",
"the",
"city",
"that",
"will",
"be",
"queried",
"against",
"."
] | train | https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/api.py#L23-L31 |
codeforamerica/three | three/api.py | dev | def dev(endpoint, **kwargs):
"""
Use an endpoint and any additional keyword arguments rather than one
of the pre-defined cities. Similar to the `city` function, but useful for
development.
"""
kwargs['endpoint'] = endpoint
os.environ['OPEN311_CITY_INFO'] = dumps(kwargs)
return Three(**kw... | python | def dev(endpoint, **kwargs):
"""
Use an endpoint and any additional keyword arguments rather than one
of the pre-defined cities. Similar to the `city` function, but useful for
development.
"""
kwargs['endpoint'] = endpoint
os.environ['OPEN311_CITY_INFO'] = dumps(kwargs)
return Three(**kw... | [
"def",
"dev",
"(",
"endpoint",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'endpoint'",
"]",
"=",
"endpoint",
"os",
".",
"environ",
"[",
"'OPEN311_CITY_INFO'",
"]",
"=",
"dumps",
"(",
"kwargs",
")",
"return",
"Three",
"(",
"*",
"*",
"kwargs",
... | Use an endpoint and any additional keyword arguments rather than one
of the pre-defined cities. Similar to the `city` function, but useful for
development. | [
"Use",
"an",
"endpoint",
"and",
"any",
"additional",
"keyword",
"arguments",
"rather",
"than",
"one",
"of",
"the",
"pre",
"-",
"defined",
"cities",
".",
"Similar",
"to",
"the",
"city",
"function",
"but",
"useful",
"for",
"development",
"."
] | train | https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/api.py#L40-L48 |
matllubos/django-is-core | is_core/utils/__init__.py | flatten_fieldsets | def flatten_fieldsets(fieldsets):
"""Returns a list of field names from an admin fieldsets structure."""
field_names = []
for _, opts in fieldsets or ():
if 'fieldsets' in opts:
field_names += flatten_fieldsets(opts.get('fieldsets'))
else:
for field in opts.get('field... | python | def flatten_fieldsets(fieldsets):
"""Returns a list of field names from an admin fieldsets structure."""
field_names = []
for _, opts in fieldsets or ():
if 'fieldsets' in opts:
field_names += flatten_fieldsets(opts.get('fieldsets'))
else:
for field in opts.get('field... | [
"def",
"flatten_fieldsets",
"(",
"fieldsets",
")",
":",
"field_names",
"=",
"[",
"]",
"for",
"_",
",",
"opts",
"in",
"fieldsets",
"or",
"(",
")",
":",
"if",
"'fieldsets'",
"in",
"opts",
":",
"field_names",
"+=",
"flatten_fieldsets",
"(",
"opts",
".",
"ge... | Returns a list of field names from an admin fieldsets structure. | [
"Returns",
"a",
"list",
"of",
"field",
"names",
"from",
"an",
"admin",
"fieldsets",
"structure",
"."
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/utils/__init__.py#L44-L56 |
matllubos/django-is-core | is_core/utils/__init__.py | get_inline_views_from_fieldsets | def get_inline_views_from_fieldsets(fieldsets):
"""Returns a list of field names from an admin fieldsets structure."""
inline_views = []
for _, opts in fieldsets or ():
if 'fieldsets' in opts:
inline_views += get_inline_views_from_fieldsets(opts.get('fieldsets'))
elif 'inline_vie... | python | def get_inline_views_from_fieldsets(fieldsets):
"""Returns a list of field names from an admin fieldsets structure."""
inline_views = []
for _, opts in fieldsets or ():
if 'fieldsets' in opts:
inline_views += get_inline_views_from_fieldsets(opts.get('fieldsets'))
elif 'inline_vie... | [
"def",
"get_inline_views_from_fieldsets",
"(",
"fieldsets",
")",
":",
"inline_views",
"=",
"[",
"]",
"for",
"_",
",",
"opts",
"in",
"fieldsets",
"or",
"(",
")",
":",
"if",
"'fieldsets'",
"in",
"opts",
":",
"inline_views",
"+=",
"get_inline_views_from_fieldsets",... | Returns a list of field names from an admin fieldsets structure. | [
"Returns",
"a",
"list",
"of",
"field",
"names",
"from",
"an",
"admin",
"fieldsets",
"structure",
"."
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/utils/__init__.py#L59-L67 |
matllubos/django-is-core | is_core/utils/__init__.py | get_inline_views_opts_from_fieldsets | def get_inline_views_opts_from_fieldsets(fieldsets):
"""Returns a list of field names from an admin fieldsets structure."""
inline_views = []
for _, opts in fieldsets or ():
if 'fieldsets' in opts:
inline_views += get_inline_views_opts_from_fieldsets(opts.get('fieldsets'))
elif '... | python | def get_inline_views_opts_from_fieldsets(fieldsets):
"""Returns a list of field names from an admin fieldsets structure."""
inline_views = []
for _, opts in fieldsets or ():
if 'fieldsets' in opts:
inline_views += get_inline_views_opts_from_fieldsets(opts.get('fieldsets'))
elif '... | [
"def",
"get_inline_views_opts_from_fieldsets",
"(",
"fieldsets",
")",
":",
"inline_views",
"=",
"[",
"]",
"for",
"_",
",",
"opts",
"in",
"fieldsets",
"or",
"(",
")",
":",
"if",
"'fieldsets'",
"in",
"opts",
":",
"inline_views",
"+=",
"get_inline_views_opts_from_f... | Returns a list of field names from an admin fieldsets structure. | [
"Returns",
"a",
"list",
"of",
"field",
"names",
"from",
"an",
"admin",
"fieldsets",
"structure",
"."
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/utils/__init__.py#L70-L78 |
matllubos/django-is-core | is_core/utils/__init__.py | get_readonly_field_data | def get_readonly_field_data(field_name, instance, view=None, fun_kwargs=None):
"""
Returns field humanized value, label and widget which are used to display of instance or view readonly data.
Args:
field_name: name of the field which will be displayed
instance: model instance
view: v... | python | def get_readonly_field_data(field_name, instance, view=None, fun_kwargs=None):
"""
Returns field humanized value, label and widget which are used to display of instance or view readonly data.
Args:
field_name: name of the field which will be displayed
instance: model instance
view: v... | [
"def",
"get_readonly_field_data",
"(",
"field_name",
",",
"instance",
",",
"view",
"=",
"None",
",",
"fun_kwargs",
"=",
"None",
")",
":",
"fun_kwargs",
"=",
"fun_kwargs",
"or",
"{",
"}",
"if",
"view",
":",
"view_readonly_data",
"=",
"_get_view_readonly_data",
... | Returns field humanized value, label and widget which are used to display of instance or view readonly data.
Args:
field_name: name of the field which will be displayed
instance: model instance
view: view instance
fun_kwargs: kwargs that can be used inside method call
Returns:
... | [
"Returns",
"field",
"humanized",
"value",
"label",
"and",
"widget",
"which",
"are",
"used",
"to",
"display",
"of",
"instance",
"or",
"view",
"readonly",
"data",
".",
"Args",
":",
"field_name",
":",
"name",
"of",
"the",
"field",
"which",
"will",
"be",
"disp... | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/utils/__init__.py#L223-L246 |
matllubos/django-is-core | is_core/utils/__init__.py | display_object_data | def display_object_data(obj, field_name, request=None):
"""
Returns humanized value of model object that can be rendered to HTML or returned as part of REST
examples:
boolean True/Talse ==> Yes/No
objects ==> object display name with link if current user has permissions to see the object
... | python | def display_object_data(obj, field_name, request=None):
"""
Returns humanized value of model object that can be rendered to HTML or returned as part of REST
examples:
boolean True/Talse ==> Yes/No
objects ==> object display name with link if current user has permissions to see the object
... | [
"def",
"display_object_data",
"(",
"obj",
",",
"field_name",
",",
"request",
"=",
"None",
")",
":",
"from",
"is_core",
".",
"forms",
".",
"utils",
"import",
"ReadonlyValue",
"value",
",",
"_",
",",
"_",
"=",
"get_readonly_field_data",
"(",
"field_name",
",",... | Returns humanized value of model object that can be rendered to HTML or returned as part of REST
examples:
boolean True/Talse ==> Yes/No
objects ==> object display name with link if current user has permissions to see the object
field with choices ==> string value of choice
field with h... | [
"Returns",
"humanized",
"value",
"of",
"model",
"object",
"that",
"can",
"be",
"rendered",
"to",
"HTML",
"or",
"returned",
"as",
"part",
"of",
"REST"
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/utils/__init__.py#L249-L262 |
matllubos/django-is-core | is_core/utils/__init__.py | display_for_value | def display_for_value(value, request=None):
"""
Converts humanized value
examples:
boolean True/Talse ==> Yes/No
objects ==> object display name with link if current user has permissions to see the object
datetime ==> in localized format
"""
from is_core.utils.compatibility ... | python | def display_for_value(value, request=None):
"""
Converts humanized value
examples:
boolean True/Talse ==> Yes/No
objects ==> object display name with link if current user has permissions to see the object
datetime ==> in localized format
"""
from is_core.utils.compatibility ... | [
"def",
"display_for_value",
"(",
"value",
",",
"request",
"=",
"None",
")",
":",
"from",
"is_core",
".",
"utils",
".",
"compatibility",
"import",
"admin_display_for_value",
"if",
"request",
"and",
"isinstance",
"(",
"value",
",",
"Model",
")",
":",
"return",
... | Converts humanized value
examples:
boolean True/Talse ==> Yes/No
objects ==> object display name with link if current user has permissions to see the object
datetime ==> in localized format | [
"Converts",
"humanized",
"value"
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/utils/__init__.py#L265-L281 |
matllubos/django-is-core | is_core/utils/__init__.py | get_url_from_model_core | def get_url_from_model_core(request, obj):
"""
Returns object URL from model core.
"""
from is_core.site import get_model_core
model_core = get_model_core(obj.__class__)
if model_core and hasattr(model_core, 'ui_patterns'):
edit_pattern = model_core.ui_patterns.get('detail')
ret... | python | def get_url_from_model_core(request, obj):
"""
Returns object URL from model core.
"""
from is_core.site import get_model_core
model_core = get_model_core(obj.__class__)
if model_core and hasattr(model_core, 'ui_patterns'):
edit_pattern = model_core.ui_patterns.get('detail')
ret... | [
"def",
"get_url_from_model_core",
"(",
"request",
",",
"obj",
")",
":",
"from",
"is_core",
".",
"site",
"import",
"get_model_core",
"model_core",
"=",
"get_model_core",
"(",
"obj",
".",
"__class__",
")",
"if",
"model_core",
"and",
"hasattr",
"(",
"model_core",
... | Returns object URL from model core. | [
"Returns",
"object",
"URL",
"from",
"model",
"core",
"."
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/utils/__init__.py#L284-L298 |
matllubos/django-is-core | is_core/utils/__init__.py | get_obj_url | def get_obj_url(request, obj):
"""
Returns object URL if current logged user has permissions to see the object
"""
if (is_callable(getattr(obj, 'get_absolute_url', None)) and
(not hasattr(obj, 'can_see_edit_link') or
(is_callable(getattr(obj, 'can_see_edit_link', None)) and obj.... | python | def get_obj_url(request, obj):
"""
Returns object URL if current logged user has permissions to see the object
"""
if (is_callable(getattr(obj, 'get_absolute_url', None)) and
(not hasattr(obj, 'can_see_edit_link') or
(is_callable(getattr(obj, 'can_see_edit_link', None)) and obj.... | [
"def",
"get_obj_url",
"(",
"request",
",",
"obj",
")",
":",
"if",
"(",
"is_callable",
"(",
"getattr",
"(",
"obj",
",",
"'get_absolute_url'",
",",
"None",
")",
")",
"and",
"(",
"not",
"hasattr",
"(",
"obj",
",",
"'can_see_edit_link'",
")",
"or",
"(",
"i... | Returns object URL if current logged user has permissions to see the object | [
"Returns",
"object",
"URL",
"if",
"current",
"logged",
"user",
"has",
"permissions",
"to",
"see",
"the",
"object"
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/utils/__init__.py#L301-L310 |
matllubos/django-is-core | is_core/utils/__init__.py | get_link_or_none | def get_link_or_none(pattern_name, request, view_kwargs=None):
"""
Helper that generate URL prom pattern name and kwargs and check if current request has permission to open the URL.
If not None is returned.
Args:
pattern_name (str): slug which is used for view registratin to pattern
req... | python | def get_link_or_none(pattern_name, request, view_kwargs=None):
"""
Helper that generate URL prom pattern name and kwargs and check if current request has permission to open the URL.
If not None is returned.
Args:
pattern_name (str): slug which is used for view registratin to pattern
req... | [
"def",
"get_link_or_none",
"(",
"pattern_name",
",",
"request",
",",
"view_kwargs",
"=",
"None",
")",
":",
"from",
"is_core",
".",
"patterns",
"import",
"reverse_pattern",
"pattern",
"=",
"reverse_pattern",
"(",
"pattern_name",
")",
"assert",
"pattern",
"is",
"n... | Helper that generate URL prom pattern name and kwargs and check if current request has permission to open the URL.
If not None is returned.
Args:
pattern_name (str): slug which is used for view registratin to pattern
request (django.http.request.HttpRequest): Django request object
view_... | [
"Helper",
"that",
"generate",
"URL",
"prom",
"pattern",
"name",
"and",
"kwargs",
"and",
"check",
"if",
"current",
"request",
"has",
"permission",
"to",
"open",
"the",
"URL",
".",
"If",
"not",
"None",
"is",
"returned",
"."
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/utils/__init__.py#L339-L360 |
matllubos/django-is-core | is_core/utils/__init__.py | GetMethodFieldMixin.get_method_returning_field_value | def get_method_returning_field_value(self, field_name):
"""
Method should return object method that can be used to get field value.
Args:
field_name: name of the field
Returns: method for obtaining a field value
"""
method = getattr(self, field_name, None)
... | python | def get_method_returning_field_value(self, field_name):
"""
Method should return object method that can be used to get field value.
Args:
field_name: name of the field
Returns: method for obtaining a field value
"""
method = getattr(self, field_name, None)
... | [
"def",
"get_method_returning_field_value",
"(",
"self",
",",
"field_name",
")",
":",
"method",
"=",
"getattr",
"(",
"self",
",",
"field_name",
",",
"None",
")",
"return",
"method",
"if",
"method",
"and",
"callable",
"(",
"method",
")",
"else",
"None"
] | Method should return object method that can be used to get field value.
Args:
field_name: name of the field
Returns: method for obtaining a field value | [
"Method",
"should",
"return",
"object",
"method",
"that",
"can",
"be",
"used",
"to",
"get",
"field",
"value",
".",
"Args",
":",
"field_name",
":",
"name",
"of",
"the",
"field"
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/utils/__init__.py#L365-L375 |
inveniosoftware/invenio-iiif | invenio_iiif/handlers.py | protect_api | def protect_api(uuid=None, **kwargs):
"""Retrieve object and check permissions.
Retrieve ObjectVersion of image being requested and check permission
using the Invenio-Files-REST permission factory.
"""
bucket, version_id, key = uuid.split(':', 2)
g.obj = ObjectResource.get_object(bucket, key, v... | python | def protect_api(uuid=None, **kwargs):
"""Retrieve object and check permissions.
Retrieve ObjectVersion of image being requested and check permission
using the Invenio-Files-REST permission factory.
"""
bucket, version_id, key = uuid.split(':', 2)
g.obj = ObjectResource.get_object(bucket, key, v... | [
"def",
"protect_api",
"(",
"uuid",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"bucket",
",",
"version_id",
",",
"key",
"=",
"uuid",
".",
"split",
"(",
"':'",
",",
"2",
")",
"g",
".",
"obj",
"=",
"ObjectResource",
".",
"get_object",
"(",
"bucke... | Retrieve object and check permissions.
Retrieve ObjectVersion of image being requested and check permission
using the Invenio-Files-REST permission factory. | [
"Retrieve",
"object",
"and",
"check",
"permissions",
"."
] | train | https://github.com/inveniosoftware/invenio-iiif/blob/e4f2f93eaabdc8e2efea81c239ab76d481191959/invenio_iiif/handlers.py#L29-L37 |
inveniosoftware/invenio-iiif | invenio_iiif/handlers.py | image_opener | def image_opener(key):
"""Handler to locate file based on key.
:param key: A key encoded in the format "<bucket>:<version>:<object_key>".
:returns: A file-like object.
"""
if hasattr(g, 'obj'):
obj = g.obj
else:
obj = protect_api(key)
fp = obj.file.storage().open('rb')
... | python | def image_opener(key):
"""Handler to locate file based on key.
:param key: A key encoded in the format "<bucket>:<version>:<object_key>".
:returns: A file-like object.
"""
if hasattr(g, 'obj'):
obj = g.obj
else:
obj = protect_api(key)
fp = obj.file.storage().open('rb')
... | [
"def",
"image_opener",
"(",
"key",
")",
":",
"if",
"hasattr",
"(",
"g",
",",
"'obj'",
")",
":",
"obj",
"=",
"g",
".",
"obj",
"else",
":",
"obj",
"=",
"protect_api",
"(",
"key",
")",
"fp",
"=",
"obj",
".",
"file",
".",
"storage",
"(",
")",
".",
... | Handler to locate file based on key.
:param key: A key encoded in the format "<bucket>:<version>:<object_key>".
:returns: A file-like object. | [
"Handler",
"to",
"locate",
"file",
"based",
"on",
"key",
"."
] | train | https://github.com/inveniosoftware/invenio-iiif/blob/e4f2f93eaabdc8e2efea81c239ab76d481191959/invenio_iiif/handlers.py#L40-L61 |
xapple/plumbing | plumbing/databases/access_database.py | AccessDatabase.tables | def tables(self):
"""The complete list of tables."""
# If we are on unix use mdbtools instead #
if os.name == "posix":
mdb_tables = sh.Command("mdb-tables")
tables_list = mdb_tables('-1', self.path).split('\n')
condition = lambda t: t and not t.startswith('... | python | def tables(self):
"""The complete list of tables."""
# If we are on unix use mdbtools instead #
if os.name == "posix":
mdb_tables = sh.Command("mdb-tables")
tables_list = mdb_tables('-1', self.path).split('\n')
condition = lambda t: t and not t.startswith('... | [
"def",
"tables",
"(",
"self",
")",
":",
"# If we are on unix use mdbtools instead #",
"if",
"os",
".",
"name",
"==",
"\"posix\"",
":",
"mdb_tables",
"=",
"sh",
".",
"Command",
"(",
"\"mdb-tables\"",
")",
"tables_list",
"=",
"mdb_tables",
"(",
"'-1'",
",",
"sel... | The complete list of tables. | [
"The",
"complete",
"list",
"of",
"tables",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L84-L93 |
xapple/plumbing | plumbing/databases/access_database.py | AccessDatabase.table_as_df | def table_as_df(self, table_name):
"""Return a table as a dataframe."""
self.table_must_exist(table_name)
query = "SELECT * FROM `%s`" % table_name.lower()
return pandas.read_sql(query, self.own_conn) | python | def table_as_df(self, table_name):
"""Return a table as a dataframe."""
self.table_must_exist(table_name)
query = "SELECT * FROM `%s`" % table_name.lower()
return pandas.read_sql(query, self.own_conn) | [
"def",
"table_as_df",
"(",
"self",
",",
"table_name",
")",
":",
"self",
".",
"table_must_exist",
"(",
"table_name",
")",
"query",
"=",
"\"SELECT * FROM `%s`\"",
"%",
"table_name",
".",
"lower",
"(",
")",
"return",
"pandas",
".",
"read_sql",
"(",
"query",
","... | Return a table as a dataframe. | [
"Return",
"a",
"table",
"as",
"a",
"dataframe",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L134-L138 |
xapple/plumbing | plumbing/databases/access_database.py | AccessDatabase.insert_df | def insert_df(self, table_name, df):
"""Create a table and populate it with data from a dataframe."""
df.to_sql(table_name, con=self.own_conn) | python | def insert_df(self, table_name, df):
"""Create a table and populate it with data from a dataframe."""
df.to_sql(table_name, con=self.own_conn) | [
"def",
"insert_df",
"(",
"self",
",",
"table_name",
",",
"df",
")",
":",
"df",
".",
"to_sql",
"(",
"table_name",
",",
"con",
"=",
"self",
".",
"own_conn",
")"
] | Create a table and populate it with data from a dataframe. | [
"Create",
"a",
"table",
"and",
"populate",
"it",
"with",
"data",
"from",
"a",
"dataframe",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L140-L142 |
xapple/plumbing | plumbing/databases/access_database.py | AccessDatabase.count_rows | def count_rows(self, table_name):
"""Return the number of entries in a table by counting them."""
self.table_must_exist(table_name)
query = "SELECT COUNT (*) FROM `%s`" % table_name.lower()
self.own_cursor.execute(query)
return int(self.own_cursor.fetchone()[0]) | python | def count_rows(self, table_name):
"""Return the number of entries in a table by counting them."""
self.table_must_exist(table_name)
query = "SELECT COUNT (*) FROM `%s`" % table_name.lower()
self.own_cursor.execute(query)
return int(self.own_cursor.fetchone()[0]) | [
"def",
"count_rows",
"(",
"self",
",",
"table_name",
")",
":",
"self",
".",
"table_must_exist",
"(",
"table_name",
")",
"query",
"=",
"\"SELECT COUNT (*) FROM `%s`\"",
"%",
"table_name",
".",
"lower",
"(",
")",
"self",
".",
"own_cursor",
".",
"execute",
"(",
... | Return the number of entries in a table by counting them. | [
"Return",
"the",
"number",
"of",
"entries",
"in",
"a",
"table",
"by",
"counting",
"them",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L144-L149 |
xapple/plumbing | plumbing/databases/access_database.py | AccessDatabase.tables_with_counts | def tables_with_counts(self):
"""Return the number of entries in all table."""
table_to_count = lambda t: self.count_rows(t)
return zip(self.tables, map(table_to_count, self.tables)) | python | def tables_with_counts(self):
"""Return the number of entries in all table."""
table_to_count = lambda t: self.count_rows(t)
return zip(self.tables, map(table_to_count, self.tables)) | [
"def",
"tables_with_counts",
"(",
"self",
")",
":",
"table_to_count",
"=",
"lambda",
"t",
":",
"self",
".",
"count_rows",
"(",
"t",
")",
"return",
"zip",
"(",
"self",
".",
"tables",
",",
"map",
"(",
"table_to_count",
",",
"self",
".",
"tables",
")",
")... | Return the number of entries in all table. | [
"Return",
"the",
"number",
"of",
"entries",
"in",
"all",
"table",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L155-L158 |
xapple/plumbing | plumbing/databases/access_database.py | AccessDatabase.convert_to_sqlite | def convert_to_sqlite(self, destination=None, method="shell", progress=False):
"""Who wants to use Access when you can deal with SQLite databases instead?"""
# Display progress bar #
if progress: progress = tqdm.tqdm
else: progress = lambda x:x
# Default path #
if ... | python | def convert_to_sqlite(self, destination=None, method="shell", progress=False):
"""Who wants to use Access when you can deal with SQLite databases instead?"""
# Display progress bar #
if progress: progress = tqdm.tqdm
else: progress = lambda x:x
# Default path #
if ... | [
"def",
"convert_to_sqlite",
"(",
"self",
",",
"destination",
"=",
"None",
",",
"method",
"=",
"\"shell\"",
",",
"progress",
"=",
"False",
")",
":",
"# Display progress bar #",
"if",
"progress",
":",
"progress",
"=",
"tqdm",
".",
"tqdm",
"else",
":",
"progres... | Who wants to use Access when you can deal with SQLite databases instead? | [
"Who",
"wants",
"to",
"use",
"Access",
"when",
"you",
"can",
"deal",
"with",
"SQLite",
"databases",
"instead?"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L167-L181 |
xapple/plumbing | plumbing/databases/access_database.py | AccessDatabase.sqlite_by_shell | def sqlite_by_shell(self, destination):
"""Method with shell and a temp file. This is hopefully fast."""
script_path = new_temp_path()
self.sqlite_dump_shell(script_path)
shell_output('sqlite3 -bail -init "%s" "%s" .quit' % (script, destination))
script.remove() | python | def sqlite_by_shell(self, destination):
"""Method with shell and a temp file. This is hopefully fast."""
script_path = new_temp_path()
self.sqlite_dump_shell(script_path)
shell_output('sqlite3 -bail -init "%s" "%s" .quit' % (script, destination))
script.remove() | [
"def",
"sqlite_by_shell",
"(",
"self",
",",
"destination",
")",
":",
"script_path",
"=",
"new_temp_path",
"(",
")",
"self",
".",
"sqlite_dump_shell",
"(",
"script_path",
")",
"shell_output",
"(",
"'sqlite3 -bail -init \"%s\" \"%s\" .quit'",
"%",
"(",
"script",
",",
... | Method with shell and a temp file. This is hopefully fast. | [
"Method",
"with",
"shell",
"and",
"a",
"temp",
"file",
".",
"This",
"is",
"hopefully",
"fast",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L183-L188 |
xapple/plumbing | plumbing/databases/access_database.py | AccessDatabase.sqlite_by_object | def sqlite_by_object(self, destination, progress):
"""This is probably not very fast."""
db = SQLiteDatabase(destination)
db.create()
for script in self.sqlite_dump_string(progress): db.cursor.executescript(script)
db.close() | python | def sqlite_by_object(self, destination, progress):
"""This is probably not very fast."""
db = SQLiteDatabase(destination)
db.create()
for script in self.sqlite_dump_string(progress): db.cursor.executescript(script)
db.close() | [
"def",
"sqlite_by_object",
"(",
"self",
",",
"destination",
",",
"progress",
")",
":",
"db",
"=",
"SQLiteDatabase",
"(",
"destination",
")",
"db",
".",
"create",
"(",
")",
"for",
"script",
"in",
"self",
".",
"sqlite_dump_string",
"(",
"progress",
")",
":",... | This is probably not very fast. | [
"This",
"is",
"probably",
"not",
"very",
"fast",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L190-L195 |
xapple/plumbing | plumbing/databases/access_database.py | AccessDatabase.sqlite_by_df | def sqlite_by_df(self, destination, progress):
"""Is this fast?"""
db = SQLiteDatabase(destination)
db.create()
for table in progress(self.real_tables): self[table].to_sql(table, con=db.connection)
db.close() | python | def sqlite_by_df(self, destination, progress):
"""Is this fast?"""
db = SQLiteDatabase(destination)
db.create()
for table in progress(self.real_tables): self[table].to_sql(table, con=db.connection)
db.close() | [
"def",
"sqlite_by_df",
"(",
"self",
",",
"destination",
",",
"progress",
")",
":",
"db",
"=",
"SQLiteDatabase",
"(",
"destination",
")",
"db",
".",
"create",
"(",
")",
"for",
"table",
"in",
"progress",
"(",
"self",
".",
"real_tables",
")",
":",
"self",
... | Is this fast? | [
"Is",
"this",
"fast?"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L197-L202 |
xapple/plumbing | plumbing/databases/access_database.py | AccessDatabase.sqlite_dump_shell | def sqlite_dump_shell(self, script_path):
"""Generate a text dump compatible with SQLite by using
shell commands. Place this script at *script_path*."""
# First the schema #
shell_output('mdb-schema "%s" sqlite >> "%s"' % (self.path, script_path))
# Start a transaction, speeds th... | python | def sqlite_dump_shell(self, script_path):
"""Generate a text dump compatible with SQLite by using
shell commands. Place this script at *script_path*."""
# First the schema #
shell_output('mdb-schema "%s" sqlite >> "%s"' % (self.path, script_path))
# Start a transaction, speeds th... | [
"def",
"sqlite_dump_shell",
"(",
"self",
",",
"script_path",
")",
":",
"# First the schema #",
"shell_output",
"(",
"'mdb-schema \"%s\" sqlite >> \"%s\"'",
"%",
"(",
"self",
".",
"path",
",",
"script_path",
")",
")",
"# Start a transaction, speeds things up when importing #... | Generate a text dump compatible with SQLite by using
shell commands. Place this script at *script_path*. | [
"Generate",
"a",
"text",
"dump",
"compatible",
"with",
"SQLite",
"by",
"using",
"shell",
"commands",
".",
"Place",
"this",
"script",
"at",
"*",
"script_path",
"*",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L204-L216 |
xapple/plumbing | plumbing/databases/access_database.py | AccessDatabase.sqlite_dump_string | def sqlite_dump_string(self, progress):
"""Generate a text dump compatible with SQLite.
By yielding every table one by one as a byte string."""
# First the schema #
mdb_schema = sh.Command("mdb-schema")
yield mdb_schema(self.path, "sqlite").encode('utf8')
# Start a transa... | python | def sqlite_dump_string(self, progress):
"""Generate a text dump compatible with SQLite.
By yielding every table one by one as a byte string."""
# First the schema #
mdb_schema = sh.Command("mdb-schema")
yield mdb_schema(self.path, "sqlite").encode('utf8')
# Start a transa... | [
"def",
"sqlite_dump_string",
"(",
"self",
",",
"progress",
")",
":",
"# First the schema #",
"mdb_schema",
"=",
"sh",
".",
"Command",
"(",
"\"mdb-schema\"",
")",
"yield",
"mdb_schema",
"(",
"self",
".",
"path",
",",
"\"sqlite\"",
")",
".",
"encode",
"(",
"'u... | Generate a text dump compatible with SQLite.
By yielding every table one by one as a byte string. | [
"Generate",
"a",
"text",
"dump",
"compatible",
"with",
"SQLite",
".",
"By",
"yielding",
"every",
"table",
"one",
"by",
"one",
"as",
"a",
"byte",
"string",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L218-L231 |
xapple/plumbing | plumbing/databases/access_database.py | AccessDatabase.import_table | def import_table(self, source, table_name):
"""Copy a table from another Access database to this one.
Requires that you have mdbtools command line executables installed
in a Windows Subsystem for Linux environment."""
# Run commands #
wsl = sh.Command("wsl.exe")
table_sch... | python | def import_table(self, source, table_name):
"""Copy a table from another Access database to this one.
Requires that you have mdbtools command line executables installed
in a Windows Subsystem for Linux environment."""
# Run commands #
wsl = sh.Command("wsl.exe")
table_sch... | [
"def",
"import_table",
"(",
"self",
",",
"source",
",",
"table_name",
")",
":",
"# Run commands #",
"wsl",
"=",
"sh",
".",
"Command",
"(",
"\"wsl.exe\"",
")",
"table_schema",
"=",
"wsl",
"(",
"\"-e\"",
",",
"\"mdb-schema\"",
",",
"\"-T\"",
",",
"table_name",... | Copy a table from another Access database to this one.
Requires that you have mdbtools command line executables installed
in a Windows Subsystem for Linux environment. | [
"Copy",
"a",
"table",
"from",
"another",
"Access",
"database",
"to",
"this",
"one",
".",
"Requires",
"that",
"you",
"have",
"mdbtools",
"command",
"line",
"executables",
"installed",
"in",
"a",
"Windows",
"Subsystem",
"for",
"Linux",
"environment",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L234-L246 |
xapple/plumbing | plumbing/databases/access_database.py | AccessDatabase.create | def create(cls, destination):
"""Create a new empty MDB at destination."""
mdb_gz_b64 = """\
H4sICIenn1gC/25ldzIwMDMubWRiAO2de2wcRx3Hf7O7Pt/d3u6eLyEtVaOaqg+EkjQvuVVDwa9a
jWXHdZxQQlCJ7fOrfp3OTpqkhVxTItFWIhVQVFBRVNIKRaColVpAUKGKRwwFqUAhKiBIpUaoVWP+
qKgIIHL8Znb39u72znWJiWP3+9l473fzm... | python | def create(cls, destination):
"""Create a new empty MDB at destination."""
mdb_gz_b64 = """\
H4sICIenn1gC/25ldzIwMDMubWRiAO2de2wcRx3Hf7O7Pt/d3u6eLyEtVaOaqg+EkjQvuVVDwa9a
jWXHdZxQQlCJ7fOrfp3OTpqkhVxTItFWIhVQVFBRVNIKRaColVpAUKGKRwwFqUAhKiBIpUaoVWP+
qKgIIHL8Znb39u72znWJiWP3+9l473fzm... | [
"def",
"create",
"(",
"cls",
",",
"destination",
")",
":",
"mdb_gz_b64",
"=",
"\"\"\"\\\n H4sICIenn1gC/25ldzIwMDMubWRiAO2de2wcRx3Hf7O7Pt/d3u6eLyEtVaOaqg+EkjQvuVVDwa9a\n jWXHdZxQQlCJ7fOrfp3OTpqkhVxTItFWIhVQVFBRVNIKRaColVpAUKGKRwwFqUAhKiBIpUaoVWP+\n qKgIIHL8Znb39u72znWJiWP3+9l... | Create a new empty MDB at destination. | [
"Create",
"a",
"new",
"empty",
"MDB",
"at",
"destination",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L250-L299 |
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.tables | def tables(self):
"""The complete list of SQL tables."""
self.own_connection.row_factory = sqlite3.Row
self.own_cursor.execute('SELECT name from sqlite_master where type="table";')
result = [x[0].encode('ascii') for x in self.own_cursor.fetchall()]
self.own_connection.row_factory... | python | def tables(self):
"""The complete list of SQL tables."""
self.own_connection.row_factory = sqlite3.Row
self.own_cursor.execute('SELECT name from sqlite_master where type="table";')
result = [x[0].encode('ascii') for x in self.own_cursor.fetchall()]
self.own_connection.row_factory... | [
"def",
"tables",
"(",
"self",
")",
":",
"self",
".",
"own_connection",
".",
"row_factory",
"=",
"sqlite3",
".",
"Row",
"self",
".",
"own_cursor",
".",
"execute",
"(",
"'SELECT name from sqlite_master where type=\"table\";'",
")",
"result",
"=",
"[",
"x",
"[",
... | The complete list of SQL tables. | [
"The",
"complete",
"list",
"of",
"SQL",
"tables",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L100-L106 |
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.new_connection | def new_connection(self):
"""Make a new connection."""
if not self.prepared: self.prepare()
con = sqlite3.connect(self.path, isolation_level=self.isolation)
con.row_factory = self.factory
if self.text_fact: con.text_factory = self.text_fact
return con | python | def new_connection(self):
"""Make a new connection."""
if not self.prepared: self.prepare()
con = sqlite3.connect(self.path, isolation_level=self.isolation)
con.row_factory = self.factory
if self.text_fact: con.text_factory = self.text_fact
return con | [
"def",
"new_connection",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"prepared",
":",
"self",
".",
"prepare",
"(",
")",
"con",
"=",
"sqlite3",
".",
"connect",
"(",
"self",
".",
"path",
",",
"isolation_level",
"=",
"self",
".",
"isolation",
")",
... | Make a new connection. | [
"Make",
"a",
"new",
"connection",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L134-L140 |
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.prepare | def prepare(self):
"""Check that the file exists, optionally downloads it.
Checks that the file is indeed an SQLite3 database.
Optionally check the MD5."""
if not os.path.exists(self.path):
if self.retrieve:
print("Downloading SQLite3 database...")
... | python | def prepare(self):
"""Check that the file exists, optionally downloads it.
Checks that the file is indeed an SQLite3 database.
Optionally check the MD5."""
if not os.path.exists(self.path):
if self.retrieve:
print("Downloading SQLite3 database...")
... | [
"def",
"prepare",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"path",
")",
":",
"if",
"self",
".",
"retrieve",
":",
"print",
"(",
"\"Downloading SQLite3 database...\"",
")",
"download_from_url",
"(",
"self",
".... | Check that the file exists, optionally downloads it.
Checks that the file is indeed an SQLite3 database.
Optionally check the MD5. | [
"Check",
"that",
"the",
"file",
"exists",
"optionally",
"downloads",
"it",
".",
"Checks",
"that",
"the",
"file",
"is",
"indeed",
"an",
"SQLite3",
"database",
".",
"Optionally",
"check",
"the",
"MD5",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L142-L153 |
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.create | def create(self, columns=None, type_map=None, overwrite=False):
"""Create a new database with a certain schema."""
# Check already exists #
if self.count_bytes > 0:
if overwrite: self.remove()
else: raise Exception("File exists already at '%s'" % self)
# If we wan... | python | def create(self, columns=None, type_map=None, overwrite=False):
"""Create a new database with a certain schema."""
# Check already exists #
if self.count_bytes > 0:
if overwrite: self.remove()
else: raise Exception("File exists already at '%s'" % self)
# If we wan... | [
"def",
"create",
"(",
"self",
",",
"columns",
"=",
"None",
",",
"type_map",
"=",
"None",
",",
"overwrite",
"=",
"False",
")",
":",
"# Check already exists #",
"if",
"self",
".",
"count_bytes",
">",
"0",
":",
"if",
"overwrite",
":",
"self",
".",
"remove",... | Create a new database with a certain schema. | [
"Create",
"a",
"new",
"database",
"with",
"a",
"certain",
"schema",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L161-L172 |
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.add_table | def add_table(self, name, columns, type_map=None, if_not_exists=False):
"""Add add a new table to the database. For instance you could do this:
self.add_table('data', {'id':'integer', 'source':'text', 'pubmed':'integer'})"""
# Check types mapping #
if type_map is None and isinstance(col... | python | def add_table(self, name, columns, type_map=None, if_not_exists=False):
"""Add add a new table to the database. For instance you could do this:
self.add_table('data', {'id':'integer', 'source':'text', 'pubmed':'integer'})"""
# Check types mapping #
if type_map is None and isinstance(col... | [
"def",
"add_table",
"(",
"self",
",",
"name",
",",
"columns",
",",
"type_map",
"=",
"None",
",",
"if_not_exists",
"=",
"False",
")",
":",
"# Check types mapping #",
"if",
"type_map",
"is",
"None",
"and",
"isinstance",
"(",
"columns",
",",
"dict",
")",
":",... | Add add a new table to the database. For instance you could do this:
self.add_table('data', {'id':'integer', 'source':'text', 'pubmed':'integer'}) | [
"Add",
"add",
"a",
"new",
"table",
"to",
"the",
"database",
".",
"For",
"instance",
"you",
"could",
"do",
"this",
":",
"self",
".",
"add_table",
"(",
"data",
"{",
"id",
":",
"integer",
"source",
":",
"text",
"pubmed",
":",
"integer",
"}",
")"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L174-L185 |
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.get_columns_of_table | def get_columns_of_table(self, table=None):
"""Return the list of columns for a particular table
by querying the SQL for the complete list of column names."""
# Check the table exists #
if table is None: table = self.main_table
if not table in self.tables: return []
# A P... | python | def get_columns_of_table(self, table=None):
"""Return the list of columns for a particular table
by querying the SQL for the complete list of column names."""
# Check the table exists #
if table is None: table = self.main_table
if not table in self.tables: return []
# A P... | [
"def",
"get_columns_of_table",
"(",
"self",
",",
"table",
"=",
"None",
")",
":",
"# Check the table exists #",
"if",
"table",
"is",
"None",
":",
"table",
"=",
"self",
".",
"main_table",
"if",
"not",
"table",
"in",
"self",
".",
"tables",
":",
"return",
"[",... | Return the list of columns for a particular table
by querying the SQL for the complete list of column names. | [
"Return",
"the",
"list",
"of",
"columns",
"for",
"a",
"particular",
"table",
"by",
"querying",
"the",
"SQL",
"for",
"the",
"complete",
"list",
"of",
"column",
"names",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L191-L201 |
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.add | def add(self, entries, table=None, columns=None, ignore=False):
"""Add entries to a table.
The *entries* variable should be an iterable."""
# Default table and columns #
if table is None: table = self.main_table
if columns is None: columns = self.get_columns_of_table(table)
... | python | def add(self, entries, table=None, columns=None, ignore=False):
"""Add entries to a table.
The *entries* variable should be an iterable."""
# Default table and columns #
if table is None: table = self.main_table
if columns is None: columns = self.get_columns_of_table(table)
... | [
"def",
"add",
"(",
"self",
",",
"entries",
",",
"table",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"ignore",
"=",
"False",
")",
":",
"# Default table and columns #",
"if",
"table",
"is",
"None",
":",
"table",
"=",
"self",
".",
"main_table",
"if",
... | Add entries to a table.
The *entries* variable should be an iterable. | [
"Add",
"entries",
"to",
"a",
"table",
".",
"The",
"*",
"entries",
"*",
"variable",
"should",
"be",
"an",
"iterable",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L203-L228 |
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.add_by_steps | def add_by_steps(self, entries_by_step, table=None, columns=None):
"""Add entries to the main table.
The *entries* variable should be an iterable yielding iterables."""
for entries in entries_by_step: self.add(entries, table=table, columns=columns) | python | def add_by_steps(self, entries_by_step, table=None, columns=None):
"""Add entries to the main table.
The *entries* variable should be an iterable yielding iterables."""
for entries in entries_by_step: self.add(entries, table=table, columns=columns) | [
"def",
"add_by_steps",
"(",
"self",
",",
"entries_by_step",
",",
"table",
"=",
"None",
",",
"columns",
"=",
"None",
")",
":",
"for",
"entries",
"in",
"entries_by_step",
":",
"self",
".",
"add",
"(",
"entries",
",",
"table",
"=",
"table",
",",
"columns",
... | Add entries to the main table.
The *entries* variable should be an iterable yielding iterables. | [
"Add",
"entries",
"to",
"the",
"main",
"table",
".",
"The",
"*",
"entries",
"*",
"variable",
"should",
"be",
"an",
"iterable",
"yielding",
"iterables",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L255-L258 |
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.count_entries | def count_entries(self, table=None):
"""How many rows in a table."""
if table is None: table = self.main_table
self.own_cursor.execute('SELECT COUNT(1) FROM "%s";' % table)
return int(self.own_cursor.fetchone()[0]) | python | def count_entries(self, table=None):
"""How many rows in a table."""
if table is None: table = self.main_table
self.own_cursor.execute('SELECT COUNT(1) FROM "%s";' % table)
return int(self.own_cursor.fetchone()[0]) | [
"def",
"count_entries",
"(",
"self",
",",
"table",
"=",
"None",
")",
":",
"if",
"table",
"is",
"None",
":",
"table",
"=",
"self",
".",
"main_table",
"self",
".",
"own_cursor",
".",
"execute",
"(",
"'SELECT COUNT(1) FROM \"%s\";'",
"%",
"table",
")",
"retur... | How many rows in a table. | [
"How",
"many",
"rows",
"in",
"a",
"table",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L260-L264 |
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.get_first | def get_first(self, table=None):
"""Just the first entry."""
if table is None: table = self.main_table
query = 'SELECT * FROM "%s" LIMIT 1;' % table
return self.own_cursor.execute(query).fetchone() | python | def get_first(self, table=None):
"""Just the first entry."""
if table is None: table = self.main_table
query = 'SELECT * FROM "%s" LIMIT 1;' % table
return self.own_cursor.execute(query).fetchone() | [
"def",
"get_first",
"(",
"self",
",",
"table",
"=",
"None",
")",
":",
"if",
"table",
"is",
"None",
":",
"table",
"=",
"self",
".",
"main_table",
"query",
"=",
"'SELECT * FROM \"%s\" LIMIT 1;'",
"%",
"table",
"return",
"self",
".",
"own_cursor",
".",
"execu... | Just the first entry. | [
"Just",
"the",
"first",
"entry",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L277-L281 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.