_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q41600
CryptoYAML.write
train
def write(self): """ Encrypts and writes the current state back onto the filesystem """ with open(self.filepath, 'wb') as outfile: outfile.write( self.fernet.encrypt( yaml.dump(self.data, encoding='utf-8')))
python
{ "resource": "" }
q41601
ConditionSet.has_active_condition
train
def has_active_condition(self, condition, instances): """ Given a list of instances, and the condition active for this switch, returns a boolean representing if the conditional is met, including a non-instance default. """ return_value = None for instance in insta...
python
{ "resource": "" }
q41602
Version.get_pypi_version
train
async def get_pypi_version(self): """Get version published to PyPi.""" self._version_data["beta"] = self.beta self._version_data["source"] = "PyPi" info_version = None last_release = None try: async with async_timeout.timeout(5, loop=self.loop): ...
python
{ "resource": "" }
q41603
Version.get_hassio_version
train
async def get_hassio_version(self): """Get version published for hassio.""" if self.image not in IMAGES: _LOGGER.warning("%s is not a valid image using default", self.image) self.image = "default" board = BOARDS.get(self.image, BOARDS["default"]) self._version_d...
python
{ "resource": "" }
q41604
Version.get_docker_version
train
async def get_docker_version(self): """Get version published for docker.""" if self.image not in IMAGES: _LOGGER.warning("%s is not a valid image using default", self.image) self.image = "default" self._version_data["beta"] = self.beta self._version_data["source"...
python
{ "resource": "" }
q41605
ByUserTag.matches
train
def matches(self, a, b, **config): """ The message must match by username """ submitter_a = a['msg']['override']['submitter']['name'] submitter_b = b['msg']['override']['submitter']['name'] if submitter_a != submitter_b: return False return True
python
{ "resource": "" }
q41606
Client.start_stream_subscriber
train
def start_stream_subscriber(self): """ Starts the stream consumer's main loop. Called when the stream consumer has been set up with the correct callbacks. """ if not self._stream_process_started: # pragma: no cover if sys.platform.startswith("win"): # if we're on windo...
python
{ "resource": "" }
q41607
Client.subscribe
train
def subscribe(self, stream): """ Subscribe to a stream. :param stream: stream to subscribe to :type stream: str :raises: :class:`~datasift.exceptions.StreamSubscriberNotStarted`, :class:`~datasift.exceptions.DeleteRequired`, :class:`~datasift.exceptions.StreamNotConnected` ...
python
{ "resource": "" }
q41608
Client.on_open
train
def on_open(self, func): """ Function to set the callback for the opening of a stream. Can be called manually:: def open_callback(data): setup_stream() client.on_open(open_callback) or as a decorator:: @client.on_ope...
python
{ "resource": "" }
q41609
Client._stream
train
def _stream(self): # pragma: no cover """Runs in a sub-process to perform stream consumption""" self.factory.protocol = LiveStream self.factory.datasift = { 'on_open': self._on_open, 'on_close': self._on_close, 'on_message': self._on_message, 'sen...
python
{ "resource": "" }
q41610
Client.compile
train
def compile(self, csdl): """ Compile the given CSDL. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/compile Raises a DataSiftApiException for any error given by the REST API, including CSDL compilation. :param csdl: CSDL to compile :...
python
{ "resource": "" }
q41611
Client.is_valid
train
def is_valid(self, csdl): """ Checks if the given CSDL is valid. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/validate :param csdl: CSDL to validate :type csdl: str :returns: Boolean indicating the validity of the CSDL :...
python
{ "resource": "" }
q41612
Client.usage
train
def usage(self, period='hour'): """ Check the number of objects processed and delivered for a given time period Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/usage :param period: (optional) time period to measure usage for, can be one of "day", "hour" or "c...
python
{ "resource": "" }
q41613
Client.dpu
train
def dpu(self, hash=None, historics_id=None): """ Calculate the DPU cost of consuming a stream. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/dpu :param hash: target CSDL filter hash :type hash: str :returns: dict with extra response ...
python
{ "resource": "" }
q41614
Client.pull
train
def pull(self, subscription_id, size=None, cursor=None): """ Pulls a series of interactions from the queue for the given subscription ID. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pull :param subscription_id: The ID of the subscription to pull interacti...
python
{ "resource": "" }
q41615
PUBGAPI.player_skill
train
def player_skill(self, player_handle, game_mode='solo'): """Returns the current skill rating of the player for a specified gamemode, default gamemode is solo""" if game_mode not in constants.GAME_MODES: raise APIException("game_mode must be one of: solo, duo, squad, all") ...
python
{ "resource": "" }
q41616
plot
train
def plot(nxG, nyG, iBeg, iEnd, jBeg, jEnd, data, title=''): """ Plot distributed array @param nxG number of global cells in x @param nyG number of global cells in y @param iBeg global starting index in x @param iEnd global ending index in x @param jBeg global starting index in y @param j...
python
{ "resource": "" }
q41617
NdriveTerm.do_ls
train
def do_ls(self, nothing = ''): """list files in current remote directory""" for d in self.dirs: self.stdout.write("\033[0;34m" + ('%s\n' % d) + "\033[0m") for f in self.files: self.stdout.write('%s\n' % f)
python
{ "resource": "" }
q41618
NdriveTerm.do_cd
train
def do_cd(self, path = '/'): """change current working directory""" path = path[0] if path == "..": self.current_path = "/".join(self.current_path[:-1].split("/")[0:-1]) + '/' elif path == '/': self.current_path = "/" else: if path[-1] == '/':...
python
{ "resource": "" }
q41619
NdriveTerm.do_cat
train
def do_cat(self, path): """display the contents of a file""" path = path[0] tmp_file_path = self.TMP_PATH + 'tmp' if not os.path.exists(self.TMP_PATH): os.makedirs(self.TMP_PATH) f = self.n.downloadFile(self.current_path + path, tmp_file_path) f = open(tmp_f...
python
{ "resource": "" }
q41620
NdriveTerm.do_mkdir
train
def do_mkdir(self, path): """create a new directory""" path = path[0] self.n.makeDirectory(self.current_path + path) self.dirs = self.dir_complete()
python
{ "resource": "" }
q41621
NdriveTerm.do_rm
train
def do_rm(self, path): path = path[0] """delete a file or directory""" self.n.delete(self.current_path + path) self.dirs = self.dir_complete() self.files = self.file_complete()
python
{ "resource": "" }
q41622
NdriveTerm.do_account_info
train
def do_account_info(self): """display account information""" s, metadata = self.n.getRegisterUserInfo() pprint.PrettyPrinter(indent=2).pprint(metadata)
python
{ "resource": "" }
q41623
NdriveTerm.do_get
train
def do_get(self, from_path, to_path): """ Copy file from Ndrive to local file and print out out the metadata. Examples: Ndrive> get file.txt ~/ndrive-file.txt """ to_file = open(os.path.expanduser(to_path), "wb") self.n.downloadFile(self.current_path + "/" + f...
python
{ "resource": "" }
q41624
NdriveTerm.do_put
train
def do_put(self, from_path, to_path): """ Copy local file to Ndrive Examples: Ndrive> put ~/test.txt ndrive-copy-test.txt """ from_file = open(os.path.expanduser(from_path), "rb") self.n.put(self.current_path + "/" + from_path, to_path)
python
{ "resource": "" }
q41625
NdriveTerm.do_search
train
def do_search(self, string): """Search Ndrive for filenames containing the given string.""" results = self.n.doSearch(string, full_path = self.current_path) if results: for r in results: self.stdout.write("%s\n" % r['path'])
python
{ "resource": "" }
q41626
tr
train
def tr(string1, string2, source, option=''): """Replace or remove specific characters. If not given option, then replace all characters in string1 with the character in the same position in string2. Following options are available: c Replace all complemented characters in string1 with ...
python
{ "resource": "" }
q41627
DataService.upload
train
def upload(self, filepath, service_path, remove=False): ''' "Upload" a file to a service This copies a file from the local filesystem into the ``DataService``'s filesystem. If ``remove==True``, the file is moved rather than copied. If ``filepath`` and ``service_path`` paths are...
python
{ "resource": "" }
q41628
DataArchive.get_version_path
train
def get_version_path(self, version=None): ''' Returns a storage path for the archive and version If the archive is versioned, the version number is used as the file path and the archive path is the directory. If not, the archive path is used as the file path. Parameters...
python
{ "resource": "" }
q41629
DataArchive.update
train
def update( self, filepath, cache=False, remove=False, bumpversion=None, prerelease=None, dependencies=None, metadata=None, message=None): ''' Enter a new version to a DataArchive Paramet...
python
{ "resource": "" }
q41630
DataArchive._get_default_dependencies
train
def _get_default_dependencies(self): ''' Get default dependencies for archive Get default dependencies from requirements file or (if no requirements file) from previous version ''' # Get default dependencies from requirements file default_dependencies = { ...
python
{ "resource": "" }
q41631
DataArchive.download
train
def download(self, filepath, version=None): ''' Downloads a file from authority to local path 1. First checks in cache to check if file is there and if it is, is it up to date 2. If it is not up to date, it will download the file to cache ''' version = _proce...
python
{ "resource": "" }
q41632
DataArchive.delete
train
def delete(self): ''' Delete the archive .. warning:: Deleting an archive will erase all data and metadata permanently. For help setting user permissions, see :ref:`Administrative Tools <admin>` ''' versions = self.get_versions() sel...
python
{ "resource": "" }
q41633
DataArchive.isfile
train
def isfile(self, version=None, *args, **kwargs): ''' Check whether the path exists and is a file ''' version = _process_version(self, version) path = self.get_version_path(version) self.authority.fs.isfile(path, *args, **kwargs)
python
{ "resource": "" }
q41634
DataArchive.add_tags
train
def add_tags(self, *tags): ''' Set tags for a given archive ''' normed_tags = self.api.manager._normalize_tags(tags) self.api.manager.add_tags(self.archive_name, normed_tags)
python
{ "resource": "" }
q41635
open
train
def open( file, mode="r", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None, ): r"""Open file and return a stream. Raise OSError upon failure. file is either a text or byte string giving the name (and the path ...
python
{ "resource": "" }
q41636
wrap_file
train
def wrap_file(file_like_obj): """Wrap a file like object in an async stream wrapper. Files generated with `open()` may be one of several types. This convenience function retruns the stream wrapped in the most appropriate wrapper for the type. If the stream is already wrapped it is returned unaltere...
python
{ "resource": "" }
q41637
StringIO
train
def StringIO(*args, **kwargs): """StringIO constructor shim for the async wrapper.""" raw = sync_io.StringIO(*args, **kwargs) return AsyncStringIOWrapper(raw)
python
{ "resource": "" }
q41638
BytesIO
train
def BytesIO(*args, **kwargs): """BytesIO constructor shim for the async wrapper.""" raw = sync_io.BytesIO(*args, **kwargs) return AsyncBytesIOWrapper(raw)
python
{ "resource": "" }
q41639
AsyncFileIOWrapper.seek
train
async def seek(self, pos, whence=sync_io.SEEK_SET): """Move to new file position. Argument offset is a byte count. Optional argument whence defaults to SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values are SEEK_CUR or 1 (move relative to current position, p...
python
{ "resource": "" }
q41640
QueryManager._join_gene
train
def _join_gene(query, gene_name, gene_symbol, gene_id): """helper function to add a query join to Gene model :param `sqlalchemy.orm.query.Query` query: SQL Alchemy query :param str gene_name: gene name :param str gene_symbol: gene symbol :param int gene_id: NCBI Gene identifier...
python
{ "resource": "" }
q41641
QueryManager.actions
train
def actions(self): """Gets the list of allowed actions :rtype: list[str] """ r = self.session.query(models.Action).all() return [x.type_name for x in r]
python
{ "resource": "" }
q41642
S3UploadFormView.get_validate_upload_form_kwargs
train
def get_validate_upload_form_kwargs(self): """ Return the keyword arguments for instantiating the form for validating the upload. """ kwargs = { 'storage': self.get_storage(), 'upload_to': self.get_upload_to(), 'content_type_prefix': self.get...
python
{ "resource": "" }
q41643
SoundService.play
train
def play(state): """ Play sound for a given state. :param state: a State value. """ filename = None if state == SoundService.State.welcome: filename = "pad_glow_welcome1.wav" elif state == SoundService.State.goodbye: filename = "pad_glow_power_off...
python
{ "resource": "" }
q41644
get_readme
train
def get_readme(): """Generate long description""" pandoc = None for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') pandoc = os.path.join(path, 'pandoc') if os.path.isfile(pandoc) and os.access(pandoc, os.X_OK): break else: pandoc ...
python
{ "resource": "" }
q41645
_casual_timedelta_string
train
def _casual_timedelta_string(meeting): """ Return a casual timedelta string. If a meeting starts in 2 hours, 15 minutes, and 32 seconds from now, then return just "in 2 hours". If a meeting starts in 7 minutes and 40 seconds from now, return just "in 7 minutes". If a meeting starts 56 seconds...
python
{ "resource": "" }
q41646
repo_name
train
def repo_name(msg): """ Compat util to get the repo name from a message. """ try: # git messages look like this now path = msg['msg']['commit']['path'] project = path.split('.git')[0][9:] except KeyError: # they used to look like this, though project = msg['msg']['com...
python
{ "resource": "" }
q41647
Account.usage
train
def usage(self, period=None, start=None, end=None): """ Get account usage information :param period: Period is one of either hourly, daily or monthly :type period: str :param start: Determines time period of the usage :type start: int :param end: Dete...
python
{ "resource": "" }
q41648
bmrblex
train
def bmrblex(text): """A lexical analyzer for the BMRB NMR-STAR format syntax. :param text: Input text. :type text: :py:class:`str` or :py:class:`bytes` :return: Current token. :rtype: :py:class:`str` """ stream = transform_text(text) wordchars = (u"abcdfeghijklmnopqrstuvwxyz" ...
python
{ "resource": "" }
q41649
check_dependencies
train
def check_dependencies(): """Check external dependecies Return a tuple with the available generators. """ available = [] try: shell('ebook-convert') available.append('calibre') except OSError: pass try: shell('pandoc --help') available.append('pandoc')...
python
{ "resource": "" }
q41650
MongoLock.lock
train
def lock(self, key, owner, timeout=None, expire=None): """Lock given `key` to `owner`. :Parameters: - `key` - lock name - `owner` - name of application/component/whatever which asks for lock - `timeout` (optional) - how long to wait if `key` is locked - `expire` ...
python
{ "resource": "" }
q41651
MongoLock.touch
train
def touch(self, key, owner, expire=None): """Renew lock to avoid expiration. """ lock = self.collection.find_one({'_id': key, 'owner': owner}) if not lock: raise MongoLockException(u'Can\'t find lock for {key}: {owner}'.format(key=key, owner=owner)) if not lock['expire']: ...
python
{ "resource": "" }
q41652
PartialRequest.build_response
train
def build_response(self, response, path=None, parser=json_decode_wrapper, async=False): """ Builds a List or Dict response object. Wrapper for a response from the DataSift REST API, can be accessed as a list. :param response: HTTP response to wrap :type response: :class:`~d...
python
{ "resource": "" }
q41653
ControlCluster.compile_instance_masks
train
def compile_instance_masks(cls): """ Compiles instance masks into a master mask that is usable by the IO expander. Also determines whether or not the pump should be on. Method is generalized to support multiple IO expanders for possible future expansi...
python
{ "resource": "" }
q41654
ControlCluster.update
train
def update(self): """ This method exposes a more simple interface to the IO module Regardless of what the control instance contains, this method will transmit the queued IO commands to the IO expander Usage: plant1Control.update(bus) """ ControlCluster.compile_instance_m...
python
{ "resource": "" }
q41655
ControlCluster.form_GPIO_map
train
def form_GPIO_map(self): """ This method creates a dictionary to map plant IDs to GPIO pins are associated in triples. Each ID gets a light, a fan, and a mist nozzle. """ # Compute bank/pins/IOexpander address based on ID if self.ID == 1: self.IOexpander = 0x2...
python
{ "resource": "" }
q41656
ControlCluster.manage_pump
train
def manage_pump(self, operation): """ Updates control module knowledge of pump requests. If any sensor module requests water, the pump will turn on. """ if operation == "on": self.controls["pump"] = "on" elif operation == "off": self.controls["pum...
python
{ "resource": "" }
q41657
ControlCluster.control
train
def control(self, on=[], off=[]): """ This method serves as the primary interaction point to the controls interface. - The 'on' and 'off' arguments can either be a list or a single string. This allows for both individual device control and batch controls. Note: ...
python
{ "resource": "" }
q41658
ControlCluster.restore_state
train
def restore_state(self): """ Method should be called on obj. initialization When called, the method will attempt to restore IO expander and RPi coherence and restore local knowledge across a possible power failure """ current_mask = get_IO_reg(ControlCluster...
python
{ "resource": "" }
q41659
_key
train
def _key(key=''): ''' Returns a Datastore key object, prefixed with the NAMESPACE. ''' if not isinstance(key, datastore.Key): # Switchboard uses ':' to denote one thing (parent-child) and datastore # uses it for another, so replace ':' in the datastore version of the # key. ...
python
{ "resource": "" }
q41660
Model.update
train
def update(cls, spec, updates, upsert=False): ''' The spec is used to search for the data to update, updates contains the values to be updated, and upsert specifies whether to do an insert if the original data is not found. ''' if 'key' in spec: previous = cls...
python
{ "resource": "" }
q41661
Model._queryless_all
train
def _queryless_all(cls): ''' This is a hack because some datastore implementations don't support querying. Right now the solution is to drop down to the underlying native client and query all, which means that this section is ugly. If it were architected properly, you might be ab...
python
{ "resource": "" }
q41662
Switch.remove_condition
train
def remove_condition(self, manager, condition_set, field_name, condition, commit=True): """ Removes a condition and updates the global ``operator`` switch manager. If ``commit`` is ``False``, the data will not be written to the database. >>> switch = op...
python
{ "resource": "" }
q41663
Push.validate
train
def validate(self, output_type, output_params): """ Check that a subscription is defined correctly. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushvalidate :param output_type: One of DataSift's supported output types, e.g. s3 :type output_t...
python
{ "resource": "" }
q41664
Push.create_from_hash
train
def create_from_hash(self, stream, name, output_type, output_params, initial_status=None, start=None, end=None): """ Create a new push subscription using a live stream. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushcreate :param...
python
{ "resource": "" }
q41665
Push.create_from_historics
train
def create_from_historics(self, historics_id, name, output_type, output_params, initial_status=None, start=None, end=None): """ Create a new push subscription using the given Historic ID. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushcr...
python
{ "resource": "" }
q41666
Push.pause
train
def pause(self, subscription_id): """ Pause a Subscription and buffer the data for up to one hour. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushpause :param subscription_id: id of an existing Push Subscription. :type subscription_id: str ...
python
{ "resource": "" }
q41667
Push.resume
train
def resume(self, subscription_id): """ Resume a previously paused Subscription. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushresume :param subscription_id: id of an existing Push Subscription. :type subscription_id: str :returns...
python
{ "resource": "" }
q41668
Push.update
train
def update(self, subscription_id, output_params, name=None): """ Update the name or output parameters for an existing Subscription. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushupdate :param subscription_id: id of an existing Push Subscription. ...
python
{ "resource": "" }
q41669
Push.stop
train
def stop(self, subscription_id): """ Stop the given subscription from running. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushstop :param subscription_id: id of an existing Push Subscription. :type subscription_id: str :returns: d...
python
{ "resource": "" }
q41670
Push.delete
train
def delete(self, subscription_id): """ Delete the subscription for the given ID. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushdelete :param subscription_id: id of an existing Push Subscription. :type subscription_id: str :return...
python
{ "resource": "" }
q41671
Push.log
train
def log(self, subscription_id=None, page=None, per_page=None, order_by=None, order_dir=None): """ Retrieve any messages that have been logged for your subscriptions. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushlog :param subscription_id: optional id o...
python
{ "resource": "" }
q41672
Push.get
train
def get(self, subscription_id=None, stream=None, historics_id=None, page=None, per_page=None, order_by=None, order_dir=None, include_finished=None): """ Show details of the Subscriptions belonging to this user. Uses API documented at http://dev.datasift.com/docs/api/rest-api...
python
{ "resource": "" }
q41673
_git_receive_v1
train
def _git_receive_v1(msg, tmpl, **config): ''' Return the subtitle for the first version of pagure git.receive messages. ''' repo = _get_project(msg['msg']['commit'], key='repo') email = msg['msg']['commit']['email'] user = email2fas(email, **config) summ = msg['msg']['commit']['summary'] ...
python
{ "resource": "" }
q41674
_git_receive_v2
train
def _git_receive_v2(msg, tmpl): ''' Return the subtitle for the second version of pagure git.receive messages. ''' repo = _get_project(msg['msg'], key='repo') user = msg['msg']['agent'] n_commits = msg['msg']['total_commits'] commit_lbl = 'commit' if str(n_commits) == '1' else 'commits' ...
python
{ "resource": "" }
q41675
BaseDataManager.update
train
def update(self, archive_name, version_metadata): ''' Register a new version for archive ``archive_name`` .. note :: need to implement hash checking to prevent duplicate writes ''' version_metadata['updated'] = self.create_timestamp() version_metadata['versi...
python
{ "resource": "" }
q41676
BaseDataManager.update_metadata
train
def update_metadata(self, archive_name, archive_metadata): ''' Update metadata for archive ``archive_name`` ''' required_metadata_keys = self.required_archive_metadata.keys() for key, val in archive_metadata.items(): if key in required_metadata_keys and val is None: ...
python
{ "resource": "" }
q41677
BaseDataManager.create_archive
train
def create_archive( self, archive_name, authority_name, archive_path, versioned, raise_on_err=True, metadata=None, user_config=None, tags=None, helper=False): ''' Create a new data arc...
python
{ "resource": "" }
q41678
BaseDataManager.get_archive
train
def get_archive(self, archive_name): ''' Get a data archive given an archive name Returns ------- archive_specification : dict archive_name: name of the archive to be retrieved authority: name of the archive's authority archive_path: service p...
python
{ "resource": "" }
q41679
BaseDataManager.delete_tags
train
def delete_tags(self, archive_name, tags): ''' Delete tags from an archive Parameters ---------- archive_name:s tr Name of archive tags: list or tuple of strings tags to delete from the archive ''' updated_tag_list = list(self._g...
python
{ "resource": "" }
q41680
BaseDataManager._normalize_tags
train
def _normalize_tags(self, tags): ''' Coerces tags to lowercase strings Parameters ---------- tags: list or tuple of strings ''' lowered_str_tags = [] for tag in tags: lowered_str_tags.append(str(tag).lower()) return lowered_str_tags
python
{ "resource": "" }
q41681
Commander.start
train
def start(self): "Start the project on the directory" bookname = self.args.get('--bookname', None) if not bookname: bookname = 'book.md' project_dir = self.args.get('<name>', None) if not project_dir: project_dir = join(self.cwd, 'Book') project_di...
python
{ "resource": "" }
q41682
Commander.build
train
def build(self): "Build your book" config = self.load_config() html_generator = HTMLGenerator(self.cwd, config) html_generator.build() if self.args.get('--generator', None): generator = self.args.get('--generator') else: generator = config.get('ge...
python
{ "resource": "" }
q41683
Commander.check
train
def check(self): "Checks EPUB integrity" config = self.load_config() if not check_dependency_epubcheck(): sys.exit(error('Unavailable command.')) epub_file = u"%s.epub" % config['fileroot'] epub_path = join(CWD, 'build', epub_file) print success("Starting to c...
python
{ "resource": "" }
q41684
PostgresDatabase.create
train
def create(self, sql=None): """CREATE this DATABASE. @param sql: (Optional) A string of psql (such as might be generated by pg_dump); it will be executed by psql(1) after creating the database. @type sql: str @rtype: None """ create_sql = 'CREATE DATABAS...
python
{ "resource": "" }
q41685
PostgresDatabase.psql
train
def psql(self, args): r"""Invoke psql, passing the given command-line arguments. Typical <args> values: ['-c', <sql_string>] or ['-f', <pathname>]. Connection parameters are taken from self. STDIN, STDOUT, and STDERR are inherited from the parent. WARNING: This method uses th...
python
{ "resource": "" }
q41686
PostgresDatabase.sql
train
def sql(self, input_string, *args): """Execute a SQL command using the Python DBI directly. Connection parameters are taken from self. Autocommit is in effect. Example: .sql('SELECT %s FROM %s WHERE age > %s', 'name', 'table1', '45') @param input_string: A string of SQL. ...
python
{ "resource": "" }
q41687
PostgresServer.destroy
train
def destroy(self): """Undo the effects of initdb. Destroy all evidence of this DBMS, including its backing files. """ self.stop() if self.base_pathname is not None: self._robust_remove(self.base_pathname)
python
{ "resource": "" }
q41688
PostgresServer._robust_remove
train
def _robust_remove(path): """ Remove the directory specified by `path`. Because we can't determine directly if the path is in use, and on Windows, it's not possible to remove a path if it is in use, retry a few times until the call succeeds. """ tries = itertools....
python
{ "resource": "" }
q41689
PostgresServer.initdb
train
def initdb(self, quiet=True, locale='en_US.UTF-8'): """Bootstrap this DBMS from nothing. If you're running in an environment where the DBMS is provided as part of the basic infrastructure, you probably don't want to call this method! @param quiet: Should we operate quietly, emi...
python
{ "resource": "" }
q41690
PostgresServer._is_running
train
def _is_running(self, tries=10): """ Return if the server is running according to pg_ctl. """ # We can't possibly be running if our base_pathname isn't defined. if not self.base_pathname: return False if tries < 1: raise ValueError('tries must be ...
python
{ "resource": "" }
q41691
PostgresServer.ready
train
def ready(self): """ Assumes postgres now talks to pg_ctl, but might not yet be listening or connections from psql. Test that psql is able to connect, as it occasionally takes 5-10 seconds for postgresql to start listening. """ cmd = self._psql_cmd() for i in ran...
python
{ "resource": "" }
q41692
PostgresServer.start
train
def start(self): """Launch this postgres server. If it's already running, do nothing. If the backing storage directory isn't configured, raise NotInitializedError. This method is optional. If you're running in an environment where the DBMS is provided as part of the basic inf...
python
{ "resource": "" }
q41693
PostgresServer.stop
train
def stop(self): """Stop this DMBS daemon. If it's not currently running, do nothing. Don't return until it's terminated. """ log.info('Stopping PostgreSQL at %s:%s', self.host, self.port) if self._is_running(): cmd = [ PostgresFinder.find_root() / 'p...
python
{ "resource": "" }
q41694
PostgresServer.create
train
def create(self, db_name, **kwargs): """ Construct a PostgresDatabase and create it on self """ db = PostgresDatabase( db_name, host=self.host, port=self.port, superuser=self.superuser, **kwargs) db.ensure_user() db.create() return db
python
{ "resource": "" }
q41695
DynamoDBManager._search
train
def _search(self, search_terms, begins_with=None): """ Returns a list of Archive id's in the table on Dynamo """ kwargs = dict( ProjectionExpression='#id', ExpressionAttributeNames={"#id": "_id"}) if len(search_terms) > 0: kwargs['FilterExpr...
python
{ "resource": "" }
q41696
DynamoDBManager._update
train
def _update(self, archive_name, version_metadata): ''' Updates the version specific metadata attribute in DynamoDB In DynamoDB this is simply a list append on this attribute value Parameters ---------- archive_name: str unique '_id' primary key versi...
python
{ "resource": "" }
q41697
DynamoDBManager._create_archive_table
train
def _create_archive_table(self, table_name): ''' Dynamo implementation of BaseDataManager create_archive_table waiter object is implemented to ensure table creation before moving on this will slow down table creation. However, since we are only creating table once this should no...
python
{ "resource": "" }
q41698
DynamoDBManager._create_spec_config
train
def _create_spec_config(self, table_name, spec_documents): ''' Dynamo implementation of spec config creation Called by `create_archive_table()` in :py:class:`manager.BaseDataManager` Simply adds two rows to the spec table Parameters ---------- table_nam...
python
{ "resource": "" }
q41699
DynamoDBManager._update_spec_config
train
def _update_spec_config(self, document_name, spec): ''' Dynamo implementation of project specific metadata spec ''' # add the updated archive_metadata object to Dynamo self._spec_table.update_item( Key={'_id': '{}'.format(document_name)}, UpdateExpression...
python
{ "resource": "" }