_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q243000
Gourde._add_routes
train
def _add_routes(self): """Add some nice default routes.""" if self.app.has_static_folder: self.add_url_rule("/favicon.ico", "favicon", self.favicon) self.add_url_rule("/", "__default_redirect_to_status", self.redirect_to_status)
python
{ "resource": "" }
q243001
Gourde.get_argparser
train
def get_argparser(parser=None): """Customize a parser to get the correct options.""" parser = parser or argparse.ArgumentParser() parser.add_argument("--host", default="0.0.0.0", help="Host listen address") parser.add_argument("--port", "-p", default=9050, help="Listen port", type=int) ...
python
{ "resource": "" }
q243002
Gourde.setup_prometheus
train
def setup_prometheus(self, registry=None): """Setup Prometheus.""" kwargs = {} if registry: kwargs["registry"] = registry self.metrics = PrometheusMetrics(self.app, **kwargs) try: version = pkg_resources.require(self.app.name)[0].version except pkg...
python
{ "resource": "" }
q243003
Gourde.add_url_rule
train
def add_url_rule(self, route, endpoint, handler): """Add a new url route. Args: See flask.Flask.add_url_route(). """ self.app.add_url_rule(route, endpoint, handler)
python
{ "resource": "" }
q243004
Gourde.healthy
train
def healthy(self): """Return 200 is healthy, else 500. Override is_healthy() to change the health check. """ try: if self.is_healthy(): return "OK", 200 else: return "FAIL", 500 except Exception as e: self.app...
python
{ "resource": "" }
q243005
Gourde.ready
train
def ready(self): """Return 200 is ready, else 500. Override is_ready() to change the readiness check. """ try: if self.is_ready(): return "OK", 200 else: return "FAIL", 500 except Exception as e: self.app.logg...
python
{ "resource": "" }
q243006
Gourde.threads_bt
train
def threads_bt(self): """Display thread backtraces.""" import threading import traceback threads = {} for thread in threading.enumerate(): frames = sys._current_frames().get(thread.ident) if frames: stack = traceback.format_stack(frames) ...
python
{ "resource": "" }
q243007
Gourde.run_with_werkzeug
train
def run_with_werkzeug(self, **options): """Run with werkzeug simple wsgi container.""" threaded = self.threads is not None and (self.threads > 0) self.app.run( host=self.host, port=self.port, debug=self.debug, threaded=threaded, **optio...
python
{ "resource": "" }
q243008
Gourde.run_with_twisted
train
def run_with_twisted(self, **options): """Run with twisted.""" from twisted.internet import reactor from twisted.python import log import flask_twisted twisted = flask_twisted.Twisted(self.app) if self.threads: reactor.suggestThreadPoolSize(self.threads) ...
python
{ "resource": "" }
q243009
Gourde.run_with_gunicorn
train
def run_with_gunicorn(self, **options): """Run with gunicorn.""" import gunicorn.app.base from gunicorn.six import iteritems import multiprocessing class GourdeApplication(gunicorn.app.base.BaseApplication): def __init__(self, app, options=None): sel...
python
{ "resource": "" }
q243010
initialize_api
train
def initialize_api(flask_app): """Initialize an API.""" if not flask_restplus: return api = flask_restplus.Api(version="1.0", title="My Example API") api.add_resource(HelloWorld, "/hello") blueprint = flask.Blueprint("api", __name__, url_prefix="/api") api.init_app(blueprint) flask...
python
{ "resource": "" }
q243011
initialize_app
train
def initialize_app(flask_app, args): """Initialize the App.""" # Setup gourde with the args. gourde.setup(args) # Register a custom health check. gourde.is_healthy = is_healthy # Add an optional API initialize_api(flask_app)
python
{ "resource": "" }
q243012
quote
train
def quote(text, limit=1000): """ Takes a plain text message as an argument, returns a list of tuples. The first argument of the tuple denotes whether the text should be expanded by default. The second argument is the unmodified corresponding text. Example: [(True, 'expanded text'), (False, '> Some ...
python
{ "resource": "" }
q243013
extract_headers
train
def extract_headers(lines, max_wrap_lines): """ Extracts email headers from the given lines. Returns a dict with the detected headers and the amount of lines that were processed. """ hdrs = {} header_name = None # Track overlong headers that extend over multiple lines extend_lines = 0 ...
python
{ "resource": "" }
q243014
trim_tree_after
train
def trim_tree_after(element, include_element=True): """ Removes the document tree following the given element. If include_element is True, the given element is kept in the tree, otherwise it is removed. """ el = element for parent_el in element.iterancestors(): el.tail = None if ...
python
{ "resource": "" }
q243015
trim_tree_before
train
def trim_tree_before(element, include_element=True, keep_head=True): """ Removes the document tree preceding the given element. If include_element is True, the given element is kept in the tree, otherwise it is removed. """ el = element for parent_el in element.iterancestors(): parent_el...
python
{ "resource": "" }
q243016
Sridentify.get_epsg
train
def get_epsg(self): """ Attempts to determine the EPSG code for a given PRJ file or other similar text-based spatial reference file. First, it looks up the PRJ text in the included epsg.db SQLite database, which was manually sourced and cleaned from an ESRI website, http...
python
{ "resource": "" }
q243017
Sridentify.from_epsg
train
def from_epsg(self, epsg_code): """ Loads self.prj by epsg_code. If prjtext not found returns False. """ self.epsg_code = epsg_code assert isinstance(self.epsg_code, int) cur = self.conn.cursor() cur.execute("SELECT prjtext FROM prj_epsg WHERE epsg_code = ...
python
{ "resource": "" }
q243018
Sridentify.to_prj
train
def to_prj(self, filename): """ Saves prj WKT to given file. """ with open(filename, "w") as fp: fp.write(self.prj)
python
{ "resource": "" }
q243019
get_current_head_version
train
def get_current_head_version(graph): """ Returns the current head version. """ script_dir = ScriptDirectory("/", version_locations=[graph.metadata.get_path("migrations")]) return script_dir.get_current_head()
python
{ "resource": "" }
q243020
create_temporary_table
train
def create_temporary_table(from_table, name=None, on_commit=None): """ Create a new temporary table from another table. """ from_table = from_table.__table__ if hasattr(from_table, "__table__") else from_table name = name or f"temporary_{from_table.name}" # copy the origin table into the meta...
python
{ "resource": "" }
q243021
get_current_head
train
def get_current_head(graph): """ Get the current database head revision, if any. """ session = new_session(graph) try: result = session.execute("SELECT version_num FROM alembic_version") except ProgrammingError: return None else: return result.scalar() finally: ...
python
{ "resource": "" }
q243022
Store.flushing
train
def flushing(self): """ Flush the current session, handling common errors. """ try: yield self.session.flush() except (FlushError, IntegrityError) as error: error_message = str(error) # There ought to be a cleaner way to capture th...
python
{ "resource": "" }
q243023
Store.create
train
def create(self, instance): """ Create a new model instance. """ with self.flushing(): if instance.id is None: instance.id = self.new_object_id() self.session.add(instance) return instance
python
{ "resource": "" }
q243024
Store.retrieve
train
def retrieve(self, identifier, *criterion): """ Retrieve a model by primary key and zero or more other criteria. :raises `NotFound` if there is no existing model """ return self._retrieve( self.model_class.id == identifier, *criterion )
python
{ "resource": "" }
q243025
Store.count
train
def count(self, *criterion, **kwargs): """ Count the number of models matching some criterion. """ query = self._query(*criterion) query = self._filter(query, **kwargs) return query.count()
python
{ "resource": "" }
q243026
Store.search
train
def search(self, *criterion, **kwargs): """ Return the list of models matching some criterion. :param offset: pagination offset, if any :param limit: pagination limit, if any """ query = self._query(*criterion) query = self._order_by(query, **kwargs) que...
python
{ "resource": "" }
q243027
Store.search_first
train
def search_first(self, *criterion, **kwargs): """ Returns the first match based on criteria or None. """ query = self._query(*criterion) query = self._order_by(query, **kwargs) query = self._filter(query, **kwargs) # NB: pagination must go last query = se...
python
{ "resource": "" }
q243028
Store._filter
train
def _filter(self, query, **kwargs): """ Filter a query with user-supplied arguments. """ query = self._auto_filter(query, **kwargs) return query
python
{ "resource": "" }
q243029
Store._retrieve
train
def _retrieve(self, *criterion): """ Retrieve a model by some criteria. :raises `ModelNotFoundError` if the row cannot be deleted. """ try: return self._query(*criterion).one() except NoResultFound as error: raise ModelNotFoundError( ...
python
{ "resource": "" }
q243030
Store._delete
train
def _delete(self, *criterion): """ Delete a model by some criterion. Avoids race-condition check-then-delete logic by checking the count of affected rows. :raises `ResourceNotFound` if the row cannot be deleted. """ with self.flushing(): count = self._query...
python
{ "resource": "" }
q243031
Store._query
train
def _query(self, *criterion): """ Construct a query for the model. """ return self.session.query( self.model_class ).filter( *criterion )
python
{ "resource": "" }
q243032
maybe_transactional
train
def maybe_transactional(func): """ Variant of `transactional` that will not commit if there's an argument `commit` with a falsey value. Useful for dry-run style operations. """ @wraps(func) def wrapper(*args, **kwargs): commit = kwargs.get("commit", True) with transaction(commi...
python
{ "resource": "" }
q243033
make_alembic_config
train
def make_alembic_config(temporary_dir, migrations_dir): """ Alembic uses the `alembic.ini` file to configure where it looks for everything else. Not only is this file an unnecessary complication around a single-valued configuration, the single-value it chooses to use (the alembic configuration director...
python
{ "resource": "" }
q243034
make_script_directory
train
def make_script_directory(cls, config): """ Alembic uses a "script directory" to encapsulate its `env.py` file, its migrations directory, and its `script.py.mako` revision template. We'd rather not have such a directory at all as the default `env.py` rarely works without manipulation, migrations a...
python
{ "resource": "" }
q243035
run_online_migration
train
def run_online_migration(self): """ Run an online migration using microcosm configuration. This function takes the place of the `env.py` file in the Alembic migration. """ connectable = self.graph.postgres with connectable.connect() as connection: context.configure( connec...
python
{ "resource": "" }
q243036
patch_script_directory
train
def patch_script_directory(graph): """ Monkey patch the `ScriptDirectory` class, working around configuration assumptions. Changes include: - Using a generated, temporary directory (with a generated, temporary `script.py.mako`) instead of the assumed script directory. - Using our `make_...
python
{ "resource": "" }
q243037
get_migrations_dir
train
def get_migrations_dir(graph): """ Resolve the migrations directory path. Either take the directory from a component of the object graph or by using the metaata's path resolution facilities. """ try: migrations_dir = graph.migrations_dir except (LockedGraphError, NotBoundError): ...
python
{ "resource": "" }
q243038
main
train
def main(graph, *args): """ Entry point for invoking Alembic's `CommandLine`. Alembic's CLI defines its own argument parsing and command invocation; we want to use these directly but define configuration our own way. This function takes the behavior of `CommandLine.main()` and reinterprets it with ...
python
{ "resource": "" }
q243039
configure_sessionmaker
train
def configure_sessionmaker(graph): """ Create the SQLAlchemy session class. """ engine_routing_strategy = getattr(graph, graph.config.sessionmaker.engine_routing_strategy) if engine_routing_strategy.supports_multiple_binds: ScopedFactory.infect(graph, "postgres") class RoutingSession(...
python
{ "resource": "" }
q243040
clone
train
def clone(instance, substitutions, ignore=()): """ Clone an instance of `Model` that uses `IdentityMixin`. :param instance: the instance to clonse :param substitutions: a dictionary of substitutions :param ignore: a tuple of column names to ignore """ substitutions[instance.id] = new_objec...
python
{ "resource": "" }
q243041
configure_encryptor
train
def configure_encryptor(graph): """ Create a MultiTenantEncryptor from configured keys. """ encryptor = graph.multi_tenant_key_registry.make_encryptor(graph) # register the encryptor will each encryptable type for encryptable in EncryptableMixin.__subclasses__(): encryptable.register(e...
python
{ "resource": "" }
q243042
toposorted
train
def toposorted(nodes, edges): """ Perform a topological sort on the input resources. The topological sort uses Kahn's algorithm, which is a stable sort and will preserve this ordering; note that a DFS will produce a worst case ordering from the perspective of batching. """ incoming = defaultdi...
python
{ "resource": "" }
q243043
should_copy
train
def should_copy(column): """ Determine if a column should be copied. """ if not isinstance(column.type, Serial): return True if column.nullable: return True if not column.server_default: return True # do not create temporary serial values; they will be defaulted o...
python
{ "resource": "" }
q243044
SingleTenantEncryptor.encrypt
train
def encrypt(self, encryption_context_key: str, plaintext: str) -> Tuple[bytes, Sequence[str]]: """ Encrypt a plaintext string value. The return value will include *both* the resulting binary ciphertext and the master key ids used for encryption. In the li...
python
{ "resource": "" }
q243045
on_init
train
def on_init(target: "EncryptableMixin", args, kwargs): """ Intercept SQLAlchemy's instance init event. SQLALchemy allows callback to intercept ORM instance init functions. The calling arguments will be an empty instance of the `target` model, plus the arguments passed to `__init__`. The `kwargs` d...
python
{ "resource": "" }
q243046
on_load
train
def on_load(target: "EncryptableMixin", context): """ Intercept SQLAlchemy's instance load event. """ decrypt, plaintext = decrypt_instance(target) if decrypt: target.plaintext = plaintext
python
{ "resource": "" }
q243047
EncryptableMixin.register
train
def register(cls, encryptor: Encryptor): """ Register this encryptable with an encryptor. Instances of this encryptor will be encrypted on initialization and decrypted on load. """ # save the current encryptor statically cls.__encryptor__ = encryptor # NB: we c...
python
{ "resource": "" }
q243048
DAG.nodes_map
train
def nodes_map(self): """ Build a mapping from node type to a list of nodes. A typed mapping helps avoid polymorphism at non-persistent layers. """ dct = dict() for node in self.nodes.values(): cls = next(base for base in getmro(node.__class__) if "__tablenam...
python
{ "resource": "" }
q243049
DAG.build_edges
train
def build_edges(self): """ Build edges based on node `edges` property. Filters out any `Edge` not defined in the DAG. """ self.edges = [ edge if isinstance(edge, Edge) else Edge(*edge) for node in self.nodes.values() for edge in getattr(node,...
python
{ "resource": "" }
q243050
DAG.clone
train
def clone(self, ignore=()): """ Clone this dag using a set of substitutions. Traverse the dag in topological order. """ nodes = [ clone(node, self.substitutions, ignore) for node in toposorted(self.nodes, self.edges) ] return DAG(nodes=no...
python
{ "resource": "" }
q243051
DAGCloner.explain
train
def explain(self, **kwargs): """ Generate a "dry run" DAG of that state that WILL be cloned. """ root = self.retrieve_root(**kwargs) children = self.iter_children(root, **kwargs) dag = DAG.from_nodes(root, *children) return self.add_edges(dag)
python
{ "resource": "" }
q243052
DAGCloner.clone
train
def clone(self, substitutions, **kwargs): """ Clone a DAG. """ dag = self.explain(**kwargs) dag.substitutions.update(substitutions) cloned_dag = dag.clone(ignore=self.ignore) return self.update_nodes(self.add_edges(cloned_dag))
python
{ "resource": "" }
q243053
choose_database_name
train
def choose_database_name(metadata, config): """ Choose the database name to use. As a default, databases should be named after the service that uses them. In addition, database names should be different between unit testing and runtime so that there is no chance of a unit test dropping a real datab...
python
{ "resource": "" }
q243054
choose_username
train
def choose_username(metadata, config): """ Choose the database username to use. Because databases should not be shared between services, database usernames should be the same as the service that uses them. """ if config.username is not None: # we allow -- but do not encourage -- databa...
python
{ "resource": "" }
q243055
choose_uri
train
def choose_uri(metadata, config): """ Choose the database URI to use. """ database_name = choose_database_name(metadata, config) driver = config.driver host, port = config.host, config.port username, password = choose_username(metadata, config), config.password return f"{driver}://{use...
python
{ "resource": "" }
q243056
choose_connect_args
train
def choose_connect_args(metadata, config): """ Choose the SSL mode and optional root cert for the connection. """ if not config.require_ssl and not config.verify_ssl: return dict( sslmode="prefer", ) if config.require_ssl and not config.verify_ssl: return dict( ...
python
{ "resource": "" }
q243057
choose_args
train
def choose_args(metadata, config): """ Choose database connection arguments. """ return dict( connect_args=choose_connect_args(metadata, config), echo=config.echo, max_overflow=config.max_overflow, pool_size=config.pool_size, pool_timeout=config.pool_timeout, ...
python
{ "resource": "" }
q243058
IdentityMixin._members
train
def _members(self): """ Return a dict of non-private members. """ return { key: value for key, value in self.__dict__.items() # NB: ignore internal SQLAlchemy state and nested relationships if not key.startswith("_") and not isinstance(val...
python
{ "resource": "" }
q243059
insert_many
train
def insert_many(self, items): """ Insert many items at once into a temporary table. """ return SessionContext.session.execute( self.insert(values=[ to_dict(item, self.c) for item in items ]), ).rowcount
python
{ "resource": "" }
q243060
upsert_into
train
def upsert_into(self, table): """ Upsert from a temporarty table into another table. """ return SessionContext.session.execute( insert(table).from_select( self.c, self, ).on_conflict_do_nothing(), ).rowcount
python
{ "resource": "" }
q243061
configure_key_provider
train
def configure_key_provider(graph, key_ids): """ Configure a key provider. During unit tests, use a static key provider (e.g. without AWS calls). """ if graph.metadata.testing: # use static provider provider = StaticMasterKeyProvider() provider.add_master_keys_from_list(key_...
python
{ "resource": "" }
q243062
configure_materials_manager
train
def configure_materials_manager(graph, key_provider): """ Configure a crypto materials manager """ if graph.config.materials_manager.enable_cache: return CachingCryptoMaterialsManager( cache=LocalCryptoMaterialsCache(graph.config.materials_manager.cache_capacity), master...
python
{ "resource": "" }
q243063
main
train
def main(graph): """ Create and drop databases. """ args = parse_args(graph) if args.drop: drop_all(graph) create_all(graph)
python
{ "resource": "" }
q243064
get_lattice_type
train
def get_lattice_type(cryst): '''Find the symmetry of the crystal using spglib symmetry finder. Derive name of the space group and its number extracted from the result. Based on the group number identify also the lattice type and the Bravais lattice of the crystal. The lattice type numbers are (the ...
python
{ "resource": "" }
q243065
get_bulk_modulus
train
def get_bulk_modulus(cryst): '''Calculate bulk modulus using the Birch-Murnaghan equation of state. The EOS must be previously calculated by get_BM_EOS routine. The returned bulk modulus is a :math:`B_0` coefficient of the B-M EOS. The units of the result are defined by ASE. To get the result in an...
python
{ "resource": "" }
q243066
get_BM_EOS
train
def get_BM_EOS(cryst, systems): """Calculate Birch-Murnaghan Equation of State for the crystal. The B-M equation of state is defined by: .. math:: P(V)= \\frac{B_0}{B'_0}\\left[ \\left({\\frac{V}{V_0}}\\right)^{-B'_0} - 1 \\right] It's coefficients are estimated using n single-po...
python
{ "resource": "" }
q243067
get_elementary_deformations
train
def get_elementary_deformations(cryst, n=5, d=2): '''Generate elementary deformations for elastic tensor calculation. The deformations are created based on the symmetry of the crystal and are limited to the non-equivalet axes of the crystal. :param cryst: Atoms object, basic structure :param n: in...
python
{ "resource": "" }
q243068
get_cart_deformed_cell
train
def get_cart_deformed_cell(base_cryst, axis=0, size=1): '''Return the cell deformed along one of the cartesian directions Creates new deformed structure. The deformation is based on the base structure and is performed along single axis. The axis is specified as follows: 0,1,2 = x,y,z ; sheers: 3,4,5 = ...
python
{ "resource": "" }
q243069
get_strain
train
def get_strain(cryst, refcell=None): '''Calculate strain tensor in the Voight notation Computes the strain tensor in the Voight notation as a conventional 6-vector. The calculation is done with respect to the crystal geometry passed in refcell parameter. :param cryst: deformed structure :param...
python
{ "resource": "" }
q243070
work_dir
train
def work_dir(path): ''' Context menager for executing commands in some working directory. Returns to the previous wd when finished. Usage: >>> with work_dir(path): ... subprocess.call('git status') ''' starting_directory = os.getcwd() try: os.chdir(path) yield ...
python
{ "resource": "" }
q243071
ClusterVasp.prepare_calc_dir
train
def prepare_calc_dir(self): ''' Prepare the calculation directory for VASP execution. This needs to be re-implemented for each local setup. The following code reflects just my particular setup. ''' with open("vasprun.conf","w") as f: f.write('NODES="nodes=%s:p...
python
{ "resource": "" }
q243072
ClusterVasp.calc_finished
train
def calc_finished(self): ''' Check if the lockfile is in the calculation directory. It is removed by the script at the end regardless of the success of the calculation. This is totally tied to implementation and you need to implement your own scheme! ''' #print_st...
python
{ "resource": "" }
q243073
RemoteCalculator.run_calculation
train
def run_calculation(self, atoms=None, properties=['energy'], system_changes=all_changes): ''' Internal calculation executor. We cannot use FileIOCalculator directly since we need to support remote execution. This calculator is different from others. ...
python
{ "resource": "" }
q243074
gen
train
def gen(ctx, num, lo, hi, size, struct): '''Generate deformed structures''' frmt = ctx.parent.params['frmt'] action = ctx.parent.params['action'] cryst = ase.io.read(struct, format=frmt) fn_tmpl = action if frmt == 'vasp': fn_tmpl += '_%03d.POSCAR' kwargs = {'vasp5': True, 'dire...
python
{ "resource": "" }
q243075
proc
train
def proc(ctx, files): '''Process calculated structures''' def calc_reader(fn, verb): if verb: echo('Reading: {:<60s}\r'.format(fn), nl=False, err=True) return ase.io.read(fn) action = ctx.parent.params['action'] systems = [calc_reader(calc, verbose) for calc in files] i...
python
{ "resource": "" }
q243076
EntryPlaceholderAdmin.save_model
train
def save_model(self, request, entry, form, change): """ Fill the content field with the interpretation of the placeholder """ context = RequestContext(request) try: content = render_placeholder(entry.content_placeholder, context) entry.content = co...
python
{ "resource": "" }
q243077
EntryMenu.get_nodes
train
def get_nodes(self, request): """ Return menu's node for entries """ nodes = [] archives = [] attributes = {'hidden': HIDE_ENTRY_MENU} for entry in Entry.published.all(): year = entry.creation_date.strftime('%Y') month = entry.creation_date...
python
{ "resource": "" }
q243078
CategoryMenu.get_nodes
train
def get_nodes(self, request): """ Return menu's node for categories """ nodes = [] nodes.append(NavigationNode(_('Categories'), reverse('zinnia:category_list'), 'categories')) for category in Category...
python
{ "resource": "" }
q243079
AuthorMenu.get_nodes
train
def get_nodes(self, request): """ Return menu's node for authors """ nodes = [] nodes.append(NavigationNode(_('Authors'), reverse('zinnia:author_list'), 'authors')) for author in Author.published.all(...
python
{ "resource": "" }
q243080
TagMenu.get_nodes
train
def get_nodes(self, request): """ Return menu's node for tags """ nodes = [] nodes.append(NavigationNode(_('Tags'), reverse('zinnia:tag_list'), 'tags')) for tag in tags_published(): nodes.append(NavigationNode(tag.name, ...
python
{ "resource": "" }
q243081
EntryModifier.modify
train
def modify(self, request, nodes, namespace, root_id, post_cut, breadcrumb): """ Modify nodes of a menu """ if breadcrumb: return nodes for node in nodes: if node.attr.get('hidden'): node.visible = False return nodes
python
{ "resource": "" }
q243082
PlaceholderEntry.acquire_context
train
def acquire_context(self): """ Inspect the stack to acquire the current context used, to render the placeholder. I'm really sorry for this, but if you have a better way, you are welcome ! """ frame = None request = None try: for f in inspect.s...
python
{ "resource": "" }
q243083
get_boto_ses_connection
train
def get_boto_ses_connection(): """ Shortcut for instantiating and returning a boto SESConnection object. :rtype: boto.ses.SESConnection :returns: A boto SESConnection object, from which email sending is done. """ access_key_id = getattr( settings, 'CUCUMBER_SES_ACCESS_KEY_ID', ...
python
{ "resource": "" }
q243084
SendEmailTask.run
train
def run(self, from_email, recipients, message): """ This does the dirty work. Connects to Amazon SES via boto and fires off the message. :param str from_email: The email address the message will show as originating from. :param list recipients: A list of email addres...
python
{ "resource": "" }
q243085
Command.handle
train
def handle(self, *args, **options): """ Renders the output by piecing together a few methods that do the dirty work. """ # AWS SES connection, which can be re-used for each query needed. conn = get_boto_ses_connection() self._print_quota(conn) self._print_...
python
{ "resource": "" }
q243086
Command._print_quota
train
def _print_quota(self, conn): """ Prints some basic quota statistics. """ quota = conn.get_send_quota() quota = quota['GetSendQuotaResponse']['GetSendQuotaResult'] print "--- SES Quota ---" print " 24 Hour Quota: %s" % quota['Max24HourSend'] prin...
python
{ "resource": "" }
q243087
TabuSampler.sample
train
def sample(self, bqm, init_solution=None, tenure=None, scale_factor=1, timeout=20, num_reads=1): """Run a tabu search on a given binary quadratic model. Args: bqm (:obj:`~dimod.BinaryQuadraticModel`): The binary quadratic model (BQM) to be sampled. init_solution ...
python
{ "resource": "" }
q243088
GfycatClient.upload_from_url
train
def upload_from_url(self, url): """ Upload a GIF from a URL. """ self.check_token() params = {'fetchUrl': url} r = requests.get(FETCH_URL_ENDPOINT, params=params) if r.status_code != 200: raise GfycatClientError('Error fetching the URL', r.st...
python
{ "resource": "" }
q243089
GfycatClient.upload_from_file
train
def upload_from_file(self, filename): """ Upload a local file to Gfycat """ key = str(uuid.uuid4())[:8] form = [('key', key), ('acl', ACL), ('AWSAccessKeyId', AWS_ACCESS_KEY_ID), ('success_action_status', SUCCESS_ACTION_STATUS), ...
python
{ "resource": "" }
q243090
GfycatClient.uploaded_file_info
train
def uploaded_file_info(self, key): """ Get information about an uploaded GIF. """ r = requests.get(FILE_UPLOAD_STATUS_ENDPOINT + key) if r.status_code != 200: raise GfycatClientError('Unable to check the status', r.status_code) ...
python
{ "resource": "" }
q243091
GfycatClient.query_gfy
train
def query_gfy(self, gfyname): """ Query a gfy name for URLs and more information. """ self.check_token() r = requests.get(QUERY_ENDPOINT + gfyname, headers=self.headers) response = r.json() if r.status_code != 200 and not ERROR_KEY in re...
python
{ "resource": "" }
q243092
GfycatClient.check_link
train
def check_link(self, link): """ Check if a link has been already converted. """ r = requests.get(CHECK_LINK_ENDPOINT + link) if r.status_code != 200: raise GfycatClientError('Unable to check the link', r.status_code) return...
python
{ "resource": "" }
q243093
GfycatClient.get_token
train
def get_token(self): """ Gets the authorization token """ payload = {'grant_type': 'client_credentials', 'client_id': self.client_id, 'client_secret': self.client_secret} r = requests.post(OAUTH_ENDPOINT, data=json.dumps(payload), headers={'content-type': 'application/js...
python
{ "resource": "" }
q243094
BaseMetadata.dict
train
def dict(self): """ dictionary representation of the metadata. :return: dictionary representation of the metadata :rtype: dict """ metadata = {} properties = {} for name, prop in list(self.properties.items()): properties[name] = prop.dict ...
python
{ "resource": "" }
q243095
BaseMetadata.json
train
def json(self): """ json representation of the metadata. :return: json representation of the metadata :rtype: str """ json_dumps = json.dumps( self.dict, indent=2, sort_keys=True, separators=(',', ': '), cls=Met...
python
{ "resource": "" }
q243096
BaseMetadata._read_json_file
train
def _read_json_file(self): """ read metadata from a json file. :return: the parsed json dict :rtype: dict """ with open(self.json_uri) as metadata_file: try: metadata = json.load(metadata_file) return metadata excep...
python
{ "resource": "" }
q243097
BaseMetadata._read_json_db
train
def _read_json_db(self): """ read metadata from a json string stored in a DB. :return: the parsed json dict :rtype: dict """ try: metadata_str = self.db_io.read_metadata_from_uri( self.layer_uri, 'json') except HashNotFoundError: ...
python
{ "resource": "" }
q243098
BaseMetadata._read_xml_file
train
def _read_xml_file(self): """ read metadata from an xml file. :return: the root element of the xml :rtype: ElementTree.Element """ # this raises a IOError if the file doesn't exist root = ElementTree.parse(self.xml_uri) root.getroot() return root
python
{ "resource": "" }
q243099
BaseMetadata._read_xml_db
train
def _read_xml_db(self): """ read metadata from an xml string stored in a DB. :return: the root element of the xml :rtype: ElementTree.Element """ try: metadata_str = self.db_io.read_metadata_from_uri( self.layer_uri, 'xml') root = ...
python
{ "resource": "" }