_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q28900 | WriteWatchingStream.write | train | def write(self, data):
"""
Write the given data to the file.
"""
# Do the write
self.backingStream.write(data)
| python | {
"resource": ""
} |
q28901 | ServiceManager.scheduleServices | train | def scheduleServices(self, jobGraph):
"""
Schedule the services of a job asynchronously.
When the job's services are running the jobGraph for the job will
be returned by toil.leader.ServiceManager.getJobGraphsWhoseServicesAreRunning.
:param toil.jobGraph.JobGraph jobGraph: wrapp... | python | {
"resource": ""
} |
q28902 | ServiceManager.shutdown | train | def shutdown(self):
"""
Cleanly terminate worker threads starting and killing services. Will block
until all services are started and blocked.
"""
logger.debug('Waiting for service manager thread to finish ...')
startTime = time.time()
self._terminate.set()
... | python | {
"resource": ""
} |
q28903 | ServiceManager._startServices | train | def _startServices(jobGraphsWithServicesToStart,
jobGraphsWithServicesThatHaveStarted,
serviceJobsToStart,
terminate, jobStore):
"""
Thread used to schedule services.
"""
servicesThatAreStarting = set()
services... | python | {
"resource": ""
} |
q28904 | optimize_spot_bid | train | def optimize_spot_bid(ctx, instance_type, spot_bid):
"""
Check whether the bid is sane and makes an effort to place the instance in a sensible zone.
"""
spot_history = _get_spot_history(ctx, instance_type)
if spot_history:
_check_spot_bid(spot_bid, spot_history)
| python | {
"resource": ""
} |
q28905 | _check_spot_bid | train | def _check_spot_bid(spot_bid, spot_history):
"""
Prevents users from potentially over-paying for instances
Note: this checks over the whole region, not a particular zone
:param spot_bid: float
:type spot_history: list[SpotPriceHistory]
:raises UserError: if bid is > 2X the spot price's avera... | python | {
"resource": ""
} |
q28906 | checkValidNodeTypes | train | def checkValidNodeTypes(provisioner, nodeTypes):
"""
Raises if an invalid nodeType is specified for aws, azure, or gce.
:param str provisioner: 'aws', 'gce', or 'azure' to specify which cloud provisioner used.
:param nodeTypes: A list of node types. Example: ['t2.micro', 't2.medium']
:return: Noth... | python | {
"resource": ""
} |
q28907 | padStr | train | def padStr(s, field=None):
""" Pad the begining of a string with spaces, if necessary.
"""
| python | {
"resource": ""
} |
q28908 | prettyMemory | train | def prettyMemory(k, field=None, isBytes=False):
""" Given input k as kilobytes, return a nicely formatted string.
"""
if isBytes:
k /= 1024
if k < 1024:
return padStr("%gK" % k, field)
if k < (1024 * 1024):
return padStr("%.1fM" % (old_div(k, 1024.0)), field)
if k < (1024... | python | {
"resource": ""
} |
q28909 | prettyTime | train | def prettyTime(t, field=None):
""" Given input t as seconds, return a nicely formatted string.
"""
from math import floor
pluralDict = {True: "s", False: ""}
if t < 120:
return padStr("%ds" % t, field)
if t < 120 * 60:
m = floor(old_div(t, 60.))
s = t % 60
return ... | python | {
"resource": ""
} |
q28910 | reportTime | train | def reportTime(t, options, field=None):
""" Given t seconds, report back the correct format as string.
"""
if options.pretty:
return prettyTime(t, field=field)
else:
| python | {
"resource": ""
} |
q28911 | reportMemory | train | def reportMemory(k, options, field=None, isBytes=False):
""" Given k kilobytes, report back the correct format as string.
"""
if options.pretty:
return prettyMemory(int(k), field=field, isBytes=isBytes)
else:
if isBytes:
k /= 1024.
| python | {
"resource": ""
} |
q28912 | refineData | train | def refineData(root, options):
""" walk down from the root and gather up the important bits.
"""
worker = root.worker
job = root.jobs
jobTypesTree = root.job_types
| python | {
"resource": ""
} |
q28913 | decorateSubHeader | train | def decorateSubHeader(title, columnWidths, options):
""" Add a marker to the correct field if the TITLE is sorted on.
"""
title = title.lower()
if title != options.sortCategory:
s = "| %*s%*s%*s%*s%*s " % (
columnWidths.getWidth(title, "min"), "min",
columnWidths.getWidth... | python | {
"resource": ""
} |
q28914 | get | train | def get(tree, name):
""" Return a float value attribute NAME from TREE.
"""
if name in tree:
value = tree[name]
else:
return float("nan")
try:
| python | {
"resource": ""
} |
q28915 | sortJobs | train | def sortJobs(jobTypes, options):
""" Return a jobTypes all sorted.
"""
longforms = {"med": "median",
"ave": "average",
"min": "min",
"total": "total",
"max": "max",}
sortField = longforms[options.sortField]
if (options.sortCategory ... | python | {
"resource": ""
} |
q28916 | reportPrettyData | train | def reportPrettyData(root, worker, job, job_types, options):
""" print the important bits out.
"""
out_str = "Batch System: %s\n" % root.batch_system
out_str += ("Default Cores: %s Default Memory: %s\n"
"Max Cores: %s\n" % (
reportNumber(get(root, "default_cores"), options),
... | python | {
"resource": ""
} |
q28917 | updateColumnWidths | train | def updateColumnWidths(tag, cw, options):
""" Update the column width attributes for this tag's fields.
"""
longforms = {"med": "median",
"ave": "average",
"min": "min",
"total": "total",
"max": "max",}
for category in ["time", "clock",... | python | {
"resource": ""
} |
q28918 | buildElement | train | def buildElement(element, items, itemName):
""" Create an element for output.
"""
def assertNonnegative(i,name):
if i < 0:
raise RuntimeError("Negative value %s reported for %s" %(i,name) )
else:
return float(i)
itemTimes = []
itemClocks = []
itemMemory =... | python | {
"resource": ""
} |
q28919 | getStats | train | def getStats(jobStore):
""" Collect and return the stats and config data.
"""
def aggregateStats(fileHandle,aggregateObject):
try:
stats = json.load(fileHandle, object_hook=Expando)
for key in list(stats.keys()):
if key in aggregateObject:
... | python | {
"resource": ""
} |
q28920 | processData | train | def processData(config, stats):
"""
Collate the stats and report
"""
if 'total_time' not in stats or 'total_clock' not in stats:
# toil job not finished yet
stats.total_time = [0.0]
stats.total_clock = [0.0]
stats.total_time = sum([float(number) for number in stats.total_tim... | python | {
"resource": ""
} |
q28921 | ColumnWidths.title | train | def title(self, category):
""" Return the total printed length of this category item.
"""
| python | {
"resource": ""
} |
q28922 | nextChainableJobGraph | train | def nextChainableJobGraph(jobGraph, jobStore):
"""Returns the next chainable jobGraph after this jobGraph if one
exists, or None if the chain must terminate.
"""
#If no more jobs to run or services not finished, quit
if len(jobGraph.stack) == 0 or len(jobGraph.services) > 0 or jobGraph.checkpoint !=... | python | {
"resource": ""
} |
q28923 | LoggingDatagramHandler.handle | train | def handle(self):
"""
Handle a single message. SocketServer takes care of splitting out the messages.
Messages are JSON-encoded logging module records.
"""
# Unpack the data from the request
data, socket = self.request
try:
# Parse it... | python | {
"resource": ""
} |
q28924 | RealtimeLogger._stopLeader | train | def _stopLeader(cls):
"""
Stop the server on the leader.
"""
with cls.lock:
assert cls.initialized > 0
cls.initialized -= 1
if cls.initialized == 0:
if cls.loggingServer:
log.info('Stopping real-time logging server.'... | python | {
"resource": ""
} |
q28925 | RealtimeLogger.getLogger | train | def getLogger(cls):
"""
Get the logger that logs real-time to the leader.
Note that if the returned logger is used on the leader, you will see the message twice,
since it still goes to the normal log handlers, too.
"""
# Only do the setup once, so we don't add a ... | python | {
"resource": ""
} |
q28926 | uploadFromPath | train | def uploadFromPath(localFilePath, partSize, bucket, fileID, headers):
"""
Uploads a file to s3, using multipart uploading if applicable
:param str localFilePath: Path of the file to upload to s3
:param int partSize: max size of each part in the multipart upload, in bytes
:param boto.s3.Bucket bucke... | python | {
"resource": ""
} |
q28927 | copyKeyMultipart | train | def copyKeyMultipart(srcBucketName, srcKeyName, srcKeyVersion, dstBucketName, dstKeyName, sseAlgorithm=None, sseKey=None,
copySourceSseAlgorithm=None, copySourceSseKey=None):
"""
Copies a key from a source key to a destination key in multiple parts. Note that if the
destination key exis... | python | {
"resource": ""
} |
q28928 | _put_attributes_using_post | train | def _put_attributes_using_post(self, domain_or_name, item_name, attributes,
replace=True, expected_value=None):
"""
Monkey-patched version of SDBConnection.put_attributes that uses POST instead of GET
The GET version is subject to the URL length limit which kicks in before th... | python | {
"resource": ""
} |
q28929 | logFile | train | def logFile(fileName, printFunction=logger.info):
"""Writes out a formatted version of the given log file
"""
printFunction("Reporting file: %s" % fileName)
shortName = fileName.split("/")[-1]
| python | {
"resource": ""
} |
q28930 | logStream | train | def logStream(fileHandle, shortName, printFunction=logger.info):
"""Writes out a formatted version of the given log stream.
"""
printFunction("Reporting file: %s" % shortName)
line = fileHandle.readline()
while line != '':
if line[-1] == '\n':
| python | {
"resource": ""
} |
q28931 | system | train | def system(command):
"""
A convenience wrapper around subprocess.check_call that logs the command before passing it
on. The command can be either a string or a sequence of strings. If it is a string shell=True
will be passed to subprocess.check_call.
| python | {
"resource": ""
} |
q28932 | absSymPath | train | def absSymPath(path):
"""like os.path.abspath except it doesn't dereference symlinks | python | {
"resource": ""
} |
q28933 | makePublicDir | train | def makePublicDir(dirName):
"""Makes a given subdirectory if it doesn't already exist, making sure it is public.
"""
if not os.path.exists(dirName):
| python | {
"resource": ""
} |
q28934 | write_AST | train | def write_AST(wdl_file, outdir=None):
'''
Writes a file with the AST for a wdl file in the outdir.
'''
if outdir is None:
outdir = os.getcwd()
| python | {
"resource": ""
} |
q28935 | SynthesizeWDL.write_main | train | def write_main(self):
'''
Writes out a huge string representing the main section of the python
compiled toil script.
Currently looks at and writes 5 sections:
1. JSON Variables (includes importing and preparing files as tuples)
2. TSV Variables (includes importing and pr... | python | {
"resource": ""
} |
q28936 | SynthesizeWDL.write_main_jobwrappers | train | def write_main_jobwrappers(self):
'''
Writes out 'jobs' as wrapped toil objects in preparation for calling.
:return: A string representing this.
'''
main_section = ''
# toil cannot technically start with multiple jobs, so an empty
# 'initialize_jobs' function is... | python | {
"resource": ""
} |
q28937 | SynthesizeWDL.write_scatterfunction | train | def write_scatterfunction(self, job, scattername):
'''
Writes out a python function for each WDL "scatter" object.
'''
scatter_outputs = self.fetch_scatter_outputs(job)
# write the function header
fn_section = self.write_scatterfunction_header(scattername)
# wr... | python | {
"resource": ""
} |
q28938 | SynthesizeWDL.write_function_bashscriptline | train | def write_function_bashscriptline(self, job):
'''
Writes a function to create a bashscript for injection into the docker
container.
:param job_task_reference: The job referenced in WDL's Task section.
:param job_alias: The actual job name to be written.
:return: A string... | python | {
"resource": ""
} |
q28939 | SynthesizeWDL.write_python_file | train | def write_python_file(self,
module_section,
fn_section,
main_section,
output_file):
'''
Just takes three strings and writes them to output_file.
:param module_section: A string of 'import mod... | python | {
"resource": ""
} |
q28940 | MesosBatchSystem._buildExecutor | train | def _buildExecutor(self):
"""
Creates and returns an ExecutorInfo-shaped object representing our executor implementation.
"""
# The executor program is installed as a setuptools entry point by setup.py
info = addict.Dict()
info.name = "toil"
info.command.value | python | {
"resource": ""
} |
q28941 | MesosBatchSystem._startDriver | train | def _startDriver(self):
"""
The Mesos driver thread which handles the scheduler's communication with the Mesos master
"""
framework = addict.Dict()
framework.user = getpass.getuser() # We must determine the user name ourselves with pymesos
framework.name = "toil"
... | python | {
"resource": ""
} |
q28942 | MesosBatchSystem.registered | train | def registered(self, driver, frameworkId, masterInfo):
"""
Invoked when the scheduler successfully registers with a Mesos master
"""
| python | {
"resource": ""
} |
q28943 | MesosBatchSystem._newMesosTask | train | def _newMesosTask(self, job, offer):
"""
Build the Mesos task object for a given the Toil job and Mesos offer
"""
task = addict.Dict()
task.task_id.value = str(job.jobID)
task.agent_id.value = offer.agent_id.value
task.name = job.name
task.data = encode_da... | python | {
"resource": ""
} |
q28944 | MesosBatchSystem.frameworkMessage | train | def frameworkMessage(self, driver, executorId, agentId, message):
"""
Invoked when an executor sends a message.
"""
# Take it out of base 64 encoding from Protobuf
message = decode_data(message)
log.debug('Got framework message from executor %s running o... | python | {
"resource": ""
} |
q28945 | MesosBatchSystem._registerNode | train | def _registerNode(self, nodeAddress, agentId, nodePort=5051):
"""
Called when we get communication from an agent. Remembers the
information about the agent by address, and the agent address by agent
ID.
"""
executor = self.executors.get(nodeAddress)
if executor is... | python | {
"resource": ""
} |
q28946 | Node.remainingBillingInterval | train | def remainingBillingInterval(self):
"""
If the node has a launch time, this function returns a floating point value
between 0 and 1.0 representing how far we are into the
current billing cycle for the given instance. If the return value is .25, we are one
quarter into the billing... | python | {
"resource": ""
} |
q28947 | Node.copySshKeys | train | def copySshKeys(self, keyName):
""" Copy authorized_keys file to the core user from the keyName user."""
if keyName == 'core':
return # No point.
# Make sure that keys are there.
self._waitForSSHKeys(keyName=keyName)
# copy keys to core user so that the ssh calls wi... | python | {
"resource": ""
} |
q28948 | Node.injectFile | train | def injectFile(self, fromFile, toFile, role):
"""
rysnc a file to the vm with the given role
"""
maxRetries = 10
for retry in range(maxRetries):
try:
self.coreRsync([fromFile, ":" + toFile], applianceName=role)
return True
e... | python | {
"resource": ""
} |
q28949 | Node._waitForSSHPort | train | def _waitForSSHPort(self):
"""
Wait until the instance represented by this box is accessible via SSH.
:return: the number of unsuccessful attempts to connect to the port before a the first
success
"""
logger.debug('Waiting for ssh port to open...')
for i in count... | python | {
"resource": ""
} |
q28950 | Node.sshInstance | train | def sshInstance(self, *args, **kwargs):
"""
Run a command on the instance.
Returns the binary output of the command.
| python | {
"resource": ""
} |
q28951 | adjustEndingReservationForJob | train | def adjustEndingReservationForJob(reservation, jobShape, wallTime):
"""
Add a job to an ending reservation that ends at wallTime, splitting
the reservation if the job doesn't fill the entire timeslice.
"""
if jobShape.wallTime - wallTime < reservation.shape.wallTime:
# This job only partiall... | python | {
"resource": ""
} |
q28952 | split | train | def split(nodeShape, jobShape, wallTime):
"""
Partition a node allocation into two to fit the job, returning the
modified shape of the node and a new node reservation for
the extra time that the job didn't fill.
"""
return (Shape(wallTime,
nodeShape.memory - jobShape.memory,
... | python | {
"resource": ""
} |
q28953 | BinPackedFit.binPack | train | def binPack(self, jobShapes):
"""Pack a list of jobShapes into the fewest nodes reasonable. Can be run multiple times."""
# TODO: Check for redundancy with batchsystems.mesos.JobQueue() sorting
logger.debug('Running bin packing for node shapes %s and %s job(s).',
self.nodeSh... | python | {
"resource": ""
} |
q28954 | BinPackedFit.getRequiredNodes | train | def getRequiredNodes(self):
"""
Returns a dict from node shape to number of nodes required to run the packed jobs.
"""
| python | {
"resource": ""
} |
q28955 | NodeReservation.fits | train | def fits(self, jobShape):
"""Check if a job shape's resource requirements will fit within this allocation."""
return jobShape.memory <= self.shape.memory and \
jobShape.cores <= self.shape.cores and \
| python | {
"resource": ""
} |
q28956 | NodeReservation.shapes | train | def shapes(self):
"""Get all time-slice shapes, in order, from this reservation on."""
shapes = []
curRes = self
while curRes is not None:
| python | {
"resource": ""
} |
q28957 | NodeReservation.subtract | train | def subtract(self, jobShape):
"""
Subtracts the resources necessary to run a jobShape from the reservation.
"""
self.shape = Shape(self.shape.wallTime,
self.shape.memory - jobShape.memory,
| python | {
"resource": ""
} |
q28958 | ClusterScaler.setStaticNodes | train | def setStaticNodes(self, nodes, preemptable):
"""
Used to track statically provisioned nodes. This method must be called
before any auto-scaled nodes are provisioned.
These nodes are treated differently than auto-scaled nodes in that they should
not be automatically terminated.
... | python | {
"resource": ""
} |
q28959 | ClusterScaler.smoothEstimate | train | def smoothEstimate(self, nodeShape, estimatedNodeCount):
"""
Smooth out fluctuations in the estimate for this node compared to
previous runs. Returns an integer.
"""
weightedEstimate = (1 - self.betaInertia) * estimatedNodeCount + \
| python | {
"resource": ""
} |
q28960 | ClusterScaler.getEstimatedNodeCounts | train | def getEstimatedNodeCounts(self, queuedJobShapes, currentNodeCounts):
"""
Given the resource requirements of queued jobs and the current size of the cluster, returns
a dict mapping from nodeShape to the number of nodes we want in the cluster right now.
"""
nodesToRunQueuedJobs = ... | python | {
"resource": ""
} |
q28961 | ClusterScaler.setNodeCount | train | def setNodeCount(self, nodeType, numNodes, preemptable=False, force=False):
"""
Attempt to grow or shrink the number of preemptable or non-preemptable worker nodes in
the cluster to the given value, or as close a value as possible, and, after performing
the necessary additions or removal... | python | {
"resource": ""
} |
q28962 | ClusterScaler.getNodes | train | def getNodes(self, preemptable):
"""
Returns a dictionary mapping node identifiers of preemptable or non-preemptable nodes to
NodeInfo objects, one for each node.
This method is the definitive source on nodes in cluster, & is responsible for consolidating
cluster state between t... | python | {
"resource": ""
} |
q28963 | ScalerThread.check | train | def check(self):
"""
Attempt to join any existing scaler threads that may have died or finished. This insures
any exceptions raised in the threads are propagated in a timely fashion.
"""
try:
| python | {
"resource": ""
} |
q28964 | ScalerThread.shutdown | train | def shutdown(self):
"""
Shutdown the cluster.
"""
self.stop = True
| python | {
"resource": ""
} |
q28965 | AbstractJobStore.initialize | train | def initialize(self, config):
"""
Create the physical storage for this job store, allocate a workflow ID and persist the
given Toil configuration to the store.
:param toil.common.Config config: the Toil configuration to initialize this job store
with. The given configurat... | python | {
"resource": ""
} |
q28966 | AbstractJobStore.setRootJob | train | def setRootJob(self, rootJobStoreID):
"""
Set the root job of the workflow backed by this job store
:param str rootJobStoreID: The ID of the job to set as root
| python | {
"resource": ""
} |
q28967 | AbstractJobStore.loadRootJob | train | def loadRootJob(self):
"""
Loads the root job in the current job store.
:raises toil.job.JobException: If no root job is set or if the root job doesn't exist in
this job store
:return: The root job.
:rtype: toil.jobGraph.JobGraph
"""
try:
... | python | {
"resource": ""
} |
q28968 | AbstractJobStore.createRootJob | train | def createRootJob(self, *args, **kwargs):
"""
Create a new job and set it as the root job in this job store
| python | {
"resource": ""
} |
q28969 | AbstractJobStore._jobStoreClasses | train | def _jobStoreClasses(self):
"""
A list of concrete AbstractJobStore implementations whose dependencies are installed.
:rtype: list[AbstractJobStore]
"""
jobStoreClassNames = (
"toil.jobStores.azureJobStore.AzureJobStore",
"toil.jobStores.fileJobStore.File... | python | {
"resource": ""
} |
q28970 | AbstractJobStore._findJobStoreForUrl | train | def _findJobStoreForUrl(self, url, export=False):
"""
Returns the AbstractJobStore subclass that supports the given URL.
:param urlparse.ParseResult url: The given URL
:param bool export: The URL for
:rtype: toil.jobStore.AbstractJobStore
"""
for jobStoreCls in s... | python | {
"resource": ""
} |
q28971 | AbstractJobStore.importFile | train | def importFile(self, srcUrl, sharedFileName=None, hardlink=False):
"""
Imports the file at the given URL into job store. The ID of the newly imported file is
returned. If the name of a shared file name is provided, the file will be imported as
such and None is returned.
Currentl... | python | {
"resource": ""
} |
q28972 | AbstractJobStore._exportFile | train | def _exportFile(self, otherCls, jobStoreFileID, url):
"""
Refer to exportFile docstring for information about this method.
:param AbstractJobStore otherCls: The concrete subclass of AbstractJobStore that supports
exporting to the given URL. Note that the type annotation here is n... | python | {
"resource": ""
} |
q28973 | parseStorage | train | def parseStorage(storageData):
"""
Parses EC2 JSON storage param string into a number.
Examples:
"2 x 160 SSD"
"3 x 2000 HDD"
"EBS only"
"1 x 410"
"8 x 1.9 NVMe SSD"
:param str storageData: EC2 JSON storage param string.
:return: Two floats representing: (# ... | python | {
"resource": ""
} |
q28974 | parseMemory | train | def parseMemory(memAttribute):
"""
Returns EC2 'memory' string as a float.
Format should always be '#' GiB (example: '244 GiB' or '1,952 GiB').
Amazon loves to put commas in their numbers, so we have to accommodate that.
If the syntax ever changes, this will raise.
:param memAttribute: EC2 JSO... | python | {
"resource": ""
} |
q28975 | fetchEC2InstanceDict | train | def fetchEC2InstanceDict(regionNickname=None):
"""
Fetches EC2 instances types by region programmatically using the AWS pricing API.
See: https://aws.amazon.com/blogs/aws/new-aws-price-list-api/
:return: A dict of InstanceType objects, where the key is the string:
aws instance name (examp... | python | {
"resource": ""
} |
q28976 | parseEC2Json2List | train | def parseEC2Json2List(jsontext, region):
"""
Takes a JSON and returns a list of InstanceType objects representing EC2 instance params.
:param jsontext:
:param region:
:return:
"""
currentList = json.loads(jsontext)
ec2InstanceList = []
for k, v in iteritems(currentList["products"]):... | python | {
"resource": ""
} |
q28977 | updateStaticEC2Instances | train | def updateStaticEC2Instances():
"""
Generates a new python file of fetchable EC2 Instances by region with current prices and specs.
Takes a few (~3+) minutes to run (you'll need decent internet).
:return: Nothing. Writes a new 'generatedEC2Lists.py' file.
"""
logger.info("Updating Toil's EC2 ... | python | {
"resource": ""
} |
q28978 | SingleMachineBatchSystem._runWorker | train | def _runWorker(self, jobCommand, jobID, environment):
"""
Run the jobCommand using the worker and wait for it to finish.
The worker is forked unless it is a '_toil_worker' job and
debugWorker is True.
"""
startTime = time.time() # Time job is started
if self.debu... | python | {
"resource": ""
} |
q28979 | SingleMachineBatchSystem.issueBatchJob | train | def issueBatchJob(self, jobNode):
"""Adds the command and resources to a queue to be run."""
# Round cores to minCores and apply scale
cores = math.ceil(jobNode.cores * self.scale / self.minCores) * self.minCores
assert cores <= self.maxCores, ('The job {} is requesting {} cores, more th... | python | {
"resource": ""
} |
q28980 | SingleMachineBatchSystem.killBatchJobs | train | def killBatchJobs(self, jobIDs):
"""Kills jobs by ID."""
log.debug('Killing jobs: {}'.format(jobIDs))
for jobID in jobIDs:
if jobID in self.runningJobs:
info = self.runningJobs[jobID]
info.killIntended = True
if info.popen != None:
... | python | {
"resource": ""
} |
q28981 | SingleMachineBatchSystem.shutdown | train | def shutdown(self):
"""
Cleanly terminate worker threads. Add sentinels to inputQueue equal to maxThreads. Join
all worker threads.
"""
# Remove reference to inputQueue (raises exception if inputQueue is used after method call)
inputQueue = self.inputQueue
self.in... | python | {
"resource": ""
} |
q28982 | SingleMachineBatchSystem.getUpdatedBatchJob | train | def getUpdatedBatchJob(self, maxWait):
"""Returns a map of the run jobs and the return value of their processes."""
try:
item = self.outputQueue.get(timeout=maxWait)
except Empty:
return None
jobID, exitValue, wallTime = | python | {
"resource": ""
} |
q28983 | MesosExecutor.registered | train | def registered(self, driver, executorInfo, frameworkInfo, agentInfo):
"""
Invoked once the executor driver has been able to successfully connect with Mesos.
"""
# Get the ID we have been assigned, if we have it
self.id = executorInfo.executor_id.get('value', None)
... | python | {
"resource": ""
} |
q28984 | MesosExecutor.killTask | train | def killTask(self, driver, taskId):
"""
Kill parent task process and all its spawned children
"""
try:
pid = self.runningTasks[taskId]
pgid = os.getpgid(pid)
| python | {
"resource": ""
} |
q28985 | retry | train | def retry( delays=(0, 1, 1, 4, 16, 64), timeout=300, predicate=never ):
"""
Retry an operation while the failure matches a given predicate and until a given timeout
expires, waiting a given amount of time in between attempts. This function is a generator
that yields contextmanagers. See doctests below f... | python | {
"resource": ""
} |
q28986 | retryable_http_error | train | def retryable_http_error( e ):
"""
Determine if an error encountered during an HTTP download is likely to go away if we try again.
"""
if isinstance( e, urllib.error.HTTPError ) and e.code in ('503', '408', '500'):
# The server returned one of:
# 503 Service Unavailable
| python | {
"resource": ""
} |
q28987 | AbstractGridEngineBatchSystem.getRunningBatchJobIDs | train | def getRunningBatchJobIDs(self):
"""
Retrieve running job IDs from local and batch scheduler.
Respects statePollingWait and will return cached results if not within
time period to talk with the scheduler.
"""
if (self._getRunningBatchJobIDsTimestamp and (
... | python | {
"resource": ""
} |
q28988 | GaussianMultivariate.get_lower_bound | train | def get_lower_bound(self):
"""Compute the lower bound to integrate cumulative density.
Returns:
float: lower bound for cumulative density integral.
"""
lower_bounds = []
for distribution in self.distribs.values():
lower_bound | python | {
"resource": ""
} |
q28989 | GaussianMultivariate.get_column_names | train | def get_column_names(self, X):
"""Return iterable containing columns for the given array X.
Args:
X: `numpy.ndarray` or `pandas.DataFrame`.
Returns:
iterable: columns for the given matrix.
| python | {
"resource": ""
} |
q28990 | GaussianMultivariate.get_column | train | def get_column(self, X, column):
"""Return a column of the given matrix.
Args:
X: `numpy.ndarray` or `pandas.DataFrame`.
column: `int` or `str`.
Returns:
| python | {
"resource": ""
} |
q28991 | GaussianMultivariate.set_column | train | def set_column(self, X, column, value):
"""Sets a column on the matrix X with the given value.
Args:
X: `numpy.ndarray` or `pandas.DataFrame`.
column: `int` or `str`.
value: `np.ndarray` with shape (1,)
Returns:
| python | {
"resource": ""
} |
q28992 | GaussianMultivariate._get_covariance | train | def _get_covariance(self, X):
"""Compute covariance matrix with transformed data.
Args:
X: `numpy.ndarray` or `pandas.DataFrame`.
Returns:
np.ndarray
"""
result = pd.DataFrame(index=range(len(X)))
column_names = self.get_column_names(X)
... | python | {
"resource": ""
} |
q28993 | GaussianMultivariate.fit | train | def fit(self, X):
"""Compute the distribution for each variable and then its covariance matrix.
Args:
X(numpy.ndarray or pandas.DataFrame): Data to model.
Returns:
None
"""
LOGGER.debug('Fitting Gaussian Copula')
column_names = self.get_column_na... | python | {
"resource": ""
} |
q28994 | GaussianMultivariate.cumulative_distribution | train | def cumulative_distribution(self, X):
"""Computes the cumulative distribution function for the copula
Args:
X: `numpy.ndarray` or `pandas.DataFrame`
Returns:
np.array: cumulative probability
"""
| python | {
"resource": ""
} |
q28995 | GaussianMultivariate.sample | train | def sample(self, num_rows=1):
"""Creates sintentic values stadistically similar to the original dataset.
Args:
num_rows: `int` amount of samples to generate.
Returns:
np.ndarray: Sampled data.
"""
self.check_fit()
res = {}
means = np.ze... | python | {
"resource": ""
} |
q28996 | GaussianUnivariate.probability_density | train | def probability_density(self, X):
"""Compute probability density.
Arguments:
X: `np.ndarray` of shape (n, 1).
Returns:
np.ndarray
""" | python | {
"resource": ""
} |
q28997 | GaussianUnivariate.cumulative_distribution | train | def cumulative_distribution(self, X):
"""Cumulative distribution function for gaussian distribution.
Arguments:
X: `np.ndarray` of shape (n, 1).
Returns:
np.ndarray: Cumulative | python | {
"resource": ""
} |
q28998 | GaussianUnivariate.percent_point | train | def percent_point(self, U):
"""Given a cumulated distribution value, returns a value in original space.
Arguments:
U: `np.ndarray` of shape | python | {
"resource": ""
} |
q28999 | GaussianUnivariate.sample | train | def sample(self, num_samples=1):
"""Returns new data point based on model.
Arguments:
n_samples: `int`
Returns:
np.ndarray: Generated samples
"""
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.