_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q45800 | Connection.recv | train | def recv(self):
"""Receives a message from PS and decrypts it and returns a Message"""
LOGGER.debug('Receiving')
try:
message_length = struct.unpack('>i', self._socket.recv(4))[0]
message_length -= Connection.COMM_LENGTH
LOGGER.debug('Length: %i', message_leng... | python | {
"resource": ""
} |
q45801 | Connection.send | train | def send(self, content):
"""Sends a JavaScript command to PS
:param content: Script content
:type content: str
:yields: :class:`.Message`
"""
LOGGER.debug('Sending: %s', content)
all_bytes = struct.pack('>i', Connection.PROTOCOL_VERSION)
all_bytes += stru... | python | {
"resource": ""
} |
q45802 | watch_command | train | def watch_command(context, backend, config, poll):
"""
Watch for change on your Sass project sources then compile them to CSS.
Watched events are:
\b
* Create: when a new source file is created;
* Change: when a source is changed;
* Delete: when a source is deleted;
* Move: When a sour... | python | {
"resource": ""
} |
q45803 | init | train | def init(deb1, deb2=False):
"""Initialize DEBUG and DEBUGALL.
Allows other modules to set DEBUG and DEBUGALL, so their
call to dprint or dprintx generate output.
Args:
deb1 (bool): value of DEBUG to set
deb2 (bool): optional - value of DEBUGALL to set,
defaults to ... | python | {
"resource": ""
} |
q45804 | dprintx | train | def dprintx(passeditem, special=False):
"""Print Text if DEBUGALL set, optionally with PrettyPrint.
Args:
passeditem (str): item to print
special (bool): determines if item prints with PrettyPrint
or regular print.
"""
if DEBUGALL:
if special:
... | python | {
"resource": ""
} |
q45805 | get | train | def get(url, **kwargs):
"""
Wrapper for `request.get` function to set params.
"""
headers = kwargs.get('headers', {})
headers['User-Agent'] = config.USER_AGENT # overwrite
kwargs['headers'] = headers
timeout = kwargs.get('timeout', config.TIMEOUT)
kwargs['timeout'] = timeout
kwargs... | python | {
"resource": ""
} |
q45806 | phantomjs_get | train | def phantomjs_get(url):
"""
Perform the request via PhantomJS.
"""
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = config.USER_AGENT
dcap[... | python | {
"resource": ""
} |
q45807 | NwcpymatgenTcodtranslator.get_atom_type_symbol | train | def get_atom_type_symbol(cls,calc,**kwargs):
"""
Returns a list of atom types. Each atom site MUST occur only
once in this list. List MUST be sorted.
"""
parameters = calc.out.output
dictionary = parameters.get_dict()
if 'basis_set' not in dictionary.keys():
... | python | {
"resource": ""
} |
q45808 | FilterProcessor.tag_handler | train | def tag_handler(self, cmd):
"""Process a TagCommand."""
# Keep tags if they indirectly reference something we kept
cmd.from_ = self._find_interesting_from(cmd.from_)
self.keep = cmd.from_ is not None | python | {
"resource": ""
} |
q45809 | FilterProcessor._print_command | train | def _print_command(self, cmd):
"""Wrapper to avoid adding unnecessary blank lines."""
text = helpers.repr_bytes(cmd)
self.outf.write(text)
if not text.endswith(b'\n'):
self.outf.write(b'\n') | python | {
"resource": ""
} |
q45810 | FilterProcessor._filter_filecommands | train | def _filter_filecommands(self, filecmd_iter):
"""Return the filecommands filtered by includes & excludes.
:return: a list of FileCommand objects
"""
if self.includes is None and self.excludes is None:
return list(filecmd_iter())
# Do the filtering, adjusting for the... | python | {
"resource": ""
} |
q45811 | FilterProcessor._path_to_be_kept | train | def _path_to_be_kept(self, path):
"""Does the given path pass the filtering criteria?"""
if self.excludes and (path in self.excludes
or helpers.is_inside_any(self.excludes, path)):
return False
if self.includes:
return (path in self.includes
... | python | {
"resource": ""
} |
q45812 | FilterProcessor._adjust_for_new_root | train | def _adjust_for_new_root(self, path):
"""Adjust a path given the new root directory of the output."""
if self.new_root is None:
return path
elif path.startswith(self.new_root):
return path[len(self.new_root):]
else:
return path | python | {
"resource": ""
} |
q45813 | FilterProcessor._convert_rename | train | def _convert_rename(self, fc):
"""Convert a FileRenameCommand into a new FileCommand.
:return: None if the rename is being ignored, otherwise a
new FileCommand based on the whether the old and new paths
are inside or outside of the interesting locations.
"""
old = ... | python | {
"resource": ""
} |
q45814 | FilterProcessor._convert_copy | train | def _convert_copy(self, fc):
"""Convert a FileCopyCommand into a new FileCommand.
:return: None if the copy is being ignored, otherwise a
new FileCommand based on the whether the source and destination
paths are inside or outside of the interesting locations.
"""
s... | python | {
"resource": ""
} |
q45815 | bundle | train | def bundle(context, yes, bundle_name):
"""Delete the latest bundle version."""
bundle_obj = context.obj['store'].bundle(bundle_name)
if bundle_obj is None:
click.echo(click.style('bundle not found', fg='red'))
context.abort()
version_obj = bundle_obj.versions[0]
if version_obj.includ... | python | {
"resource": ""
} |
q45816 | files | train | def files(context, yes, tag, bundle, before, notondisk):
"""Delete files based on tags."""
file_objs = []
if not tag and not bundle:
click.echo("I'm afraid I can't let you do that.")
context.abort()
if bundle:
bundle_obj = context.obj['store'].bundle(bundle)
if bundle_o... | python | {
"resource": ""
} |
q45817 | sam_readline | train | def sam_readline(sock, partial = None):
"""read a line from a sam control socket"""
response = b''
exception = None
while True:
try:
c = sock.recv(1)
if not c:
raise EOFError('SAM connection died. Partial response %r %r' % (partial, response))
... | python | {
"resource": ""
} |
q45818 | sam_parse_reply | train | def sam_parse_reply(line):
"""parse a reply line into a dict"""
parts = line.split(' ')
opts = {k: v for (k, v) in split_kv(parts[2:])}
return SAMReply(parts[0], opts) | python | {
"resource": ""
} |
q45819 | sam_send | train | def sam_send(sock, line_and_data):
"""Send a line to the SAM controller, but don't read it"""
if isinstance(line_and_data, tuple):
line, data = line_and_data
else:
line, data = line_and_data, b''
line = bytes(line, encoding='ascii') + b' \n'
# print('-->', line, data)
sock.senda... | python | {
"resource": ""
} |
q45820 | sam_cmd | train | def sam_cmd(sock, line, parse=True):
"""Send a line to the SAM controller, returning the parsed response"""
sam_send(sock, line)
reply_line = sam_readline(sock)
if parse:
return sam_parse_reply(reply_line)
else:
return reply_line | python | {
"resource": ""
} |
q45821 | handshake | train | def handshake(timeout, sam_api, max_version):
"""handshake with sam via a socket.socket instance"""
sock = controller_connect(sam_api, timeout=timeout)
response = sam_cmd(sock, greet(max_version))
if response.ok:
return sock
else:
raise HandshakeError("Failed to handshake with SAM: %... | python | {
"resource": ""
} |
q45822 | lookup | train | def lookup(sock, domain, cache = None):
"""lookup an I2P domain name, returning a Destination instance"""
domain = normalize_domain(domain)
# cache miss, perform lookup
reply = sam_cmd(sock, "NAMING LOOKUP NAME=%s" % domain)
b64_dest = reply.get('VALUE')
if b64_dest:
dest = Dest(b64_de... | python | {
"resource": ""
} |
q45823 | HistoryHandler.post | train | async def post(self):
"""
Accepts json-rpc post request.
Retrieves data from request body.
Calls defined method in field 'method_name'
"""
request = self.request.body.decode()
response = await methods.dispatch(request)
if not response.is_notification:
... | python | {
"resource": ""
} |
q45824 | get_template_directories | train | def get_template_directories():
"""This function tries to figure out where template directories are located.
It first inspects the TEMPLATES setting, and if that exists and is not
empty, uses its values.
Otherwise, the values from all of the defined DIRS within TEMPLATES are used.
Returns a set of... | python | {
"resource": ""
} |
q45825 | urls_from_file_tree | train | def urls_from_file_tree(template_dir):
"""Generates a list of URL strings that would match each staticflatpage."""
urls = [] # keep a list of of all the files/paths
# Should be somethign like:
# /path/to/myproject/templates/staticflatpages
root_dir = join(template_dir, 'staticflatpages')
for ... | python | {
"resource": ""
} |
q45826 | get_terminal_size | train | def get_terminal_size(defaultw=80):
""" Checks various methods to determine the terminal size
Methods:
- shutil.get_terminal_size (only Python3)
- fcntl.ioctl
- subprocess.check_output
- os.environ
Parameters
----------
defaultw : int
Default width of terminal.
Retur... | python | {
"resource": ""
} |
q45827 | FormField.compress | train | def compress(self, data_list):
"""
Return the cleaned_data of the form, everything should already be valid
"""
data = {}
if data_list:
return dict(
(f.name, data_list[i]) for i, f in enumerate(self.form))
return data | python | {
"resource": ""
} |
q45828 | FormField.clean | train | def clean(self, value):
"""
Call the form is_valid to ensure every value supplied is valid
"""
if not value:
raise ValidationError(
'Error found in Form Field: Nothing to validate')
data = dict((bf.name, value[i]) for i, bf in enumerate(self.form))
... | python | {
"resource": ""
} |
q45829 | MOCTool.run | train | def run(self, params):
"""Main run method for PyMOC tool.
Takes a list of command line arguments to process.
Each operation is performed on a current "running" MOC
object.
"""
self.params = list(reversed(params))
if not self.params:
self.help()
... | python | {
"resource": ""
} |
q45830 | MOCTool.read_moc | train | def read_moc(self, filename):
"""Read a file into the current running MOC object.
If the running MOC object has not yet been created, then
it is created by reading the file, which will import the
MOC metadata. Otherwise the metadata are not imported.
"""
if self.moc is... | python | {
"resource": ""
} |
q45831 | MOCTool.catalog | train | def catalog(self):
"""Create MOC from catalog of coordinates.
This command requires that the Healpy and Astropy libraries
be available. It attempts to load the given catalog,
and merges it with the running MOC.
The name of an ASCII catalog file should be given. The file
... | python | {
"resource": ""
} |
q45832 | MOCTool.help | train | def help(self):
"""Display command usage information."""
if self.params:
command = self.params.pop().lstrip('-')
if command in self.command.documentation:
(aliases, doc) = self.command.documentation[command]
(synopsis, body) = self._split_docstri... | python | {
"resource": ""
} |
q45833 | MOCTool.identifier | train | def identifier(self):
"""Set the identifier of the current MOC.
The new identifier should be given after this option.
::
pymoctool ... --id 'New MOC identifier' --output new_moc.fits
"""
if self.moc is None:
self.moc = MOC()
self.moc.id = self... | python | {
"resource": ""
} |
q45834 | MOCTool.display_info | train | def display_info(self):
"""Display basic information about the running MOC."""
if self.moc is None:
print('No MOC information present')
return
if self.moc.name is not None:
print('Name:', self.moc.name)
if self.moc.id is not None:
print('... | python | {
"resource": ""
} |
q45835 | MOCTool.intersection | train | def intersection(self):
"""Compute the intersection with the given MOC.
This command takes the name of a MOC file and forms the intersection
of the running MOC with that file.
::
pymoctool a.fits --intersection b.fits --output intersection.fits
"""
if self... | python | {
"resource": ""
} |
q45836 | MOCTool.name | train | def name(self):
"""Set the name of the current MOC.
The new name should be given after this option.
::
pymoctool ... --name 'New MOC name' --output new_moc.fits
"""
if self.moc is None:
self.moc = MOC()
self.moc.name = self.params.pop() | python | {
"resource": ""
} |
q45837 | MOCTool.normalize | train | def normalize(self):
"""Normalize the MOC to a given order.
This command takes a MOC order (0-29) and normalizes the MOC so that
its maximum order is the given order.
::
pymoctool a.fits --normalize 10 --output a_10.fits
"""
if self.moc is None:
... | python | {
"resource": ""
} |
q45838 | MOCTool.write_moc | train | def write_moc(self):
"""Write the MOC to a given file."""
if self.moc is None:
raise CommandError('No MOC information present for output')
filename = self.params.pop()
self.moc.write(filename) | python | {
"resource": ""
} |
q45839 | MOCTool.subtract | train | def subtract(self):
"""Subtract the given MOC from the running MOC.
This command takes the name of a MOC file to be subtracted from the
running MOC.
::
pymoctool a.fits --subtract b.fits --output difference.fits
"""
if self.moc is None:
raise C... | python | {
"resource": ""
} |
q45840 | MOCTool.plot | train | def plot(self):
"""Show the running MOC on an all-sky map.
This command requires that the Healpy and matplotlib libraries be
available. It plots the running MOC, which should be normalized to
a lower order first if it would generate an excessively large pixel
array.
::... | python | {
"resource": ""
} |
q45841 | load_synapses | train | def load_synapses(path=HOME + "/Downloads/pinky100_final.df",
scaling=(1, 1, 1)):
""" Test scenario using real synapses """
scaling = np.array(list(scaling))
df = pd.read_csv(path)
locs = np.array(df[["presyn_x", "centroid_x", "postsyn_x"]])
mask = ~np.any(np.isnan(locs), axis=... | python | {
"resource": ""
} |
q45842 | include | train | def include(context, bundle_name, version):
"""Include a bundle of files into the internal space.
Use bundle name if you simply want to inlcude the latest version.
"""
store = Store(context.obj['database'], context.obj['root'])
if version:
version_obj = store.Version.get(version)
if... | python | {
"resource": ""
} |
q45843 | Service.ingress_filter | train | def ingress_filter(self, response):
""" Flatten a response with meta and data keys into an object. """
data = self.data_getter(response)
if isinstance(data, dict):
data = m_data.DictResponse(data)
elif isinstance(data, list):
data = m_data.ListResponse(data)
... | python | {
"resource": ""
} |
q45844 | Service.get_pager | train | def get_pager(self, *path, **kwargs):
""" A generator for all the results a resource can provide. The pages
are lazily loaded. """
page_arg = kwargs.pop('page_size', None)
limit_arg = kwargs.pop('limit', None)
kwargs['limit'] = page_arg or limit_arg or self.default_page_size
... | python | {
"resource": ""
} |
q45845 | RefTracker.track_heads | train | def track_heads(self, cmd):
"""Track the repository heads given a CommitCommand.
:param cmd: the CommitCommand
:return: the list of parents in terms of commit-ids
"""
# Get the true set of parents
if cmd.from_ is not None:
parents = [cmd.from_]
else:
... | python | {
"resource": ""
} |
q45846 | metasay | train | def metasay(ctx, inputfile, item):
"""Moo some dataset metadata to stdout.
Python module: rio-metasay
(https://github.com/sgillies/rio-plugin-example).
"""
with rasterio.open(inputfile) as src:
meta = src.profile
click.echo(moothedata(meta, key=item)) | python | {
"resource": ""
} |
q45847 | load_pdb | train | def load_pdb(pdb, path=True, pdb_id='', ignore_end=False):
"""Converts a PDB file into an AMPAL object.
Parameters
----------
pdb : str
Either a path to a PDB file or a string containing PDB
format structural data.
path : bool, optional
If `true`, flags `pdb` as a path and n... | python | {
"resource": ""
} |
q45848 | PdbParser.gen_states | train | def gen_states(self, monomer_data, parent):
"""Generates the `states` dictionary for a `Monomer`.
monomer_data : list
A list of atom data parsed from the input PDB.
parent : ampal.Monomer
`Monomer` used to assign `parent` on created
`Atoms`.
"""
... | python | {
"resource": ""
} |
q45849 | PdbParser.check_for_non_canonical | train | def check_for_non_canonical(residue):
"""Checks to see if the residue is non-canonical."""
res_label = list(residue[0])[0][2]
atom_labels = {x[2] for x in itertools.chain(
*residue[1].values())} # Used to find unnatural aas
if (all(x in atom_labels for x in ['N', 'CA', 'C', ... | python | {
"resource": ""
} |
q45850 | get_inst_info | train | def get_inst_info(qry_string):
"""Get details for instances that match the qry_string.
Execute a query against the AWS EC2 client object, that is
based on the contents of qry_string.
Args:
qry_string (str): the query to be used against the aws ec2 client.
Returns:
qry_results (dict... | python | {
"resource": ""
} |
q45851 | get_all_aminames | train | def get_all_aminames(i_info):
"""Get Image_Name for each instance in i_info.
Args:
i_info (dict): information on instances and details.
Returns:
i_info (dict): i_info is returned with the aminame
added for each instance.
"""
for i in i_info:
try:
... | python | {
"resource": ""
} |
q45852 | get_one_aminame | train | def get_one_aminame(inst_img_id):
"""Get Image_Name for the image_id specified.
Args:
inst_img_id (str): image_id to get name value from.
Returns:
aminame (str): name of the image.
"""
try:
aminame = EC2R.Image(inst_img_id).name
except AttributeError:
aminame = ... | python | {
"resource": ""
} |
q45853 | startstop | train | def startstop(inst_id, cmdtodo):
"""Start or Stop the Specified Instance.
Args:
inst_id (str): instance-id to perform command against
cmdtodo (str): command to perform (start or stop)
Returns:
response (dict): reponse returned from AWS after
performing speci... | python | {
"resource": ""
} |
q45854 | GitHubRegion.addCity | train | def addCity(self, fileName):
"""Add a JSON file and read the users.
:param fileName: path to the JSON file. This file has to have a list of
users, called users.
:type fileName: str.
"""
with open(fileName) as data_file:
data = load(data_file)
for u in... | python | {
"resource": ""
} |
q45855 | GitHubRegion.__getTemplate | train | def __getTemplate(template_file_name):
"""Get temaplte to save the ranking.
:param template_file_name: path to the template.
:type template_file_name: str.
:return: template for the file.
:rtype: pystache's template.
"""
with open(template_file_name) as template... | python | {
"resource": ""
} |
q45856 | setup_logging | train | def setup_logging(logging_config, debug=False):
"""Setup logging config."""
if logging_config is not None:
logging.config.fileConfig(logging_config)
else:
logging.basicConfig(level=debug and logging.DEBUG or logging.ERROR) | python | {
"resource": ""
} |
q45857 | loop | train | def loop(sock, config=None):
"""Loops over all docker events and executes subscribed callbacks with an
optional config value.
:param config: a dictionary with external config values
"""
if config is None:
config = {}
client = docker.Client(base_url=sock)
# fake a running event f... | python | {
"resource": ""
} |
q45858 | join_configs | train | def join_configs(configs):
"""Join all config files into one config."""
joined_config = {}
for config in configs:
joined_config.update(yaml.load(config))
return joined_config | python | {
"resource": ""
} |
q45859 | load_modules | train | def load_modules(modules):
"""Load a module."""
for dotted_module in modules:
try:
__import__(dotted_module)
except ImportError as e:
LOG.error("Unable to import %s: %s", dotted_module, e) | python | {
"resource": ""
} |
q45860 | load_files | train | def load_files(files):
"""Load and execute a python file."""
for py_file in files:
LOG.debug("exec %s", py_file)
execfile(py_file, globals(), locals()) | python | {
"resource": ""
} |
q45861 | summarize_events | train | def summarize_events():
"""Some information about active events and callbacks."""
for ev in event.events:
if ev.callbacks:
LOG.info("subscribed to %s by %s", ev, ', '.join(imap(repr, ev.callbacks))) | python | {
"resource": ""
} |
q45862 | cli | train | def cli(sock, configs, modules, files, log, debug):
"""The CLI."""
setup_logging(log, debug)
config = join_configs(configs)
# load python modules
load_modules(modules)
# load python files
load_files(files)
# summarize active events and callbacks
summarize_events()
gloop = g... | python | {
"resource": ""
} |
q45863 | MOC.type | train | def type(self, value):
"""Set the type of the MOC.
The value should be either "IMAGE" or "CATALOG".
"""
self._type = None
if value is None:
return
value = value.upper()
if value in MOC_TYPES:
self._type = value
else:
... | python | {
"resource": ""
} |
q45864 | MOC.area | train | def area(self):
"""The area enclosed by the MOC, in steradians.
>>> m = MOC(0, (0, 1, 2))
>>> round(m.area, 2)
3.14
"""
self.normalize()
area = 0.0
for (order, cells) in self:
area += (len(cells) * pi) / (3 * 4 ** order)
return area | python | {
"resource": ""
} |
q45865 | MOC.cells | train | def cells(self):
"""The number of cells in the MOC.
This gives the total number of cells at all orders,
with cells from every order counted equally.
>>> m = MOC(0, (1, 2))
>>> m.cells
2
"""
n = 0
for (order, cells) in self:
n += len... | python | {
"resource": ""
} |
q45866 | MOC.add | train | def add(self, order, cells, no_validation=False):
"""Add cells at a given order to the MOC.
The cells are inserted into the MOC at the specified order. This
leaves the MOC in an un-normalized state. The cells are given
as a collection of integers (or types which can be converted
... | python | {
"resource": ""
} |
q45867 | MOC.remove | train | def remove(self, order, cells):
"""Remove cells at a given order from the MOC.
"""
self._normalized = False
order = self._validate_order(order)
for cell in cells:
cell = self._validate_cell(order, cell)
self._compare_operation(order, cell, True, 'remov... | python | {
"resource": ""
} |
q45868 | MOC.clear | train | def clear(self):
"""Clears all cells from a MOC.
>>> m = MOC(4, (5, 6))
>>> m.clear()
>>> m.cells
0
"""
for order in range(0, MAX_ORDER + 1):
self._orders[order].clear()
self._normalized = True | python | {
"resource": ""
} |
q45869 | MOC.copy | train | def copy(self):
"""Return a copy of a MOC.
>>> p = MOC(4, (5, 6))
>>> q = p.copy()
>>> repr(q)
'<MOC: [(4, [5, 6])]>'
"""
copy = MOC(name=self.name, mocid=self.id,
origin=self.origin, moctype=self.type)
copy += self
return co... | python | {
"resource": ""
} |
q45870 | MOC.contains | train | def contains(self, order, cell, include_smaller=False):
"""Test whether the MOC contains the given cell.
If the include_smaller argument is true then the MOC is considered
to include a cell if it includes part of that cell (at a higher
order).
>>> m = MOC(1, (5,))
>>> m... | python | {
"resource": ""
} |
q45871 | MOC._compare_operation | train | def _compare_operation(self, order, cell, include_smaller, operation):
"""General internal method for comparison-based operations.
This is a private method, and does not update the normalized
flag.
"""
# Check for a larger cell (lower order) which contains the
# given c... | python | {
"resource": ""
} |
q45872 | MOC.intersection | train | def intersection(self, other):
"""Returns a MOC representing the intersection with another MOC.
>>> p = MOC(2, (3, 4, 5))
>>> q = MOC(2, (4, 5, 6))
>>> p.intersection(q)
<MOC: [(2, [4, 5])]>
"""
inter = MOC()
for (order, cells) in other:
for... | python | {
"resource": ""
} |
q45873 | MOC.normalize | train | def normalize(self, max_order=MAX_ORDER):
"""Ensure that the MOC is "well-formed".
This structures the MOC as is required for the FITS and JSON
representation. This method is invoked automatically when writing
to these formats.
The number of cells in the MOC will be minimized,... | python | {
"resource": ""
} |
q45874 | MOC.flattened | train | def flattened(self, order=None, include_smaller=True):
"""Return a flattened pixel collection at a single order."""
if order is None:
order = self.order
else:
order = self._validate_order(order)
# Start with the cells which are already at this order.
fla... | python | {
"resource": ""
} |
q45875 | MOC.read | train | def read(self, filename, filetype=None, include_meta=False, **kwargs):
"""Read data from the given file into the MOC object.
The cell lists read from the file are added to the current
object. Therefore if the object already contains some
cells, it will be updated to represent the union... | python | {
"resource": ""
} |
q45876 | MOC.write | train | def write(self, filename, filetype=None, **kwargs):
"""Write the coverage data in the MOC object to a file.
The filetype can be given or left to be inferred as for the
read method.
Any additional keyword arguments (kwargs) are passed on to
the corresponding pymoc.io write funct... | python | {
"resource": ""
} |
q45877 | MOC._guess_file_type | train | def _guess_file_type(self, filename):
"""Attempt to guess the type of a MOC file.
Returns "fits", "json" or "ascii" if successful and raised
a ValueError otherwise.
"""
# First attempt to guess from the file name.
namelc = filename.lower()
if namelc.endswith('.... | python | {
"resource": ""
} |
q45878 | MOC._validate_order | train | def _validate_order(self, order):
"""Check that the given order is valid."""
try:
order = int(order)
except ValueError as e:
raise TypeError('MOC order must be convertable to int')
if not 0 <= order <= MAX_ORDER:
raise ValueError(
'MO... | python | {
"resource": ""
} |
q45879 | MOC._validate_cell | train | def _validate_cell(self, order, cell):
"""Check that the given cell is valid.
The order is assumed already to have been validated.
"""
max_cells = self._order_num_cells(order)
try:
cell = int(cell)
except ValueError as e:
raise TypeError('MOC ce... | python | {
"resource": ""
} |
q45880 | queues_for_endpoint | train | def queues_for_endpoint(event):
"""
Return the list of queues to publish to for a given endpoint.
:param event: Lambda event that triggered the handler
:type event: dict
:return: list of queues for endpoint
:rtype: :std:term:`list`
:raises: Exception
"""
global endpoints # endpoint... | python | {
"resource": ""
} |
q45881 | msg_body_for_event | train | def msg_body_for_event(event, context):
"""
Generate the JSON-serialized message body for an event.
:param event: Lambda event that triggered the handler
:type event: dict
:param context: Lambda function context - see
http://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html
... | python | {
"resource": ""
} |
q45882 | handle_event | train | def handle_event(event, context):
"""
Do the actual event handling - try to enqueue the request.
:param event: Lambda event that triggered the handler
:type event: dict
:param context: Lambda function context - see
http://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html
:re... | python | {
"resource": ""
} |
q45883 | try_enqueue | train | def try_enqueue(conn, queue_name, msg):
"""
Try to enqueue a message. If it succeeds, return the message ID.
:param conn: SQS API connection
:type conn: :py:class:`botocore:SQS.Client`
:param queue_name: name of queue to put message in
:type queue_name: str
:param msg: JSON-serialized messa... | python | {
"resource": ""
} |
q45884 | serializable_dict | train | def serializable_dict(d):
"""
Return a dict like d, but with any un-json-serializable elements removed.
"""
newd = {}
for k in d.keys():
if isinstance(d[k], type({})):
newd[k] = serializable_dict(d[k])
continue
try:
json.dumps({'k': d[k]})
... | python | {
"resource": ""
} |
q45885 | cmdline | train | def cmdline(argv=sys.argv[1:]):
"""
Script for rebasing a text file
"""
parser = ArgumentParser(
description='Rebase a text from his stop words')
parser.add_argument('language', help='The language used to rebase')
parser.add_argument('source', help='Text file to rebase')
options = pa... | python | {
"resource": ""
} |
q45886 | MongoStorage.create | train | def create(self, data):
"""Creates new entry in mongo database
"""
q = self.history.insert_one(data).inserted_id
logging.debug(self.history.find_one({"_id":q})) | python | {
"resource": ""
} |
q45887 | Table.get_url | train | def get_url(self, **kwargs):
"""
Return an url, relative to the request associated with this
table. Any keywords arguments provided added to the query
string, replacing existing values.
"""
return build(
self._request.path,
self._request.GET,
... | python | {
"resource": ""
} |
q45888 | Table.rows | train | def rows(self):
"""Return the list of object on the active page."""
return map(
lambda o: self._meta.row_class(self, o),
self.paginator.page(self._meta.page).object_list ) | python | {
"resource": ""
} |
q45889 | SublemonSubprocess.spawn | train | async def spawn(self):
"""Spawn the command wrapped in this object as a subprocess."""
self._server._pending_set.add(self)
await self._server._sem.acquire()
self._subprocess = await asyncio.create_subprocess_shell(
self._cmd,
stdout=asyncio.subprocess.PIPE,
... | python | {
"resource": ""
} |
q45890 | SublemonSubprocess.wait_done | train | async def wait_done(self) -> int:
"""Coroutine to wait for subprocess run completion.
Returns:
The exit code of the subprocess.
"""
await self._done_running_evt.wait()
if self._exit_code is None:
raise SublemonLifetimeError(
'Subprocess e... | python | {
"resource": ""
} |
q45891 | SublemonSubprocess._poll | train | def _poll(self) -> None:
"""Check the status of the wrapped running subprocess.
Note:
This should only be called on currently-running tasks.
"""
if self._subprocess is None:
raise SublemonLifetimeError(
'Attempted to poll a non-active subprocess'... | python | {
"resource": ""
} |
q45892 | SublemonSubprocess.stdout | train | async def stdout(self) -> AsyncGenerator[str, None]:
"""Asynchronous generator for lines from subprocess stdout."""
await self.wait_running()
async for line in self._subprocess.stdout: # type: ignore
yield line | python | {
"resource": ""
} |
q45893 | SublemonSubprocess.stderr | train | async def stderr(self) -> AsyncGenerator[str, None]:
"""Asynchronous generator for lines from subprocess stderr."""
await self.wait_running()
async for line in self._subprocess.stderr: # type: ignore
yield line | python | {
"resource": ""
} |
q45894 | Task._execute | train | def _execute(self, worker):
"""
This method is ASSIGNED during the evaluation to control how to resume it once it has been paused
"""
self._assert_status_is(TaskStatus.RUNNING)
operation = worker.look_up(self.operation)
operation.invoke(self, [], worker=worker) | python | {
"resource": ""
} |
q45895 | Column.value | train | def value(self, cell):
"""
Extract the value of ``cell``, ready to be rendered.
If this Column was instantiated with a ``value`` attribute, it
is called here to provide the value. (For example, to provide a
calculated value.) Otherwise, ``cell.value`` is returned.
"""
... | python | {
"resource": ""
} |
q45896 | Column.css_class | train | def css_class(self, cell):
"""Return the CSS class for this column."""
if isinstance(self._css_class, basestring):
return self._css_class
else:
return self._css_class(cell) | python | {
"resource": ""
} |
q45897 | WrappedColumn.sort_url | train | def sort_url(self):
"""
Return the URL to sort the linked table by this column. If the
table is already sorted by this column, the order is reversed.
Since there is no canonical URL for a table the current URL (via
the HttpRequest linked to the Table instance) is reused, and any... | python | {
"resource": ""
} |
q45898 | check_or_confirm_overwrite | train | def check_or_confirm_overwrite(file_name):
"""
Returns True if OK to proceed, False otherwise
"""
try:
with open(file_name) as fd:
header = next(fd)
if header.find(':sedge:') == -1:
okay = ask_overwrite(file_name)
if okay:
... | python | {
"resource": ""
} |
q45899 | update | train | def update(config):
"""
Update ssh config from sedge specification
"""
def write_to(out):
engine.output(out)
config_file = Path(config.config_file)
if not config_file.is_file():
click.echo('No file {} '.format(config_file), err=True)
sys.exit()
library = KeyLibrary... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.