INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Draw a path. | def draw_path(self, data, coordinates, pathcodes, style,
offset=None, offset_coordinates="data", mplobj=None):
"""
Draw a path.
In matplotlib, paths are created by filled regions, histograms,
contour plots, patches, etc.
Parameters
----------
d... |
Create a TimeMOC from a astropy. time. Time | def from_times(cls, times, delta_t=DEFAULT_OBSERVATION_TIME):
"""
Create a TimeMOC from a `astropy.time.Time`
Parameters
----------
times : `astropy.time.Time`
astropy observation times
delta_t : `astropy.time.TimeDelta`, optional
the duration of ... |
Create a TimeMOC from a range defined by two astropy. time. Time | def from_time_ranges(cls, min_times, max_times, delta_t=DEFAULT_OBSERVATION_TIME):
"""
Create a TimeMOC from a range defined by two `astropy.time.Time`
Parameters
----------
min_times : `astropy.time.Time`
astropy times defining the left part of the intervals
... |
Add all the pixels at max order in the neighbourhood of the moc | def add_neighbours(self):
"""
Add all the pixels at max order in the neighbourhood of the moc
"""
time_delta = 1 << (2*(IntervalSet.HPY_MAX_ORDER - self.max_order))
intervals_arr = self._interval_set._intervals
intervals_arr[:, 0] = np.maximum(intervals_arr[:, 0] - time... |
Remove all the pixels at max order located at the bound of the moc | def remove_neighbours(self):
"""
Remove all the pixels at max order located at the bound of the moc
"""
time_delta = 1 << (2*(IntervalSet.HPY_MAX_ORDER - self.max_order))
intervals_arr = self._interval_set._intervals
intervals_arr[:, 0] = np.minimum(intervals_arr[:, 0] ... |
Degrade ( down - sampling ) self and another_moc to order_op order | def _process_degradation(self, another_moc, order_op):
"""
Degrade (down-sampling) self and ``another_moc`` to ``order_op`` order
Parameters
----------
another_moc : `~mocpy.tmoc.TimeMoc`
order_op : int
the order in which self and ``another_moc`` will be down... |
Intersection between self and moc. delta_t gives the possibility to the user to set a time resolution for performing the tmoc intersection | def intersection(self, another_moc, delta_t=DEFAULT_OBSERVATION_TIME):
"""
Intersection between self and moc. ``delta_t`` gives the possibility to the user
to set a time resolution for performing the tmoc intersection
Parameters
----------
another_moc : `~mocpy.abstract_... |
Get the total duration covered by the temporal moc | def total_duration(self):
"""
Get the total duration covered by the temporal moc
Returns
-------
duration : `~astropy.time.TimeDelta`
total duration of all the observation times of the tmoc
total duration of all the observation times of the tmoc
... |
Get a percentage of fill between the min and max time the moc is defined. | def consistency(self):
"""
Get a percentage of fill between the min and max time the moc is defined.
A value near 0 shows a sparse temporal moc (i.e. the moc does not cover a lot
of time and covers very distant times. A value near 1 means that the moc covers
a lot of time withou... |
Get the ~astropy. time. Time time of the tmoc first observation | def min_time(self):
"""
Get the `~astropy.time.Time` time of the tmoc first observation
Returns
-------
min_time : `astropy.time.Time`
time of the first observation
"""
min_time = Time(self._interval_set.min / TimeMOC.DAY_MICRO_SEC, format='jd', sca... |
Get the ~astropy. time. Time time of the tmoc last observation | def max_time(self):
"""
Get the `~astropy.time.Time` time of the tmoc last observation
Returns
-------
max_time : `~astropy.time.Time`
time of the last observation
"""
max_time = Time(self._interval_set.max / TimeMOC.DAY_MICRO_SEC, format='jd', scal... |
Get a mask array ( e. g. a numpy boolean array ) of times being inside ( or outside ) the TMOC instance. | def contains(self, times, keep_inside=True, delta_t=DEFAULT_OBSERVATION_TIME):
"""
Get a mask array (e.g. a numpy boolean array) of times being inside (or outside) the
TMOC instance.
Parameters
----------
times : `astropy.time.Time`
astropy times to check whe... |
Plot the TimeMoc in a time window. | def plot(self, title='TimeMoc', view=(None, None)):
"""
Plot the TimeMoc in a time window.
This method uses interactive matplotlib. The user can move its mouse through the plot to see the
time (at the mouse position).
Parameters
----------
title : str, optional
... |
Handle a new update. | def handle(self, client, subhooks=()):
"""Handle a new update.
Fetches new data from the client, then compares it to the previous
lookup.
Returns:
(bool, new_data): whether changes occurred, and the new value.
"""
new_data = self.fetch(client)
# Hol... |
Convert text characters to VBO | def _text_to_vbo(text, font, anchor_x, anchor_y, lowres_size):
"""Convert text characters to VBO"""
# Necessary to flush commands before requesting current viewport because
# There may be a set_viewport command waiting in the queue.
# TODO: would be nicer if each canvas just remembers and manages its ow... |
Build and store a glyph corresponding to an individual character | def _load_char(self, char):
"""Build and store a glyph corresponding to an individual character
Parameters
----------
char : str
A single character to be represented.
"""
assert isinstance(char, string_types) and len(char) == 1
assert char not in self... |
Get a font described by face and size | def get_font(self, face, bold=False, italic=False):
"""Get a font described by face and size"""
key = '%s-%s-%s' % (face, bold, italic)
if key not in self._fonts:
font = dict(face=face, bold=bold, italic=italic)
self._fonts[key] = TextureFont(font, self._renderer)
... |
Compute the STFT | def stft(x, n_fft=1024, step=512, fs=2*np.pi, window='hann'):
"""Compute the STFT
Parameters
----------
x : array-like
1D signal to operate on. ``If len(x) < n_fft``, x will be zero-padded
to length ``n_fft``.
n_fft : int
Number of FFT points. Much faster for powers of two.
... |
Return frequencies for DFT | def fft_freqs(n_fft, fs):
"""Return frequencies for DFT
Parameters
----------
n_fft : int
Number of points in the FFT.
fs : float
The sampling rate.
"""
return np.arange(0, (n_fft // 2 + 1)) / float(n_fft) * float(fs) |
Set the data used for this visual | def set_data(self, pos=None, color=None, width=None, connect=None,
arrows=None):
"""Set the data used for this visual
Parameters
----------
pos : array
Array of shape (..., 2) or (..., 3) specifying vertex coordinates.
color : Color, tuple, or array
... |
Get rid of ugly twitter html | def strip_html(text):
""" Get rid of ugly twitter html """
def reply_to(text):
replying_to = []
split_text = text.split()
for index, token in enumerate(split_text):
if token.startswith('@'): replying_to.append(token[1:])
else:
message = split_text[... |
Helper function to post a tweet | def post_tweet(user_id, message, additional_params={}):
"""
Helper function to post a tweet
"""
url = "https://api.twitter.com/1.1/statuses/update.json"
params = { "status" : message }
params.update(additional_params)
r = make_twitter_request(url, user_id, params, request_type='POST')
... |
Generically make a request to twitter API using a particular user s authorization | def make_twitter_request(url, user_id, params={}, request_type='GET'):
""" Generically make a request to twitter API using a particular user's authorization """
if request_type == "GET":
return requests.get(url, auth=get_twitter_auth(user_id), params=params)
elif request_type == "POST":
retu... |
Search for a location - free form | def geo_search(user_id, search_location):
"""
Search for a location - free form
"""
url = "https://api.twitter.com/1.1/geo/search.json"
params = {"query" : search_location }
response = make_twitter_request(url, user_id, params).json()
return response |
Input - list of processed Tweets output - list of spoken responses | def read_out_tweets(processed_tweets, speech_convertor=None):
"""
Input - list of processed 'Tweets'
output - list of spoken responses
"""
return ["tweet number {num} by {user}. {text}.".format(num=index+1, user=user, text=text)
for index, (user, text) in enumerate(processed_tweets)] |
Search twitter API | def search_for_tweets_about(user_id, params):
""" Search twitter API """
url = "https://api.twitter.com/1.1/search/tweets.json"
response = make_twitter_request(url, user_id, params)
return process_tweets(response.json()["statuses"]) |
add value in form of dict | def add_val(self, val):
"""add value in form of dict"""
if not isinstance(val, type({})):
raise ValueError(type({}))
self.read()
self.config.update(val)
self.save() |
Read mesh data from file. | def read_mesh(fname):
"""Read mesh data from file.
Parameters
----------
fname : str
File name to read. Format will be inferred from the filename.
Currently only '.obj' and '.obj.gz' are supported.
Returns
-------
vertices : array
Vertices.
faces : array | None
... |
Write mesh data to file. | def write_mesh(fname, vertices, faces, normals, texcoords, name='',
format='obj', overwrite=False, reshape_faces=True):
""" Write mesh data to file.
Parameters
----------
fname : str
Filename to write. Must end with ".obj" or ".gz".
vertices : array
Vertices.
face... |
Set gl configuration | def _set_config(config):
"""Set gl configuration"""
pyglet_config = pyglet.gl.Config()
pyglet_config.red_size = config['red_size']
pyglet_config.green_size = config['green_size']
pyglet_config.blue_size = config['blue_size']
pyglet_config.alpha_size = config['alpha_size']
pyglet_config.acc... |
Set the vertex and fragment shaders. Parameters ---------- vert: str Source code for vertex shader. frag: str Source code for fragment shaders. | def set_shaders(self, vert, frag):
""" Set the vertex and fragment shaders.
Parameters
----------
vert : str
Source code for vertex shader.
frag : str
Source code for fragment shaders.
"""
if not vert or not frag:
raise... |
Parse uniforms attributes and varyings from the source code. | def _parse_variables_from_code(self):
""" Parse uniforms, attributes and varyings from the source code.
"""
# Get one string of code with comments removed
code = '\n\n'.join(self._shaders)
code = re.sub(r'(.*)(//.*)', r'\1', code, re.M)
# Regexp to look ... |
Bind a VertexBuffer that has structured data Parameters ---------- data: VertexBuffer The vertex buffer to bind. The field names of the array are mapped to attribute names in GLSL. | def bind(self, data):
""" Bind a VertexBuffer that has structured data
Parameters
----------
data : VertexBuffer
The vertex buffer to bind. The field names of the array
are mapped to attribute names in GLSL.
"""
# Check
if not isin... |
Try to apply the variables that were set but not known yet. | def _process_pending_variables(self):
""" Try to apply the variables that were set but not known yet.
"""
# Clear our list of pending variables
self._pending_variables, pending = {}, self._pending_variables
# Try to apply it. On failure, it will be added again
for name, d... |
Draw the attribute arrays in the specified mode. | def draw(self, mode='triangles', indices=None, check_error=True):
""" Draw the attribute arrays in the specified mode.
Parameters
----------
mode : str | GL_ENUM
'points', 'lines', 'line_strip', 'line_loop', 'triangles',
'triangle_strip', or 'triangle_fan'.
... |
Update the data in this surface plot. | def set_data(self, x=None, y=None, z=None, colors=None):
"""Update the data in this surface plot.
Parameters
----------
x : ndarray | None
1D array of values specifying the x positions of vertices in the
grid. If None, values will be assumed to be integers.
... |
A simplified representation of the same transformation. | def simplified(self):
"""A simplified representation of the same transformation.
"""
if self._simplified is None:
self._simplified = SimplifiedChainTransform(self)
return self._simplified |
Map coordinates | def map(self, coords):
"""Map coordinates
Parameters
----------
coords : array-like
Coordinates to map.
Returns
-------
coords : ndarray
Coordinates.
"""
for tr in reversed(self.transforms):
coords = tr.map(coo... |
Inverse map coordinates | def imap(self, coords):
"""Inverse map coordinates
Parameters
----------
coords : array-like
Coordinates to inverse map.
Returns
-------
coords : ndarray
Coordinates.
"""
for tr in self.transforms:
coords = tr.... |
Add a new transform to the end of this chain. | def append(self, tr):
"""
Add a new transform to the end of this chain.
Parameters
----------
tr : instance of Transform
The transform to use.
"""
self.transforms.append(tr)
tr.changed.connect(self._subtr_changed)
self._rebuild_shaders... |
Add a new transform to the beginning of this chain. | def prepend(self, tr):
"""
Add a new transform to the beginning of this chain.
Parameters
----------
tr : instance of Transform
The transform to use.
"""
self.transforms.insert(0, tr)
tr.changed.connect(self._subtr_changed)
self._rebui... |
Generate a simplified chain by joining adjacent transforms. | def source_changed(self, event):
"""Generate a simplified chain by joining adjacent transforms.
"""
# bail out early if the chain is empty
transforms = self._chain.transforms[:]
if len(transforms) == 0:
self.transforms = []
return
# If the... |
Pack an iterable of messages in the TCP protocol format | def pack_iterable(messages):
'''Pack an iterable of messages in the TCP protocol format'''
# [ 4-byte body size ]
# [ 4-byte num messages ]
# [ 4-byte message #1 size ][ N-byte binary data ]
# ... (repeated <num_messages> times)
return pack_string(
struct.pack('>l', len(messages)) +... |
Print out printable characters but others in hex | def hexify(message):
'''Print out printable characters, but others in hex'''
import string
hexified = []
for char in message:
if (char in '\n\r \t') or (char not in string.printable):
hexified.append('\\x%02x' % ord(char))
else:
hexified.append(char)
return ''... |
Generator for ( count object ) tuples that distributes count evenly among the provided objects | def distribute(total, objects):
'''Generator for (count, object) tuples that distributes count evenly among
the provided objects'''
for index, obj in enumerate(objects):
start = (index * total) / len(objects)
stop = ((index + 1) * total) / len(objects)
yield (stop - start, obj) |
Clean queue items from a previous session. | def clean(self):
"""Clean queue items from a previous session.
In case a previous session crashed and there are still some running
entries in the queue ('running', 'stopping', 'killing'), we clean those
and enqueue them again.
"""
for _, item in self.queue.items():
... |
Remove all completed tasks from the queue. | def clear(self):
"""Remove all completed tasks from the queue."""
for key in list(self.queue.keys()):
if self.queue[key]['status'] in ['done', 'failed']:
del self.queue[key]
self.write() |
Get the next processable item of the queue. | def next(self):
"""Get the next processable item of the queue.
A processable item is supposed to have the status `queued`.
Returns:
None : If no key is found.
Int: If a valid entry is found.
"""
smallest = None
for key in self.queue.keys():
... |
Read the queue of the last pueue session or set self. queue = {}. | def read(self):
"""Read the queue of the last pueue session or set `self.queue = {}`."""
queue_path = os.path.join(self.config_dir, 'queue')
if os.path.exists(queue_path):
queue_file = open(queue_path, 'rb')
try:
self.queue = pickle.load(queue_file)
... |
Write the current queue to a file. We need this to continue an earlier session. | def write(self):
"""Write the current queue to a file. We need this to continue an earlier session."""
queue_path = os.path.join(self.config_dir, 'queue')
queue_file = open(queue_path, 'wb+')
try:
pickle.dump(self.queue, queue_file, -1)
except Exception:
p... |
Add a new entry to the queue. | def add_new(self, command):
"""Add a new entry to the queue."""
self.queue[self.next_key] = command
self.queue[self.next_key]['status'] = 'queued'
self.queue[self.next_key]['returncode'] = ''
self.queue[self.next_key]['stdout'] = ''
self.queue[self.next_key]['stderr'] = '... |
Remove a key from the queue return False if no such key exists. | def remove(self, key):
"""Remove a key from the queue, return `False` if no such key exists."""
if key in self.queue:
del self.queue[key]
self.write()
return True
return False |
Restart a previously finished entry. | def restart(self, key):
"""Restart a previously finished entry."""
if key in self.queue:
if self.queue[key]['status'] in ['failed', 'done']:
new_entry = {'command': self.queue[key]['command'],
'path': self.queue[key]['path']}
self.... |
Switch two entries in the queue. Return False if an entry doesn t exist. | def switch(self, first, second):
"""Switch two entries in the queue. Return False if an entry doesn't exist."""
allowed_states = ['queued', 'stashed']
if first in self.queue and second in self.queue \
and self.queue[first]['status'] in allowed_states\
and self.que... |
Receive an answer from the daemon and return the response. | def receive_data(socket):
"""Receive an answer from the daemon and return the response.
Args:
socket (socket.socket): A socket that is connected to the daemon.
Returns:
dir or string: The unpickled answer.
"""
answer = b""
while True:
packet = socket.recv(4096)
if n... |
Connect to a daemon s socket. | def connect_socket(root_dir):
"""Connect to a daemon's socket.
Args:
root_dir (str): The directory that used as root by the daemon.
Returns:
socket.socket: A socket that is connected to the daemon.
"""
# Get config directory where the daemon socket is located
config_dir = os.pa... |
Return a new response from a raw buffer | def from_raw(conn, raw):
'''Return a new response from a raw buffer'''
frame_type = struct.unpack('>l', raw[0:4])[0]
message = raw[4:]
if frame_type == FRAME_TYPE_MESSAGE:
return Message(conn, frame_type, message)
elif frame_type == FRAME_TYPE_RESPONSE:
re... |
Pack the provided data into a Response | def pack(cls, data):
'''Pack the provided data into a Response'''
return struct.pack('>ll', len(data) + 4, cls.FRAME_TYPE) + data |
Indicate that this message is finished processing | def fin(self):
'''Indicate that this message is finished processing'''
self.connection.fin(self.id)
self.processed = True |
Re - queue a message | def req(self, timeout):
'''Re-queue a message'''
self.connection.req(self.id, timeout)
self.processed = True |
Make sure this message gets either fin or req d | def handle(self):
'''Make sure this message gets either 'fin' or 'req'd'''
try:
yield self
except:
# Requeue the message and raise the original exception
typ, value, trace = sys.exc_info()
if not self.processed:
try:
... |
Find the exception class by name | def find(cls, name):
'''Find the exception class by name'''
if not cls.mapping: # pragma: no branch
for _, obj in inspect.getmembers(exceptions):
if inspect.isclass(obj):
if issubclass(obj, exceptions.NSQException): # pragma: no branch
... |
Return an instance of the corresponding exception | def exception(self):
'''Return an instance of the corresponding exception'''
code, _, message = self.data.partition(' ')
return self.find(code)(message) |
r Parse the gdb version from the gdb header. | def parse_gdb_version(line):
r"""Parse the gdb version from the gdb header.
From GNU coding standards: the version starts after the last space of the
first line.
>>> DOCTEST_GDB_VERSIONS = [
... r'~"GNU gdb (GDB) 7.5.1\n"',
... r'~"GNU gdb (Sourcery CodeBench Lite 2011.09-69) 7.2.50.20100908-c... |
Spawn gdb and attach to a process. | def spawn_gdb(pid, address=DFLT_ADDRESS, gdb='gdb', verbose=False,
ctx=None, proc_iut=None):
"""Spawn gdb and attach to a process."""
parent, child = socket.socketpair()
proc = Popen([gdb, '--interpreter=mi', '-nx'],
bufsize=0, stdin=child, stdout=child, stderr=STDOUT)
... |
Spawn the process then repeatedly attach to the process. | def attach_loop(argv):
"""Spawn the process, then repeatedly attach to the process."""
# Check if the pdbhandler module is built into python.
p = Popen((sys.executable, '-X', 'pdbhandler', '-c',
'import pdbhandler; pdbhandler.get_handler().host'),
stdout=PIPE, stderr=STDOUT)
... |
Skip this py - pdb command to avoid attaching within the same loop. | def skip(self):
"""Skip this py-pdb command to avoid attaching within the same loop."""
line = self.line
self.line = ''
# 'line' is the statement line of the previous py-pdb command.
if line in self.lines:
if not self.skipping:
self.skipping = True
... |
Move the current log to a new file with timestamp and create a new empty log file. | def rotate(self, log):
"""Move the current log to a new file with timestamp and create a new empty log file."""
self.write(log, rotate=True)
self.write({}) |
Write the output of all finished processes to a compiled log file. | def write(self, log, rotate=False):
"""Write the output of all finished processes to a compiled log file."""
# Get path for logfile
if rotate:
timestamp = time.strftime('-%Y%m%d-%H%M')
logPath = os.path.join(self.log_dir, 'queue{}.log'.format(timestamp))
else:
... |
Remove all logs which are older than the specified time. | def remove_old(self, max_log_time):
"""Remove all logs which are older than the specified time."""
files = glob.glob('{}/queue-*'.format(self.log_dir))
files = list(map(lambda x: os.path.basename(x), files))
for log_file in files:
# Get time stamp from filename
n... |
Wrap a function that returns a request with some exception handling | def wrap(function, *args, **kwargs):
'''Wrap a function that returns a request with some exception handling'''
try:
req = function(*args, **kwargs)
logger.debug('Got %s: %s', req.status_code, req.content)
if req.status_code == 200:
return req
else:
raise C... |
Return the json content of a function that returns a request | def json_wrap(function, *args, **kwargs):
'''Return the json content of a function that returns a request'''
try:
# Some responses have data = None, but they generally signal a
# successful API call as well.
response = json.loads(function(*args, **kwargs).content)
if 'data' in re... |
Ensure that the response body is OK | def ok_check(function, *args, **kwargs):
'''Ensure that the response body is OK'''
req = function(*args, **kwargs)
if req.content.lower() != 'ok':
raise ClientException(req.content)
return req.content |
GET the provided endpoint | def get(self, path, *args, **kwargs):
'''GET the provided endpoint'''
target = self._host.relative(path).utf8
if not isinstance(target, basestring):
# on older versions of the `url` library, .utf8 is a method, not a property
target = target()
params = kwargs.get('... |
Decodes bitmap_node to hash of unit_id: is_uploaded | def decode_resumable_upload_bitmap(bitmap_node, number_of_units):
"""Decodes bitmap_node to hash of unit_id: is_uploaded
bitmap_node -- bitmap node of resumable_upload with
'count' number and 'words' containing array
number_of_units -- number of units we are uploading to
... |
Get MediaFireHashInfo structure from the fd unit_size | def compute_hash_info(fd, unit_size=None):
"""Get MediaFireHashInfo structure from the fd, unit_size
fd -- file descriptor - expects exclusive access because of seeking
unit_size -- size of a single unit
Returns MediaFireHashInfo:
hi.file -- sha256 of the whole file
hi.units -- list of sha256 ... |
Upload file returns UploadResult object | def upload(self, fd, name=None, folder_key=None, filedrop_key=None,
path=None, action_on_duplicate=None):
"""Upload file, returns UploadResult object
fd -- file-like object to upload from, expects exclusive access
name -- file name
folder_key -- folderkey of the target fo... |
Poll upload until quickkey is found | def _poll_upload(self, upload_key, action):
"""Poll upload until quickkey is found
upload_key -- upload_key returned by upload/* functions
"""
if len(upload_key) != UPLOAD_KEY_LENGTH:
# not a regular 11-char-long upload key
# There is no API to poll filedrop upl... |
Wrapper around upload/ check | def _upload_check(self, upload_info, resumable=False):
"""Wrapper around upload/check"""
return self._api.upload_check(
filename=upload_info.name,
size=upload_info.size,
hash_=upload_info.hash_info.file,
folder_key=upload_info.folder_key,
filed... |
Dummy upload function for when we don t actually upload | def _upload_none(self, upload_info, check_result):
"""Dummy upload function for when we don't actually upload"""
return UploadResult(
action=None,
quickkey=check_result['duplicate_quickkey'],
hash_=upload_info.hash_info.file,
filename=upload_info.name,
... |
Instant upload and return quickkey | def _upload_instant(self, upload_info, _=None):
"""Instant upload and return quickkey
Can be used when the file is already stored somewhere in MediaFire
upload_info -- UploadInfo object
check_result -- ignored
"""
result = self._api.upload_instant(
upload_i... |
Simple upload and return quickkey | def _upload_simple(self, upload_info, _=None):
"""Simple upload and return quickkey
Can be used for small files smaller than UPLOAD_SIMPLE_LIMIT_BYTES
upload_info -- UploadInfo object
check_result -- ignored
"""
upload_result = self._api.upload_simple(
uplo... |
Upload a single unit and return raw upload/ resumable result | def _upload_resumable_unit(self, uu_info):
"""Upload a single unit and return raw upload/resumable result
uu_info -- UploadUnitInfo instance
"""
# Get actual unit size
unit_size = uu_info.fd.len
if uu_info.hash_ is None:
raise ValueError('UploadUnitInfo.has... |
Prepare and upload all resumable units and return upload_key | def _upload_resumable_all(self, upload_info, bitmap,
number_of_units, unit_size):
"""Prepare and upload all resumable units and return upload_key
upload_info -- UploadInfo object
bitmap -- bitmap node of upload/check
number_of_units -- number of units reque... |
Resumable upload and return quickkey | def _upload_resumable(self, upload_info, check_result):
"""Resumable upload and return quickkey
upload_info -- UploadInfo object
check_result -- dict of upload/check call result
"""
resumable_upload = check_result['resumable_upload']
unit_size = int(resumable_upload['u... |
Remove from sys. modules the modules imported by the debuggee. | def reset(self):
"""Remove from sys.modules the modules imported by the debuggee."""
if not self.hooked:
self.hooked = True
sys.path_hooks.append(self)
sys.path.insert(0, self.PATH_ENTRY)
return
for modname in self:
if modname in sys.m... |
The first line number of the last defined funcname function. | def get_func_lno(self, funcname):
"""The first line number of the last defined 'funcname' function."""
class FuncLineno(ast.NodeVisitor):
def __init__(self):
self.clss = []
def generic_visit(self, node):
for child in ast.iter_child_nodes(node):
... |
Get the actual breakpoint line number. | def get_actual_bp(self, lineno):
"""Get the actual breakpoint line number.
When an exact match cannot be found in the lnotab expansion of the
module code object or one of its subcodes, pick up the next valid
statement line number.
Return the statement line defined by the tuple ... |
Return the list of breakpoints set at lineno. | def get_breakpoints(self, lineno):
"""Return the list of breakpoints set at lineno."""
try:
firstlineno, actual_lno = self.bdb_module.get_actual_bp(lineno)
except BdbSourceError:
return []
if firstlineno not in self:
return []
code_bps = self[f... |
Set or remove the trace function. | def settrace(self, do_set):
"""Set or remove the trace function."""
if do_set:
sys.settrace(self.trace_dispatch)
else:
sys.settrace(None) |
Restart the debugger after source code changes. | def restart(self):
"""Restart the debugger after source code changes."""
_module_finder.reset()
linecache.checkcache()
for module_bpts in self.breakpoints.values():
module_bpts.reset() |
Stop when the current line number in frame is greater than lineno or when returning from frame. | def set_until(self, frame, lineno=None):
"""Stop when the current line number in frame is greater than lineno or
when returning from frame."""
if lineno is None:
lineno = frame.f_lineno + 1
self._set_stopinfo(frame, lineno) |
Start debugging from frame. | def set_trace(self, frame=None):
"""Start debugging from `frame`.
If frame is not specified, debugging starts from caller's frame.
"""
# First disable tracing temporarily as set_trace() may be called while
# tracing is in use. For example when called from a signal handler and
... |
Return ( stop_state delete_temporary ) at a breakpoint hit event. | def process_hit_event(self, frame):
"""Return (stop_state, delete_temporary) at a breakpoint hit event."""
if not self.enabled:
return False, False
# Count every hit when breakpoint is enabled.
self.hits += 1
# A conditional breakpoint.
if self.cond:
... |
Returns list of nested files and directories for local directory by path | def listdir(directory):
"""Returns list of nested files and directories for local directory by path
:param directory: absolute or relative path to local directory
:return: list nested of file or directory names
"""
file_names = list()
for filename in os.listdir(directory):
file_path = o... |
Extract options for specified option type from all options | def get_options(option_type, from_options):
"""Extract options for specified option type from all options
:param option_type: the object of specified type of options
:param from_options: all options dictionary
:return: the dictionary of options for specified type, each option can be filled by value fro... |
Returns HTTP headers of specified WebDAV actions. | def get_headers(self, action, headers_ext=None):
"""Returns HTTP headers of specified WebDAV actions.
:param action: the identifier of action.
:param headers_ext: (optional) the addition headers list witch sgould be added to basic HTTP headers for
the specified actio... |
Generate request to WebDAV server for specified action and path and execute it. | def execute_request(self, action, path, data=None, headers_ext=None):
"""Generate request to WebDAV server for specified action and path and execute it.
:param action: the action for WebDAV server which should be executed.
:param path: the path to resource for action
:param data: (optio... |
Validates of WebDAV and proxy settings. | def valid(self):
"""Validates of WebDAV and proxy settings.
:return: True in case settings are valid and False otherwise.
"""
return True if self.webdav.valid() and self.proxy.valid() else False |
Returns list of nested files and directories for remote WebDAV directory by path. More information you can find by link http:// webdav. org/ specs/ rfc4918. html#METHOD_PROPFIND | def list(self, remote_path=root):
"""Returns list of nested files and directories for remote WebDAV directory by path.
More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND
:param remote_path: path to remote directory.
:return: list of nested file or... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.