_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q40700 | Daemon._write_pidfile | train | def _write_pidfile(self):
"""Create, write to, and lock the PID file."""
flags = os.O_CREAT | os.O_RDWR
try:
# Some systems don't have os.O_EXLOCK
flags = flags | os.O_EXLOCK
except AttributeError:
pass
self._pid_fd = os.open(self.pidfile, flag... | python | {
"resource": ""
} |
q40701 | Daemon._close_pidfile | train | def _close_pidfile(self):
"""Closes and removes the PID file."""
if self._pid_fd is not None:
os.close(self._pid_fd)
try:
os.remove(self.pidfile)
except OSError as ex:
if ex.errno != errno.ENOENT:
raise | python | {
"resource": ""
} |
q40702 | Daemon._prevent_core_dump | train | def _prevent_core_dump(cls):
"""Prevent the process from generating a core dump."""
try:
# Try to get the current limit
resource.getrlimit(resource.RLIMIT_CORE)
except ValueError:
# System doesn't support the RLIMIT_CORE resource limit
return
... | python | {
"resource": ""
} |
q40703 | Daemon._setup_environment | train | def _setup_environment(self):
"""Setup the environment for the daemon."""
# Save the original working directory so that reload can launch
# the new process with the same arguments as the original
self._orig_workdir = os.getcwd()
if self.chrootdir is not None:
try:
... | python | {
"resource": ""
} |
q40704 | Daemon._reset_file_descriptors | train | def _reset_file_descriptors(self):
"""Close open file descriptors and redirect standard streams."""
if self.close_open_files:
# Attempt to determine the max number of open files
max_fds = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
if max_fds == resource.RLIM_INFINI... | python | {
"resource": ""
} |
q40705 | Daemon._is_socket | train | def _is_socket(cls, stream):
"""Check if the given stream is a socket."""
try:
fd = stream.fileno()
except ValueError:
# If it has no file descriptor, it's not a socket
return False
sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_RAW)
try... | python | {
"resource": ""
} |
q40706 | Daemon._pid_is_alive | train | def _pid_is_alive(cls, pid, timeout):
"""Check if a PID is alive with a timeout."""
try:
proc = psutil.Process(pid)
except psutil.NoSuchProcess:
return False
try:
proc.wait(timeout=timeout)
except psutil.TimeoutExpired:
return True... | python | {
"resource": ""
} |
q40707 | Daemon._is_detach_necessary | train | def _is_detach_necessary(cls):
"""Check if detaching the process is even necessary."""
if os.getppid() == 1:
# Process was started by init
return False
if cls._is_socket(sys.stdin):
# If STDIN is a socket, the daemon was started by a super-server
... | python | {
"resource": ""
} |
q40708 | Daemon._detach_process | train | def _detach_process(self):
"""Detach the process via the standard double-fork method with
some extra magic."""
# First fork to return control to the shell
pid = os.fork()
if pid > 0:
# Wait for the first child, because it's going to wait and
# check to mak... | python | {
"resource": ""
} |
q40709 | Daemon._orphan_this_process | train | def _orphan_this_process(cls, wait_for_parent=False):
"""Orphan the current process by forking and then waiting for
the parent to exit."""
# The current PID will be the PPID of the forked child
ppid = os.getpid()
pid = os.fork()
if pid > 0:
# Exit parent
... | python | {
"resource": ""
} |
q40710 | Daemon._fork_and_supervise_child | train | def _fork_and_supervise_child(cls):
"""Fork a child and then watch the process group until there are
no processes in it."""
pid = os.fork()
if pid == 0:
# Fork again but orphan the child this time so we'll have
# the original parent and the second child which is o... | python | {
"resource": ""
} |
q40711 | Daemon._shutdown | train | def _shutdown(self, message=None, code=0):
"""Shutdown and cleanup everything."""
if self._shutdown_complete:
# Make sure we don't accidentally re-run the all cleanup
sys.exit(code)
if self.shutdown_callback is not None:
# Call the shutdown callback with a me... | python | {
"resource": ""
} |
q40712 | Daemon._handle_terminate | train | def _handle_terminate(self, signal_number, _):
"""Handle a signal to terminate."""
signal_names = {
signal.SIGINT: 'SIGINT',
signal.SIGQUIT: 'SIGQUIT',
signal.SIGTERM: 'SIGTERM',
}
message = 'Terminated by {name} ({number})'.format(
name=si... | python | {
"resource": ""
} |
q40713 | Daemon._run | train | def _run(self):
"""Run the worker function with some custom exception handling."""
try:
# Run the worker
self.worker()
except SystemExit as ex:
# sys.exit() was called
if isinstance(ex.code, int):
if ex.code is not None and ex.code ... | python | {
"resource": ""
} |
q40714 | Daemon.status | train | def status(self):
"""Get the status of the daemon."""
if self.pidfile is None:
raise DaemonError('Cannot get status of daemon without PID file')
pid = self._read_pidfile()
if pid is None:
self._emit_message(
'{prog} -- not running\n'.format(prog=s... | python | {
"resource": ""
} |
q40715 | Daemon.get_action | train | def get_action(self, action):
"""Get a callable action."""
func_name = action.replace('-', '_')
if not hasattr(self, func_name):
# Function doesn't exist
raise DaemonError(
'Invalid action "{action}"'.format(action=action))
func = getattr(self, fu... | python | {
"resource": ""
} |
q40716 | Daemon.reload | train | def reload(self):
"""Make the daemon reload itself."""
pid = self._read_pidfile()
if pid is None or pid != os.getpid():
raise DaemonError(
'Daemon.reload() should only be called by the daemon process '
'itself')
# Copy the current environment
... | python | {
"resource": ""
} |
q40717 | _get_windows | train | def _get_windows(peak_list):
"""
Given a list of peaks, bin them into windows.
"""
win_list = []
for t0, t1, hints in peak_list:
p_w = (t0, t1)
for w in win_list:
if p_w[0] <= w[0][1] and p_w[1] >= w[0][0]:
w[0] = (min(p_w[0], w[0][0]), max(p_w[1], w[0][1]... | python | {
"resource": ""
} |
q40718 | DKCloudAPI.list_order | train | def list_order(self, kitchen, save_to_file=None):
"""
List the orders for a kitchen or recipe
"""
rc = DKReturnCode()
if kitchen is None or isinstance(kitchen, basestring) is False:
rc.set(rc.DK_FAIL, 'issue with kitchen parameter')
return rc
url ... | python | {
"resource": ""
} |
q40719 | _date_trunc | train | def _date_trunc(value, timeframe):
"""
A date flooring function.
Returns the closest datetime to the current one that aligns to timeframe.
For example, _date_trunc('2014-08-13 05:00:00', DateTrunc.Unit.MONTH)
will return a Kronos time representing 2014-08-01 00:00:00.
"""
if isinstance(value, types.Strin... | python | {
"resource": ""
} |
q40720 | _date_part | train | def _date_part(value, part):
"""
Returns a portion of a datetime.
Returns the portion of a datetime represented by timeframe.
For example, _date_part('2014-08-13 05:00:00', DatePart.Unit.WEEK_DAY)
will return 2, for Wednesday.
"""
if isinstance(value, types.StringTypes):
value = parse(value)
else:
... | python | {
"resource": ""
} |
q40721 | Client.List | train | def List(self, name, initial=None):
"""The list datatype.
:param name: The name of the list.
:keyword initial: Initial contents of the list.
See :class:`redish.types.List`.
"""
return types.List(name, self.api, initial=initial) | python | {
"resource": ""
} |
q40722 | Client.Set | train | def Set(self, name, initial=None):
"""The set datatype.
:param name: The name of the set.
:keyword initial: Initial members of the set.
See :class:`redish.types.Set`.
"""
return types.Set(name, self.api, initial) | python | {
"resource": ""
} |
q40723 | Client.SortedSet | train | def SortedSet(self, name, initial=None):
"""The sorted set datatype.
:param name: The name of the sorted set.
:param initial: Initial members of the set as an iterable
of ``(element, score)`` tuples.
See :class:`redish.types.SortedSet`.
"""
return types.Sort... | python | {
"resource": ""
} |
q40724 | Client.Queue | train | def Queue(self, name, initial=None, maxsize=None):
"""The queue datatype.
:param name: The name of the queue.
:keyword initial: Initial items in the queue.
See :class:`redish.types.Queue`.
"""
return types.Queue(name, self.api, initial=initial, maxsize=maxsize) | python | {
"resource": ""
} |
q40725 | Client.LifoQueue | train | def LifoQueue(self, name, initial=None, maxsize=None):
"""The LIFO queue datatype.
:param name: The name of the queue.
:keyword initial: Initial items in the queue.
See :class:`redish.types.LifoQueue`.
"""
return types.LifoQueue(name, self.api,
... | python | {
"resource": ""
} |
q40726 | Client.rename | train | def rename(self, old_name, new_name):
"""Rename key to a new name."""
try:
self.api.rename(mkey(old_name), mkey(new_name))
except ResponseError, exc:
if "no such key" in exc.args:
raise KeyError(old_name)
raise | python | {
"resource": ""
} |
q40727 | csv | train | def csv(file, *args, **kwargs):
'''
Write CSV file.
Parameters
----------
file : Path
*args
csv.DictWriter args (except the f arg)
**kwargs
csv.DictWriter args
Examples
--------
with write.csv(file) as writer:
writer.writerow((1,2,3))
'''
with fi... | python | {
"resource": ""
} |
q40728 | State.encrypt | train | def encrypt(self, key):
"""This method encrypts and signs the state to make it unreadable by
the server, since it contains information that would allow faking
proof of storage.
:param key: the key to encrypt and sign with
"""
if (self.encrypted):
return
... | python | {
"resource": ""
} |
q40729 | State.decrypt | train | def decrypt(self, key):
"""This method checks the signature on the state and decrypts it.
:param key: the key to decrypt and sign with
"""
# check signature
if (self.get_hmac(key) != self.hmac):
raise HeartbeatError("Signature invalid on state.")
if (not self... | python | {
"resource": ""
} |
q40730 | PySwizzle.gen_challenge | train | def gen_challenge(self, state):
"""This function generates a challenge for given state. It selects a
random number and sets that as the challenge key. By default, v_max
is set to the prime, and the number of chunks to challenge is the
number of chunks in the file. (this doesn't guaran... | python | {
"resource": ""
} |
q40731 | PySwizzle.prove | train | def prove(self, file, chal, tag):
"""This function returns a proof calculated from the file, the
challenge, and the file tag
:param file: this is a file like object that supports `read()`,
`tell()` and `seek()` methods.
:param chal: the challenge to use for proving
:para... | python | {
"resource": ""
} |
q40732 | PySwizzle.verify | train | def verify(self, proof, chal, state):
"""This returns True if the proof matches the challenge and file state
:param proof: the proof that was returned from the server
:param chal: the challenge sent to the server
:param state: the state of the file, which can be encrypted
"""
... | python | {
"resource": ""
} |
q40733 | KronosClient.get_streams | train | def get_streams(self, namespace=None):
"""
Queries the Kronos server and fetches a list of streams available to be
read.
"""
request_dict = {}
namespace = namespace or self.namespace
if namespace is not None:
request_dict['namespace'] = namespace
response = self._make_request(self.... | python | {
"resource": ""
} |
q40734 | KronosClient.infer_schema | train | def infer_schema(self, stream, namespace=None):
"""
Queries the Kronos server and fetches the inferred schema for the
requested stream.
"""
return self._make_request(self._infer_schema_url,
data={'stream': stream,
'namespace': namespa... | python | {
"resource": ""
} |
q40735 | JonesClient._nodemap_changed | train | def _nodemap_changed(self, data, stat):
"""Called when the nodemap changes."""
if not stat:
raise EnvironmentNotFoundException(self.nodemap_path)
try:
conf_path = self._deserialize_nodemap(data)[self.hostname]
except KeyError:
conf_path = '/services/... | python | {
"resource": ""
} |
q40736 | JonesClient._config_changed | train | def _config_changed(self, data, stat):
"""Called when config changes."""
self.config = json.loads(data)
if self.cb:
self.cb(self.config) | python | {
"resource": ""
} |
q40737 | put_a_hit_out | train | def put_a_hit_out(name):
"""Download a feed's most recent enclosure that we don't have"""
feed = resolve_name(name)
if six.PY3:
feed = feed.decode()
d = feedparser.parse(feed)
# logger.info(d)
# logger.info(feed)
print(d['feed']['title'])
if d.entries[0].enclosures:
with... | python | {
"resource": ""
} |
q40738 | resolve_name | train | def resolve_name(name):
"""Takes a given input from a user and finds the url for it"""
logger.debug("resolve_name: %s", name)
with Database("feeds") as feeds, Database("aliases") as aliases:
if name in aliases.keys():
return feeds[aliases[name]]
elif name in feeds.keys():
... | python | {
"resource": ""
} |
q40739 | growl | train | def growl(text):
"""send native notifications where supported. Growl is gone."""
if platform.system() == 'Darwin':
import pync
pync.Notifier.notify(text, title="Hitman")
elif platform.system() == 'Linux':
notified = False
try:
logger.debug("Trying to import pynot... | python | {
"resource": ""
} |
q40740 | add_feed | train | def add_feed(url):
"""add to db"""
with Database("feeds") as db:
title = feedparser.parse(url).feed.title
name = str(title)
db[name] = url
return name | python | {
"resource": ""
} |
q40741 | del_alias | train | def del_alias(alias):
"""sometimes you goof up."""
with Database("aliases") as mydb:
try:
print("removing alias of %s to %s" % (alias, mydb.pop(alias)))
except KeyError:
print("No such alias key")
print("Check alias db:")
print(zip(list(mydb.keys()... | python | {
"resource": ""
} |
q40742 | alias_feed | train | def alias_feed(name, alias):
"""write aliases to db"""
with Database("aliases") as db:
if alias in db:
print("Something has gone horribly wrong with your aliases! Try deleting the %s entry." % name)
return
else:
db[alias] = name | python | {
"resource": ""
} |
q40743 | list_feeds | train | def list_feeds():
"""List all feeds in plain text and give their aliases"""
with Database("feeds") as feeds, Database("aliases") as aliases_db:
for feed in feeds:
name = feed
url = feeds[feed]
aliases = []
for k, v in zip(list(aliases_db.keys()), list(alia... | python | {
"resource": ""
} |
q40744 | import_opml | train | def import_opml(url):
"""Import an OPML file locally or from a URL. Uses your text attributes as aliases."""
# Test if URL given is local, then open, parse out feed urls,
# add feeds, set text= to aliases and report success, list feeds added
from bs4 import BeautifulSoup
try:
f = file(url).r... | python | {
"resource": ""
} |
q40745 | directory | train | def directory():
"""Construct hitman_dir from os name"""
home = os.path.expanduser('~')
if platform.system() == 'Linux':
hitman_dir = os.path.join(home, '.hitman')
elif platform.system() == 'Darwin':
hitman_dir = os.path.join(home, 'Library', 'Application Support',
... | python | {
"resource": ""
} |
q40746 | add | train | def add(url, force=False):
"""Add a atom or RSS feed by url.
If it doesn't end in .atom or .rss we'll do some guessing."""
if url[-3:] == 'xml' or url[1][-4:] == 'atom':
print("Added your feed as %s" % str(add_feed(url)))
elif is_feed(url):
print("Added your feed as %s" % str(add_feed(ur... | python | {
"resource": ""
} |
q40747 | set_settings | train | def set_settings(key, value):
"""Set Hitman internal settings."""
with Database("settings") as settings:
if value in ['0', 'false', 'no', 'off', 'False']:
del settings[key]
print("Disabled setting")
else:
print(value)
settings[key] = value
... | python | {
"resource": ""
} |
q40748 | get_settings | train | def get_settings(all,key):
"""View Hitman internal settings. Use 'all' for all keys"""
with Database("settings") as s:
if all:
for k, v in zip(list(s.keys()), list(s.values())):
print("{} = {}".format(k, v))
elif key:
print("{} = {}".format(key, s[key]))
... | python | {
"resource": ""
} |
q40749 | Challenge.fromdict | train | def fromdict(dict):
"""Takes a dictionary as an argument and returns a new Challenge
object from the dictionary.
:param dict: the dictionary to convert
"""
seed = hb_decode(dict['seed'])
index = dict['index']
return Challenge(seed, index) | python | {
"resource": ""
} |
q40750 | Tag.fromdict | train | def fromdict(dict):
"""Takes a dictionary as an argument and returns a new Tag object
from the dictionary.
:param dict: the dictionary to convert
"""
tree = MerkleTree.fromdict(dict['tree'])
chunksz = dict['chunksz']
filesz = dict['filesz']
return Tag(tre... | python | {
"resource": ""
} |
q40751 | Merkle.encode | train | def encode(self,
file,
n=DEFAULT_CHALLENGE_COUNT,
seed=None,
chunksz=None,
filesz=None):
"""This function generates a merkle tree with the leaves as seed file
hashes, the seed for each leaf being a deterministic seed generated
... | python | {
"resource": ""
} |
q40752 | Merkle.gen_challenge | train | def gen_challenge(self, state):
"""returns the next challenge and increments the seed and index
in the state.
:param state: the state to use for generating the challenge. will
verify the integrity of the state object before using it to generate
a challenge. it will then modify... | python | {
"resource": ""
} |
q40753 | Merkle.prove | train | def prove(self, file, challenge, tag):
"""Returns a proof of ownership of the given file based on the
challenge. The proof consists of a hash of the specified file chunk
and the complete merkle branch.
:param file: a file that supports `read()`, `seek()` and `tell()`
:param cha... | python | {
"resource": ""
} |
q40754 | Merkle.verify | train | def verify(self, proof, challenge, state):
"""returns true if the proof matches the challenge. verifies that the
server possesses the encoded file.
:param proof: the proof that was returned from the server
:param challenge: the challenge provided to the server
:param state: the... | python | {
"resource": ""
} |
q40755 | MerkleHelper.get_next_seed | train | def get_next_seed(key, seed):
"""This takes a seed and generates the next seed in the sequence.
it simply calculates the hmac of the seed with the key. It returns
the next seed
:param key: the key to use for the HMAC
:param seed: the seed to permutate
"""
return... | python | {
"resource": ""
} |
q40756 | MerkleHelper.get_file_hash | train | def get_file_hash(file, seed, bufsz=DEFAULT_BUFFER_SIZE):
"""This method generates a secure hash of the given file. Returns the
hash
:param file: a file like object to get a hash of. should support
`read()`
:param seed: the seed to use for key of the HMAC function
... | python | {
"resource": ""
} |
q40757 | MerkleHelper.get_chunk_hash | train | def get_chunk_hash(file,
seed,
filesz=None,
chunksz=DEFAULT_CHUNK_SIZE,
bufsz=DEFAULT_BUFFER_SIZE):
"""returns a hash of a chunk of the file provided. the position of
the chunk is determined by the seed. additi... | python | {
"resource": ""
} |
q40758 | Domain.from_tuple | train | def from_tuple(cls, queries):
"""Create a ``Domain`` given a set of complex query tuples.
Args:
queries (iter): An iterator of complex queries. Each iteration
should contain either:
* A data-set compatible with :func:`~domain.Domain.add_query`
... | python | {
"resource": ""
} |
q40759 | Domain.add_query | train | def add_query(self, query, join_with=AND):
"""Join a new query to existing queries on the stack.
Args:
query (tuple or list or DomainCondition): The condition for the
query. If a ``DomainCondition`` object is not provided, the
input should conform to the inte... | python | {
"resource": ""
} |
q40760 | DomainCondition.from_tuple | train | def from_tuple(cls, query):
"""Create a condition from a query tuple.
Args:
query (tuple or list): Tuple or list that contains a query domain
in the format of ``(field_name, field_value,
field_value_to)``. ``field_value_to`` is only applicable in
... | python | {
"resource": ""
} |
q40761 | StorageRouter.load_backends | train | def load_backends(self):
"""
Loads all the backends setup in settings.py.
"""
for name, backend_settings in settings.storage.iteritems():
backend_path = backend_settings['backend']
backend_module, backend_cls = backend_path.rsplit('.', 1)
backend_module = import_module(backend_module)
... | python | {
"resource": ""
} |
q40762 | StorageRouter.get_matching_prefix | train | def get_matching_prefix(self, namespace, stream):
"""
We look at the stream prefixs configured in stream.yaml and match stream
to the longest prefix.
"""
validate_stream(stream)
default_prefix = ''
longest_prefix = default_prefix
for prefix in self.prefix_confs[namespace]:
if prefi... | python | {
"resource": ""
} |
q40763 | StorageRouter.backends_to_mutate | train | def backends_to_mutate(self, namespace, stream):
"""
Return all the backends enabled for writing for `stream`.
"""
if namespace not in self.namespaces:
raise NamespaceMissing('`{}` namespace is not configured'
.format(namespace))
return self.prefix_confs[namespace]... | python | {
"resource": ""
} |
q40764 | StorageRouter.backend_to_retrieve | train | def backend_to_retrieve(self, namespace, stream):
"""
Return backend enabled for reading for `stream`.
"""
if namespace not in self.namespaces:
raise NamespaceMissing('`{}` namespace is not configured'
.format(namespace))
stream_prefix = self.get_matching_prefix(na... | python | {
"resource": ""
} |
q40765 | WebHook.create | train | def create(cls, session, web_hook):
"""Create a web hook.
Note that creating a new web hook will overwrite the web hook that is
already configured for this company. There is also no way to
programmatically determine if a web hook already exists for the
company. This is a limitat... | python | {
"resource": ""
} |
q40766 | AttachmentData.raw_data | train | def raw_data(self, value):
"""Set the base64 encoded data using a raw value or file object."""
if value:
try:
value = value.read()
except AttributeError:
pass
b64 = base64.b64encode(value.encode('utf-8'))
self.data = b64.dec... | python | {
"resource": ""
} |
q40767 | schedule | train | def schedule():
"""HTTP endpoint for scheduling tasks
If a task with the same code already exists, the one with the shorter
interval will be made active.
"""
code = request.form['code']
interval = int(request.form['interval'])
task_id = binascii.b2a_hex(os.urandom(5))
new_task = Task(id=task_id)
new... | python | {
"resource": ""
} |
q40768 | cancel | train | def cancel():
"""HTTP endpoint for canceling tasks
If an active task is cancelled, an inactive task with the same code and the
smallest interval will be activated if it exists.
"""
task_id = request.form['id']
task = Task.query.get(task_id)
if not task:
return json.dumps({
'status': 'success',... | python | {
"resource": ""
} |
q40769 | OplogReplayer.insert | train | def insert(self, ns, docid, raw, **kw):
""" Perform a single insert operation.
{'docid': ObjectId('4e95ae77a20e6164850761cd'),
'ns': u'mydb.tweets',
'raw': {u'h': -1469300750073380169L,
u'ns': u'mydb.tweets',
u'o': {u'_id': ObjectI... | python | {
"resource": ""
} |
q40770 | OplogReplayer.update | train | def update(self, ns, docid, raw, **kw):
""" Perform a single update operation.
{'docid': ObjectId('4e95ae3616692111bb000001'),
'ns': u'mydb.tweets',
'raw': {u'h': -5295451122737468990L,
u'ns': u'mydb.tweets',
u'o': {u'$set': {u'con... | python | {
"resource": ""
} |
q40771 | OplogReplayer.delete | train | def delete(self, ns, docid, raw, **kw):
""" Perform a single delete operation.
{'docid': ObjectId('4e959ea11669210edc002902'),
'ns': u'mydb.tweets',
'raw': {u'b': True,
u'h': -8347418295715732480L,
u'ns': u'mydb.tweets',
... | python | {
"resource": ""
} |
q40772 | OplogReplayer.drop_index | train | def drop_index(self, raw):
""" Executes a drop index command.
{ "op" : "c",
"ns" : "testdb.$cmd",
"o" : { "dropIndexes" : "testcoll",
"index" : "nuie_1" } }
"""
dbname = raw['ns'].split('.', 1)[0]
collname = raw['o']['dropIndexes']... | python | {
"resource": ""
} |
q40773 | OplogReplayer.command | train | def command(self, ns, raw, **kw):
""" Executes command.
{ "op" : "c",
"ns" : "testdb.$cmd",
"o" : { "drop" : "fs.files"}
}
"""
try:
dbname = raw['ns'].split('.', 1)[0]
self.dest[dbname].command(raw['o'], check=True)
... | python | {
"resource": ""
} |
q40774 | Mailboxes.get_folders | train | def get_folders(cls, session, mailbox_or_id):
"""List the folders for the mailbox.
Args:
mailbox_or_id (helpscout.models.Mailbox or int): Mailbox or the ID
of the mailbox to get the folders for.
Returns:
RequestPaginator(output_type=helpscout.models.Fold... | python | {
"resource": ""
} |
q40775 | Board.json | train | def json(self):
"""A JSON-encoded description of this board.
Format:
{'id': board_id,
'title': 'The title of the board',
'panels': [{
'title': 'The title of the panel'
'data_source': {
'source_type': PanelSource.TYPE,
'refresh_seconds': 600,
...source_spec... | python | {
"resource": ""
} |
q40776 | get | train | def get(dataset = None, include_metadata = False, mnemonics = None, **dim_values):
"""Use this function to get data from Knoema dataset."""
if not dataset and not mnemonics:
raise ValueError('Dataset id is not specified')
if mnemonics and dim_values:
raise ValueError('The function d... | python | {
"resource": ""
} |
q40777 | delete | train | def delete(dataset):
"""Use this function to delete dataset by it's id."""
config = ApiConfig()
client = ApiClient(config.host, config.app_id, config.app_secret)
client.check_correct_host()
client.delete(dataset)
return ('Dataset {} has been deleted successfully'.format(dataset)) | python | {
"resource": ""
} |
q40778 | verify | train | def verify(dataset, publication_date, source, refernce_url):
"""Use this function to verify a dataset."""
config = ApiConfig()
client = ApiClient(config.host, config.app_id, config.app_secret)
client.check_correct_host()
client.verify(dataset, publication_date, source, refernce_url) | python | {
"resource": ""
} |
q40779 | OplogWatcher.start | train | def start(self):
""" Starts the OplogWatcher. """
oplog = self.connection.local['oplog.rs']
if self.ts is None:
cursor = oplog.find().sort('$natural', -1)
obj = cursor[0]
if obj:
self.ts = obj['ts']
else:
# In case ... | python | {
"resource": ""
} |
q40780 | OplogWatcher.process_op | train | def process_op(self, ns, raw):
""" Processes a single operation from the oplog.
Performs a switch by raw['op']:
"i" insert
"u" update
"d" delete
"c" db cmd
"db" declares presence of a database
"n" no op
"""
# Comput... | python | {
"resource": ""
} |
q40781 | multi_way_partitioning | train | def multi_way_partitioning(items, bin_count): #TODO rename bin_count -> bins
'''
Greedily divide weighted items equally across bins.
This approximately solves a multi-way partition problem, minimising the
difference between the largest and smallest sum of weights in a bin.
Parameters
---------... | python | {
"resource": ""
} |
q40782 | _GlobalFigure.set_foregroundcolor | train | def set_foregroundcolor(self, color):
'''For the specified axes, sets the color of the frame, major ticks,
tick labels, axis labels, title and legend
'''
ax = self.ax
for tl in ax.get_xticklines() + ax.get_yticklines():
tl.set_color(color)
for spi... | python | {
"resource": ""
} |
q40783 | _BaseDataPerClass._getPlotData | train | def _getPlotData(self):
""" Turns the resultsByClass Dict into a list of bin groups skipping the uncertain group if empty
return: (label list, ydata list)
:rtype: tuple(list(str), list(float))
"""
resultsByClass = self.resultsByClass
try:
if resultsByClass['... | python | {
"resource": ""
} |
q40784 | DataPerParameterBin._genKeysBins | train | def _genKeysBins(self):
""" Generates keys from bins, sets self._allowedKeys normally set in _classVariables
"""
binlimits = self._binlimits
allowedKeys = []
midbinlimits = binlimits
if binlimits[0] == -float('inf'):
midbinlimits = binlimits[1:] # remove th... | python | {
"resource": ""
} |
q40785 | GeneralPlotter._set_axis | train | def _set_axis(self, param, unit):
""" this should take a variable or a function and turn it into a list by evaluating on each planet
"""
axisValues = []
for astroObject in self.objectList:
try:
value = eval('astroObject.{0}'.format(param))
except a... | python | {
"resource": ""
} |
q40786 | DiscoveryMethodByYear.setup_keys | train | def setup_keys(self):
""" Build the initial data dictionary to store the values
"""
discovery_methods = {}
discovery_years = {}
nan_list = []
# Initial Loop to get keys
for planet in self.planet_list:
if 'Solar System' in planet.params['list'] and se... | python | {
"resource": ""
} |
q40787 | plot_confusion_matrix | train | def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
i... | python | {
"resource": ""
} |
q40788 | is_zsettable | train | def is_zsettable(s):
"""quick check that all values in a dict are reals"""
return all(map(lambda x: isinstance(x, (int, float, long)), s.values())) | python | {
"resource": ""
} |
q40789 | List.trim | train | def trim(self, start, stop):
"""Trim the list to the specified range of elements."""
return self.client.ltrim(self.name, start, stop - 1) | python | {
"resource": ""
} |
q40790 | List.remove | train | def remove(self, value, count=1):
"""Remove occurences of ``value`` from the list.
:keyword count: Number of matching values to remove.
Default is to remove a single value.
"""
count = self.client.lrem(self.name, value, num=count)
if not count:
raise Val... | python | {
"resource": ""
} |
q40791 | Set.remove | train | def remove(self, member):
"""Remove element from set; it must be a member.
:raises KeyError: if the element is not a member.
"""
if not self.client.srem(self.name, member):
raise KeyError(member) | python | {
"resource": ""
} |
q40792 | Set.pop | train | def pop(self):
"""Remove and return an arbitrary set element.
:raises KeyError: if the set is empty.
"""
member = self.client.spop(self.name)
if member is not None:
return member
raise KeyError() | python | {
"resource": ""
} |
q40793 | Set.union | train | def union(self, other):
"""Return the union of sets as a new set.
(i.e. all elements that are in either set.)
Operates on either redish.types.Set or __builtins__.set.
"""
if isinstance(other, self.__class__):
return self.client.sunion([self.name, other.name])
... | python | {
"resource": ""
} |
q40794 | Set.update | train | def update(self, other):
"""Update this set with the union of itself and others."""
if isinstance(other, self.__class__):
return self.client.sunionstore(self.name, [self.name, other.name])
else:
return map(self.add, other) | python | {
"resource": ""
} |
q40795 | Set.intersection | train | def intersection(self, other):
"""Return the intersection of two sets as a new set.
(i.e. all elements that are in both sets.)
Operates on either redish.types.Set or __builtins__.set.
"""
if isinstance(other, self.__class__):
return self.client.sinter([self.name, o... | python | {
"resource": ""
} |
q40796 | Set.intersection_update | train | def intersection_update(self, other):
"""Update the set with the intersection of itself and another."""
return self.client.sinterstore(self.name, [self.name, other.name]) | python | {
"resource": ""
} |
q40797 | Set.difference_update | train | def difference_update(self, other):
"""Remove all elements of another set from this set."""
return self.client.sdiffstore(self.name, [self.name, other.name]) | python | {
"resource": ""
} |
q40798 | SortedSet.add | train | def add(self, member, score):
"""Add the specified member to the sorted set, or update the score
if it already exist."""
return self.client.zadd(self.name, member, score) | python | {
"resource": ""
} |
q40799 | SortedSet.remove | train | def remove(self, member):
"""Remove member."""
if not self.client.zrem(self.name, member):
raise KeyError(member) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.