_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q52500
Driver.freeze_all
train
def freeze_all(self): ''' Stop all activity of the agents running. ''' d = defer.succeed(None) for x in self.iter_agents(): d.addCallback(defer.drop_param, x._cancel_long_running_protocols) d.addCallback(defer.drop_param, x._cancel_all_delayed_calls) ...
python
{ "resource": "" }
q52501
Driver.destroy
train
def destroy(self): ''' Called from tearDown of simulation tests. Cleans up everything. ''' defers = list() for x in self.iter_agents(): defers.append(x.terminate_hard()) yield defer.DeferredList(defers) yield self._journaler.close() del(self._j...
python
{ "resource": "" }
q52502
getLevelName
train
def getLevelName(level): """ Return the name of a log level. @param level: The level we want to know the name @type level: int @return: The name of the level @rtype: str """ assert isinstance(level, int) and level > 0 and level < 6, \ TypeError("Bad debug level") return ge...
python
{ "resource": "" }
q52503
getLevelInt
train
def getLevelInt(levelName): """ Return the integer value of the levelName. @param levelName: The string value of the level name @type levelName: str @return: The value of the level name we are interested in. @rtype: int """ assert isinstance(levelName, str) and levelName in getLevelNames...
python
{ "resource": "" }
q52504
registerCategory
train
def registerCategory(category): """ Register a given category in the debug system. A level will be assigned to it based on previous calls to setDebug. """ # parse what level it is set to based on _DEBUG # example: *:2,admin:4 global _DEBUG global _levels global _categories level...
python
{ "resource": "" }
q52505
setLogSettings
train
def setLogSettings(state): """Update the current log settings. This can restore an old saved log settings object returned by getLogSettings @param state: the settings to set """ global _DEBUG global _log_handlers global _log_handlers_limited (_DEBUG, categories, _log_hand...
python
{ "resource": "" }
q52506
scrubFilename
train
def scrubFilename(filename): ''' Scrub the filename to a relative path for all packages in our scrub list. ''' global _PACKAGE_SCRUB_LIST for package in _PACKAGE_SCRUB_LIST: i = filename.rfind(package) if i > -1: return filename[i:] return filename
python
{ "resource": "" }
q52507
getFileLine
train
def getFileLine(where=-1, targetModule=None): """ Return the filename and line number for the given location. If where is a negative integer, look for the code entry in the current stack that is the given number of frames above this module. If where is a function, look for the code entry of the fun...
python
{ "resource": "" }
q52508
ellipsize
train
def ellipsize(o): """ Ellipsize the representation of the given object. """ r = repr(o) if len(r) < 800: return r r = r[:60] + ' ... ' + r[-15:] return r
python
{ "resource": "" }
q52509
getFormatArgs
train
def getFormatArgs(startFormat, startArgs, endFormat, endArgs, args, kwargs): """ Helper function to create a format and args to use for logging. This avoids needlessly interpolating variables. """ debugArgs = startArgs[:] for a in args: debugArgs.append(ellipsize(a)) for items in kw...
python
{ "resource": "" }
q52510
warningObject
train
def warningObject(object, cat, format, *args): """ Log a warning message in the given category. This is used for non-fatal problems. """ doLog(WARN, object, cat, format, args)
python
{ "resource": "" }
q52511
infoObject
train
def infoObject(object, cat, format, *args): """ Log an informational message in the given category. """ doLog(INFO, object, cat, format, args)
python
{ "resource": "" }
q52512
debugObject
train
def debugObject(object, cat, format, *args): """ Log a debug message in the given category. """ doLog(DEBUG, object, cat, format, args)
python
{ "resource": "" }
q52513
safeprintf
train
def safeprintf(file, format, *args): """Write to a file object, ignoring errors. """ try: if args: file.write(format % args) else: file.write(format) except IOError, e: if e.errno == errno.EPIPE: # if our output is closed, exit; e.g. when loggi...
python
{ "resource": "" }
q52514
stderrHandler
train
def stderrHandler(level, object, category, file, line, message): """ A log handler that writes to stderr. @type level: string @type object: string (or None) @type category: string @type message: string """ o = "" if object: o = '"' + object + '"' where = "(%s:%d)...
python
{ "resource": "" }
q52515
init
train
def init(envVarName, enableColorOutput=False): """ Initialize the logging system and parse the environment variable of the given name. Needs to be called before starting the actual application. """ global _initialized if _initialized: return global _ENV_VAR_NAME _ENV_VAR_NA...
python
{ "resource": "" }
q52516
setDebug
train
def setDebug(string): """Set the DEBUG string. This controls the log output.""" global _DEBUG global _ENV_VAR_NAME global _categories _DEBUG = string debug('log', "%s set to %s" % (_ENV_VAR_NAME, _DEBUG)) # reparse all already registered category levels for category in _categories: ...
python
{ "resource": "" }
q52517
getExceptionMessage
train
def getExceptionMessage(exception, frame=-1, filename=None): """ Return a short message based on an exception, useful for debugging. Tries to find where the exception was triggered. """ stack = traceback.extract_tb(sys.exc_info()[2]) if filename: stack = [f for f in stack if f[0].find(fi...
python
{ "resource": "" }
q52518
outputToFiles
train
def outputToFiles(stdout=None, stderr=None): """ Redirect stdout and stderr to named files. Records the file names so that a future call to reopenOutputFiles() can open the same files. Installs a SIGHUP handler that will reopen the output files. Note that stderr is opened unbuffered, so if it ...
python
{ "resource": "" }
q52519
logTwisted
train
def logTwisted(): """ Integrate twisted's logger with our logger. This is done in a separate method because calling this imports and sets up a reactor. Since we want basic logging working before choosing a reactor, we need to separate these. """ global _initializedTwisted if _initiali...
python
{ "resource": "" }
q52520
adaptStandardLogging
train
def adaptStandardLogging(loggerName, logCategory, targetModule): """ Make a logger from the standard library log through the Flumotion logging system. @param loggerName: The standard logger to adapt, e.g. 'library.module' @type loggerName: str @param logCategory: The Flumotion log category to u...
python
{ "resource": "" }
q52521
Loggable.writeMarker
train
def writeMarker(self, marker, level): """ Sets a marker that written to the logs. Setting this marker to multiple elements at a time helps debugging. @param marker: A string write to the log. @type marker: str @param level: The log level. It can be log.WARN, log.INFO, ...
python
{ "resource": "" }
q52522
Loggable.error
train
def error(self, *args): """Log an error. By default this will also raise an exception.""" if _canShortcutLogging(self.logCategory, ERROR): return errorObject(self.logObjectName(), self.logCategory, *self.logFunction(*args))
python
{ "resource": "" }
q52523
Loggable.warning
train
def warning(self, *args): """Log a warning. Used for non-fatal problems.""" if _canShortcutLogging(self.logCategory, WARN): return warningObject(self.logObjectName(), self.logCategory, *self.logFunction(*args))
python
{ "resource": "" }
q52524
Loggable.info
train
def info(self, *args): """Log an informational message. Used for normal operation.""" if _canShortcutLogging(self.logCategory, INFO): return infoObject(self.logObjectName(), self.logCategory, *self.logFunction(*args))
python
{ "resource": "" }
q52525
Loggable.debug
train
def debug(self, *args): """Log a debug message. Used for debugging.""" if _canShortcutLogging(self.logCategory, DEBUG): return debugObject(self.logObjectName(), self.logCategory, *self.logFunction(*args))
python
{ "resource": "" }
q52526
Loggable.doLog
train
def doLog(self, level, where, format, *args, **kwargs): """ Log a message at the given level, with the possibility of going higher up in the stack. @param level: log level @type level: int @param where: how many frames to go back from the last log frame; ...
python
{ "resource": "" }
q52527
json_exception
train
def json_exception(context, request): """Always return json content in the body of Exceptions to xhr requests.""" request.response.status = context.code return {'error': context._status, 'messages': context.message}
python
{ "resource": "" }
q52528
Checktext.load_common
train
def load_common(self, wlist): """Create the dictionary of common words.""" self.com_dict = os.path.join(self.base_dir, 'dicts', 'EN_vocab.txt') with open(self.com_dict) as words_file: data = words_file.read() self.common_words = set(data.splitlines()) if wlist: ...
python
{ "resource": "" }
q52529
Checktext.load_dale_chall
train
def load_dale_chall(self): """Create the dictionary of words, and grade dictionary, for the Dale-Chall readability test.""" self.dale_chall_dict = os.path.join(self.base_dir, 'dicts', 'dale_chall.txt') with open(self.dale_chall_dict) as words_file: data = words_file.read() se...
python
{ "resource": "" }
q52530
Checktext.pre_check
train
def pre_check(self, data): """Count chars, words and sentences in the text.""" sentences = len(re.findall('[\.!?]+\W+', data)) or 1 chars = len(data) - len(re.findall('[^a-zA-Z0-9]', data)) num_words = len(re.findall('\s+', data)) data = re.split('[^a-zA-Z]+', data) retur...
python
{ "resource": "" }
q52531
Checktext.run_check
train
def run_check(self, data): """Check for uncommon words and difficult words in file.""" if not data: sys.exit(1) data, sentences, chars, num_words = self.pre_check(data) w_dict = Counter(data) uniq_len, uncommon, uncom_len = self.gsl(w_dict) non_dchall_set = Co...
python
{ "resource": "" }
q52532
Checktext.dale_chall
train
def dale_chall(self, diff_count, words, sentences): """Calculate Dale-Chall readability score.""" pdw = diff_count / words * 100 asl = words / sentences raw = 0.1579 * (pdw) + 0.0496 * asl if pdw > 5: return raw + 3.6365 return raw
python
{ "resource": "" }
q52533
format_config
train
def format_config(data, env): """ Format data with given env. :param data: a string/integer/float/boolean/list/dict object. :param env: a dictionary. :return: return formatted data. `format_config` will try to format strings contained env placeholder `{{ ENV_KEY }}`. If `ENV_KEY` does not...
python
{ "resource": "" }
q52534
Report.create
train
def create(cls, scheduled_analysis, tags=None, json_report_objects=None, raw_report_objects=None, additional_metadata=None, analysis_date=None): """ Create a new report. For convenience :func:`~mass_api_client.resources.scheduled_analysis.ScheduledAnalysis.create_report` of class :class...
python
{ "resource": "" }
q52535
Report.get_json_report_object
train
def get_json_report_object(self, key): """ Retrieve a JSON report object of the report. :param key: The key of the report object :return: The deserialized JSON report object. """ con = ConnectionManager().get_connection(self._connection_alias) return con.get_json...
python
{ "resource": "" }
q52536
Report.download_raw_report_object_to_file
train
def download_raw_report_object_to_file(self, key, file): """ Download a raw report object and store it in a file. :param key: The key of the report object :param file: A file-like object to store the report object. """ con = ConnectionManager().get_connection(self._conne...
python
{ "resource": "" }
q52537
find_dependencies
train
def find_dependencies(module, depth=0, deps=None, seen=None, max_depth=99): """ Finds all objects a module depends on up to a certain depth truncating cyclic dependencies at the first instance :param module: The module to find dependencies of :type module: types.ModuleType :param depth: The current...
python
{ "resource": "" }
q52538
find_modules_importing
train
def find_modules_importing(dot_path, starting_with): """ Finds all the modules importing a particular attribute of a module pointed to by dot_path that starting_with is dependent on. :param dot_path: The dot path to the object of interest :type dot_path: str :param starting_with: The module from wh...
python
{ "resource": "" }
q52539
execute_side_effect
train
def execute_side_effect(side_effect=UNDEFINED, args=UNDEFINED, kwargs=UNDEFINED): """ Executes a side effect if one is defined. :param side_effect: The side effect to execute :type side_effect: Mixed. If it's an exception it's raised. If it's callable it's called with teh parameters. :param tuple a...
python
{ "resource": "" }
q52540
get_replacement_method
train
def get_replacement_method(method_to_patch, side_effect=UNDEFINED, rvalue=UNDEFINED, ignore=UNDEFINED, callback=UNDEFINED, context=UNDEFINED, subsequent_rvalue=UNDEFINED): """ Returns the method to be applied in place of an original method. This method either executes a side effect, returns an rvalue, or implem...
python
{ "resource": "" }
q52541
get_context
train
def get_context(method): """ Gets a context for a target function. :rtype: caliendo.hooks.Context :returns: The context for the call. Patches are applied and removed within a context. """ if Context.exists(method): return Context.increment(method) else: return Context(method...
python
{ "resource": "" }
q52542
patch
train
def patch(import_path, rvalue=UNDEFINED, side_effect=UNDEFINED, ignore=UNDEFINED, callback=UNDEFINED, ctxt=UNDEFINED, subsequent_rvalue=UNDEFINED): """ Patches an attribute of a module referenced on import_path with a decorated version that will use the caliendo cache if rvalue is None. Otherwise it will ...
python
{ "resource": "" }
q52543
get_recorder
train
def get_recorder(import_path, ctxt): """ Gets a recorder for a particular target given a particular context :param str import_path: The import path of the method to record :param caliendo.hooks.Context ctxt: The context to record :rtype: function :returns: A method that acts like the target, b...
python
{ "resource": "" }
q52544
MapSockClient.send
train
def send(self, request): """ Send request to server and return server response. """ self._logger.debug('Opening connection') sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.connect((self._hos...
python
{ "resource": "" }
q52545
MapSockServer._send
train
def _send(self, message): """ Return response message to client. """ result = self._talk.put(message) if not result: self._logger.error('Failed to send "%s"' % message) return result
python
{ "resource": "" }
q52546
MapSockServer._receive
train
def _receive(self): """ Receive a chunk of request from client. """ result = self._talk.get() if not result: self._logger.error('Failed to receive') return result
python
{ "resource": "" }
q52547
MapSockServer.run
train
def run(self): """ Continuously retrieve client requests until given "stop" request. """ while True: self._logger.debug('Accepting connection') conn, addr = self._sock.accept() self._talk = SocketTalk(conn, encode=self._encode) self._logge...
python
{ "resource": "" }
q52548
DataPort.parse_xml_node
train
def parse_xml_node(self, node): '''Parse an xml.dom Node object representing a data port into this object. ''' self.name = node.getAttributeNS(RTS_NS, 'name') self.comment = node.getAttributeNS(RTS_EXT_NS, 'comment') if node.hasAttributeNS(RTS_EXT_NS, 'visible'): ...
python
{ "resource": "" }
q52549
DataPort.parse_yaml
train
def parse_yaml(self, y): '''Parse a YAML specification of a data port into this object.''' self.name = y['name'] if RTS_EXT_NS_YAML + 'comment' in y: self.comment = y[RTS_EXT_NS_YAML + 'comment'] if RTS_EXT_NS_YAML + 'visible' in y: visible = y.get(RTS_EXT_NS_YAML...
python
{ "resource": "" }
q52550
ServicePort.to_dict
train
def to_dict(self): '''Save this service port into a dictionary.''' d = {'name': self.name} if self.visible != True: d[RTS_EXT_NS_YAML + 'visible'] = self.visible if self.comment: d[RTS_EXT_NS_YAML + 'comment'] = self.comment props = [] for name in ...
python
{ "resource": "" }
q52551
emit_event
train
def emit_event(project_slug, action_slug, payload, sender_name, sender_secret, event_uuid=None): """Emit Event. :param project_slug: the slug of the project :param action_slug: the slug of the action :param payload: the payload that emit with action :param sender_name: name that iden...
python
{ "resource": "" }
q52552
EntryMixin.get_ordered_entries
train
def get_ordered_entries(self, queryset=False): """ Custom ordering. First we get the average views and rating for the categories's entries. Second we created a rank by multiplying both. Last, we sort categories by this rank from top to bottom. Example: - Cat_1 ...
python
{ "resource": "" }
q52553
EntryCategoryListView.get_queryset
train
def get_queryset(self): """ Customized to get the ordered categories and entries from the Mixin. """ self.queryset = super(EntryCategoryListView, self).get_queryset() return self.get_ordered_entries(self.queryset)
python
{ "resource": "" }
q52554
to_string
train
def to_string(direction): '''Returns the correct string for a given direction. @raises InvalidDirectionError ''' if direction == UP: return UP elif direction == DOWN: return DOWN elif direction == LEFT: return LEFT elif direction == RIGHT: return RIGHT e...
python
{ "resource": "" }
q52555
start_in_oneshot_processes
train
def start_in_oneshot_processes(obj, nb_process): """ Start nb_process processes to do the job. Then process finish the job they die. """ processes = [] for i in range(nb_process): # Simple process style p = Process(target=oneshot_in_process, args=(obj,)) p.start() pr...
python
{ "resource": "" }
q52556
start_in_keepedalive_processes
train
def start_in_keepedalive_processes(obj, nb_process): """ Start nb_process and keep them alive. Send job to them multiple times, then close thems. """ processes = [] readers_pipes = [] writers_pipes = [] for i in range(nb_process): # Start process with Pipes for communicate lo...
python
{ "resource": "" }
q52557
run_keepedalive_process
train
def run_keepedalive_process(main_write_pipe, process_read_pipe, obj): """ Procees who don't finish while job to do """ while obj != 'stop': oneshot_in_process(obj) # Send to main process "I've done my job" main_write_pipe.send('job is done') # Wait for new job to do (this...
python
{ "resource": "" }
q52558
API.parse_devices
train
def parse_devices(self, json): """Parse result from API.""" result = [] for json_device in json: license_plate = json_device['EquipmentHeader']['SerialNumber'] device = Device(self, license_plate) device.update_from_json(json_device) result.appen...
python
{ "resource": "" }
q52559
RepositoryConfig.fill
train
def fill(self, config, section): """Fill data from a given configuration section. Args: config (configparser): the configuration file section (str): the section to use """ if config.has_section(section): default_url = self.DEFAULT_REPOSITORIES.get(sel...
python
{ "resource": "" }
q52560
RepositoryConfig.needs_auth
train
def needs_auth(self): """Whether this repository needs authentication.""" return self.username or self.password or (self.url and self.url.needs_auth)
python
{ "resource": "" }
q52561
PyPIConfig.get_repo_config
train
def get_repo_config(self, repo='default'): """Retrieve configuration for a given repository. Args: repo (str): a repository "realm" (alias) or its URL Returns: RepositoryConfig: if there is configuration for that repository None: otherwise """ ...
python
{ "resource": "" }
q52562
_get_template_dirs
train
def _get_template_dirs(type="plugin"): """Return a list of directories where templates may be located. """ template_dirs = [ os.path.expanduser(os.path.join(USER_CONFIG_DIR, "templates", type)), os.path.join("rapport", "templates", type) # Local dev tree ] return template_dirs
python
{ "resource": "" }
q52563
subn_filter
train
def subn_filter(s, find, replace, count=0): """A non-optimal implementation of a regex filter""" return re.gsub(find, replace, count, s)
python
{ "resource": "" }
q52564
LiffyLights._gen_header
train
def _gen_header(self, sequence, payloadtype): """ Create packet header. """ protocol = bytearray.fromhex("00 34") source = bytearray.fromhex("42 52 4b 52") target = bytearray.fromhex("00 00 00 00 00 00 00 00") reserved1 = bytearray.fromhex("00 00 00 00 00 00") sequence = ...
python
{ "resource": "" }
q52565
LiffyLights._gen_packet
train
def _gen_packet(self, sequence, payloadtype, payload=None): """ Generate packet header. """ contents = self._gen_header(sequence, payloadtype) # add payload if payload: contents.extend(payload) # get packet size size = pack("<H", len(contents) + 2) ...
python
{ "resource": "" }
q52566
LiffyLights._gen_packet_setcolor
train
def _gen_packet_setcolor(self, sequence, hue, sat, bri, kel, fade): """ Generate "setcolor" packet payload. """ hue = min(max(hue, HUE_MIN), HUE_MAX) sat = min(max(sat, SATURATION_MIN), SATURATION_MAX) bri = min(max(bri, BRIGHTNESS_MIN), BRIGHTNESS_MAX) kel = min(max(kel, TEMP_MI...
python
{ "resource": "" }
q52567
LiffyLights._gen_packet_setpower
train
def _gen_packet_setpower(self, sequence, power, fade): """ Generate "setpower" packet payload. """ level = pack("<H", Power.BULB_OFF if power == 0 else Power.BULB_ON) duration = pack("<I", fade) # assemble payload payload = bytearray(level) payload.extend(duration) ...
python
{ "resource": "" }
q52568
LiffyLights._packet_ack
train
def _packet_ack(self, packet, sequence): """ Check packet for ack. """ if packet["sequence"] == sequence: if packet["payloadtype"] == PayloadType.SETCOLOR: # notify about colour change self._color_callback(packet["target"], ...
python
{ "resource": "" }
q52569
LiffyLights._process_packet
train
def _process_packet(self, sequence): """ Check packet list for acks. """ if self._packets: with self._packet_lock: self._packets[:] = [packet for packet in self._packets if self._packet_ack(packet, sequence)]
python
{ "resource": "" }
q52570
LiffyLights._packet_timeout
train
def _packet_timeout(self, packet, now): """ Check packet for timeout. """ if now >= packet["timeout"]: # timed out return False if now >= packet["resend"]: # resend command self._send_command(packet) return False # keep packet...
python
{ "resource": "" }
q52571
LiffyLights._packet_manager
train
def _packet_manager(self): """ Watch packet list for timeouts. """ while True: if self._packets: with self._packet_lock: now = time.time() self._packets[:] = \ [packet for packet in self._packets ...
python
{ "resource": "" }
q52572
LiffyLights._packet_listener
train
def _packet_listener(self): """ Packet listener. """ while True: datastream, source = self._sock.recvfrom(BUFFERSIZE) ipaddr, port = source # mitigate against invalid packets try: sio = io.BytesIO(datastream) dummy1, sec_...
python
{ "resource": "" }
q52573
LiffyLights._command_sender
train
def _command_sender(self): """ Command sender. """ sequence = -1 while True: cmd = self._queue.get() ipaddr = cmd["target"] payloadtype = cmd["payloadtype"] if "sequence" not in cmd: # get next sequence number if we haven't got o...
python
{ "resource": "" }
q52574
LiffyLights.probe
train
def probe(self, ipaddr=None): """ Probe given address for bulb. """ if ipaddr is None: # no address so use broadcast ipaddr = self._broadcast_addr cmd = {"payloadtype": PayloadType.GET, "target": ipaddr} self._send_command(cmd)
python
{ "resource": "" }
q52575
LiffyLights.set_power
train
def set_power(self, ipaddr, power, fade): """ Send SETPOWER message. """ cmd = {"payloadtype": PayloadType.SETPOWER2, "target": ipaddr, "power": power, "fade": fade} self._send_command(cmd)
python
{ "resource": "" }
q52576
LiffyLights.set_color
train
def set_color(self, ipaddr, hue, sat, bri, kel, fade): """ Send SETCOLOR message. """ cmd = {"payloadtype": PayloadType.SETCOLOR, "target": ipaddr, "hue": hue, "sat": sat, "bri": bri, "kel": kel, "fade": fade} ...
python
{ "resource": "" }
q52577
Scenes.create_scene
train
async def create_scene(self, room_id, name, color_id=0, icon_id=0): """Creates am empty scene. Scenemembers need to be added after the scene has been created. :returns: A json object including scene id. """ name = unicode_to_base64(name) _data = { "scene": {...
python
{ "resource": "" }
q52578
push
train
def push(item, remote_addr, trg_queue, protocol=u'jsonrpc'): ''' Enqueue an FSQWorkItem at a remote queue ''' if protocol == u'jsonrpc': try: server = Server(remote_addr, encoding=_c.FSQ_CHARSET) return server.enqueue(item.id, trg_queue, item.item.read()) except Exception...
python
{ "resource": "" }
q52579
remote_trigger_pull
train
def remote_trigger_pull(remote_addr, trg_queue, ignore_listener=False, protocol=u'jsonrpc'): '''Write a non-blocking byte to a remote trigger fifo, to cause a triggered scan''' if protocol == u'jsonrpc': try: server = Server(remote_addr, encoding=_c.FSQ_CHARSET...
python
{ "resource": "" }
q52580
DNSServerFactory.gotResolverError
train
def gotResolverError(self, failure, protocol, message, address): ''' Copied from twisted.names. Removes logging the whole failure traceback. ''' if failure.check(dns.DomainError, dns.AuthoritativeDomainError): message.rCode = dns.ENAME else: messag...
python
{ "resource": "" }
q52581
DNSServerFactory.handleQuery
train
def handleQuery(self, message, protocol, address): """ Copied from twisted.names. Adds passing the address to resolver's query method. """ query = message.queries[0] d = self.resolver.query(query, address) d.addCallback(self.gotResolverResponse, protocol, message,...
python
{ "resource": "" }
q52582
BaseAgent.substitute_partner
train
def substitute_partner(self, state, partners_recp, recp, alloc_id): ''' Establish the partnership to recp and, when it is successfull remove partner with recipient partners_recp. Use with caution: The partner which we are removing is not notified in any way, so he still keeps li...
python
{ "resource": "" }
q52583
BaseAgent.breakup
train
def breakup(self, state, recp): '''Order the agent to break the partnership with the given recipient''' recp = recipient.IRecipient(recp) partner = self.find_partner(recp) if partner: return state.partners.breakup(partner) else: self.warning('We we...
python
{ "resource": "" }
q52584
get_pid
train
def get_pid(rundir, process_type=PROCESS_TYPE, name=None): """ Get the pid from the pid file in the run directory, using the given process type and process name for the filename. @returns: pid of the process, or None if not running or file not found. """ pidPath = get_pidpath(rundir, process_ty...
python
{ "resource": "" }
q52585
signal_pid
train
def signal_pid(pid, signum): """ Send the given process a signal. @returns: whether or not the process with the given pid was running """ try: os.kill(pid, signum) return True except OSError, e: # see man 2 kill if e.errno == errno.EPERM: # exists but...
python
{ "resource": "" }
q52586
get_pidpath
train
def get_pidpath(rundir, process_type, name=None): """ Get the full path to the pid file for the given process type and name. """ assert rundir, "rundir is not configured" path = os.path.join(rundir, '%s.pid' % process_type) if name: path = os.path.join(rundir, '%s.%s.pid' % (process_type...
python
{ "resource": "" }
q52587
_ensure_dir
train
def _ensure_dir(directory, description): """ Ensure the given directory exists, creating it if not. @raise errors.FatalError: if the directory could not be created. """ if not os.path.exists(directory): try: os.makedirs(directory) except OSError, e: sys.stder...
python
{ "resource": "" }
q52588
pipe
train
def pipe(maxsize=0, *, loop=None) -> Pipe: """\ A bidirectional pipe of Python objects. >>> async def example1(): ... a, b = pipe() ... a.send_nowait('foo') ... print(await b.recv()) >>> asyncio.run(example1()) foo >>> async def example2(): ... a, b = pipe() ...
python
{ "resource": "" }
q52589
Enforcer.recode
train
def recode(self, table: pd.DataFrame, validate=False) -> pd.DataFrame: """Return a fully recoded dataframe. Args: table (pd.DataFrame): A dataframe on which to apply recoding logic. validate (bool): If ``True``, recoded table must pass validation tests. """ df = ...
python
{ "resource": "" }
q52590
Column._dict_of_funcs
train
def _dict_of_funcs(self, funcs: list) -> pd.Series: """Return a pd.Series of functions with index derived from the function name.""" return {func.__name__: func for func in funcs}
python
{ "resource": "" }
q52591
Column._validate_series_dtype
train
def _validate_series_dtype(self, series: pd.Series) -> pd.Series: """Validate that the series data is the correct dtype.""" return series.apply(lambda i: isinstance(i, self.dtype))
python
{ "resource": "" }
q52592
Column.recode
train
def recode(self, table: pd.DataFrame, validate=False) -> pd.DataFrame: """Pass the provided series obj through each recoder function sequentially and return the final result. Args: table (pd.DataFrame): A dataframe on which to apply recoding logic. validate (bool): If ``True``, ...
python
{ "resource": "" }
q52593
get_available_currencies
train
def get_available_currencies(): """Return a list of all available Cryptonator currencies.""" r = requests.get(API_CURRENCIES) if r.status_code != requests.codes.ok: raise CryptonatorException( ("An error occurred while getting available currencies " "({} from Cryptonator).")...
python
{ "resource": "" }
q52594
analyzer_api
train
def analyzer_api(url): """ Analyze given `url` and return output as JSON. """ response.content_type = JSON_MIME # handle cacheing ri = get_cached_or_new(url) try: if ri.is_old(): logger.info("Running the analysis.") # forget the old one and create new requ...
python
{ "resource": "" }
q52595
_get_gs_path
train
def _get_gs_path(): """Guess where the Ghostscript executable is and return its absolute path name.""" path = os.environ.get("PATH", os.defpath) for dir in path.split(os.pathsep): for name in ("gs", "gs.exe", "gswin32c.exe"): g = os.path.join(dir, name) if os.path.exists...
python
{ "resource": "" }
q52596
init
train
def init(*, output_dir=FS_DEFAULT_OUTPUT_DIR, dry_run=False, **kwargs): """ Set up output directory :param output_dir(str, optional): Output dir for holding temporary files :param \*\*kwargs: arbitrary keyword arguments """ # Output directory global _output_dir _output_dir = output_dir ...
python
{ "resource": "" }
q52597
cleanup
train
def cleanup(): """Cleanup the output directory""" if _output_dir and os.path.exists(_output_dir): log.msg_warn("Cleaning up output directory at '{output_dir}' ..." .format(output_dir=_output_dir)) if not _dry_run: shutil.rmtree(_output_dir)
python
{ "resource": "" }
q52598
make_tmp_dir
train
def make_tmp_dir(prefix): """ Create a temporary directory :param prefix(str): Name prefix for the new directory :return: a string with the resulting name of new directory """ # Time in ISO8601 format now = datetime.now().isoformat() # A random UUID is appended to the output directory...
python
{ "resource": "" }
q52599
make_tarball
train
def make_tarball(src_dir): """ Make gzipped tarball from a source directory :param src_dir: source directory :raises TypeError: if src_dir is not str """ if type(src_dir) != str: raise TypeError('src_dir must be str') output_file = src_dir + ".tar.gz" log.msg("Wrapping tarball '...
python
{ "resource": "" }