Search is not available for this dataset
text stringlengths 75 104k |
|---|
async def update_bikes(delta: Optional[timedelta] = None):
"""
A background task that retrieves bike data.
:param delta: The amount of time to wait between checks.
"""
async def update(delta: timedelta):
logger.info("Fetching bike data.")
if await should_update_bikes(delta):
try:
bike_data = await fetch_bikes()
except ApiError:
logger.debug(f"Failed to fetch bikes.")
except CircuitBreakerError:
logger.debug(f"Failed to fetch bikes (circuit breaker open).")
else:
# save only bikes that aren't in the db
most_recent_bike = Bike.get_most_recent_bike()
new_bikes = (
Bike.from_dict(bike) for index, bike in enumerate(bike_data)
if index > (most_recent_bike.id if most_recent_bike is not None else -1)
)
counter = 0
with Bike._meta.database.atomic():
for bike in new_bikes:
bike.save()
counter += 1
logger.info(f"Saved {counter} new entries.")
else:
logger.info("Bike data up to date.")
if delta is None:
await update(timedelta(days=1000))
else:
while True:
await update(delta)
await asyncio.sleep(delta.total_seconds()) |
async def should_update_bikes(delta: timedelta):
"""
Checks the most recently cached bike and returns true if
it either doesn't exist or
:return: Whether the cache should be updated.
todo what if there are no bikes added for a week? ... every request will be triggered.
"""
bike = Bike.get_most_recent_bike()
if bike is not None:
return bike.cached_date < datetime.now() - delta
else:
return True |
async def get_bikes(postcode: PostCodeLike, kilometers=1) -> Optional[List[Bike]]:
"""
Gets stolen bikes from the database within a
certain radius (km) of a given postcode. Selects
a square from the database and then filters out
the corners of the square.
:param postcode: The postcode to look up.
:param kilometers: The radius (km) of the search.
:return: The bikes in that radius or None if the postcode doesn't exist.
"""
try:
postcode_opt = await get_postcode(postcode)
except CachingError as e:
raise e
if postcode_opt is None:
return None
else:
postcode = postcode_opt
# create point and distance
center = Point(postcode.lat, postcode.long)
distance = geodesic(kilometers=kilometers)
# calculate edges of a square and retrieve
lat_end = distance.destination(point=center, bearing=0).latitude
lat_start = distance.destination(point=center, bearing=180).latitude
long_start = distance.destination(point=center, bearing=270).longitude
long_end = distance.destination(point=center, bearing=90).longitude
bikes_in_area = Bike.select().where(
lat_start <= Bike.latitude,
Bike.latitude <= lat_end,
long_start <= Bike.longitude,
Bike.longitude <= long_end
)
# filter out items in square that aren't within the radius and return
return [
bike for bike in bikes_in_area
if geodesic(Point(bike.latitude, bike.longitude), center).kilometers < kilometers
] |
async def get_postcode_random() -> Postcode:
"""
Gets a random postcode object..
Acts as a middleware between us and the API, caching results.
:return: The PostCode object else None if the postcode does not exist.
"""
try:
postcode = await fetch_postcode_random()
except (ApiError, CircuitBreakerError):
raise CachingError(f"Requested postcode is not cached, and can't be retrieved.")
if postcode is not None:
postcode.save()
return postcode |
async def get_postcode(postcode_like: PostCodeLike) -> Optional[Postcode]:
"""
Gets the postcode object for a given postcode string.
Acts as a middleware between us and the API, caching results.
:param postcode_like: The either a string postcode or PostCode object.
:return: The PostCode object else None if the postcode does not exist..
:raises CachingError: When the postcode is not in cache, and the API is unreachable.
"""
if isinstance(postcode_like, Postcode):
return postcode_like
postcode_like = postcode_like.replace(" ", "").upper()
try:
postcode = Postcode.get(Postcode.postcode == postcode_like)
except DoesNotExist:
try:
postcode = await fetch_postcode_from_string(postcode_like)
except (ApiError, CircuitBreakerError):
raise CachingError(f"Requested postcode is not cached, and can't be retrieved.")
if postcode is not None:
postcode.save()
return postcode |
async def get_neighbourhood(postcode_like: PostCodeLike) -> Optional[Neighbourhood]:
"""
Gets a police neighbourhood from the database.
Acts as a middleware between us and the API, caching results.
:param postcode_like: The UK postcode to look up.
:return: The Neighbourhood or None if the postcode does not exist.
:raises CachingError: If the needed neighbourhood is not in cache, and the fetch isn't responding.
todo save locations/links
"""
try:
postcode = await get_postcode(postcode_like)
except CachingError as e:
raise e
else:
if postcode is None:
return None
elif postcode.neighbourhood is not None:
return postcode.neighbourhood
try:
data = await fetch_neighbourhood(postcode.lat, postcode.long)
except ApiError as e:
raise CachingError(f"Neighbourhood not in cache, and could not reach API: {e.status}")
if data is not None:
neighbourhood = Neighbourhood.from_dict(data)
locations = [Location.from_dict(neighbourhood, postcode, location) for location in data["locations"]]
links = [Link.from_dict(neighbourhood, link) for link in data["links"]]
with Neighbourhood._meta.database.atomic():
neighbourhood.save()
postcode.neighbourhood = neighbourhood
postcode.save()
for location in locations:
location.save()
for link in links:
link.save()
else:
neighbourhood = None
return neighbourhood |
def get_cdata(self, *args):
'''
all args-->_cffi_backend.buffer
Returns-->cdata (if a SINGLE argument was provided)
LIST of cdata (if a args was a tuple or list)
'''
res = tuple([
self.from_buffer(x) for x in args
])
if len(res) == 0:
return None
elif len(res) == 1:
return res[0]
else:
return res |
def get_buffer(self, *args):
'''
all args-->_cffi_backend.CDataOwn
Must be a pointer or an array
Returns-->buffer (if a SINGLE argument was provided)
LIST of buffer (if a args was a tuple or list)
'''
res = tuple([
self.buffer(x) for x in args
])
if len(res) == 0:
return None
elif len(res) == 1:
return res[0]
else:
return res |
def get_bytes(self, *args):
'''
all args-->_cffi_backend.CDataOwn
Must be a pointer or an array
Returns-->bytes (if a SINGLE argument was provided)
LIST of bytes (if a args was a tuple or list)
'''
res = tuple([
bytes(self.buffer(x)) for x in args
])
if len(res) == 0:
return None
elif len(res) == 1:
return res[0]
else:
return res |
def get_brightness(self):
"""
Return the average brightness of the image.
"""
# Only download the image if it has changed
if not self.connection.has_changed():
return self.image_brightness
image_path = self.connection.download_image()
converted_image = Image.open(image_path).convert('L')
statistics = ImageStat.Stat(converted_image)
self.image_brightness = statistics.mean[0]
return self.image_brightness |
def write_file (filename, contents):
"""Create a file with the specified name and write 'contents' (a
sequence of strings without line terminators) to it.
"""
contents = "\n".join(contents)
if sys.version_info >= (3,):
contents = contents.encode("utf-8")
f = open(filename, "wb") # always write POSIX-style manifest
f.write(contents)
f.close() |
def write_file(self, what, filename, data):
"""Write `data` to `filename` (if not a dry run) after announcing it
`what` is used in a log message to identify what is being written
to the file.
"""
log.info("writing %s to %s", what, filename)
if sys.version_info >= (3,):
data = data.encode("utf-8")
if not self.dry_run:
f = open(filename, 'wb')
f.write(data)
f.close() |
def write_manifest (self):
"""Write the file list in 'self.filelist' (presumably as filled in
by 'add_defaults()' and 'read_template()') to the manifest file
named by 'self.manifest'.
"""
# The manifest must be UTF-8 encodable. See #303.
if sys.version_info >= (3,):
files = []
for file in self.filelist.files:
try:
file.encode("utf-8")
except UnicodeEncodeError:
log.warn("'%s' not UTF-8 encodable -- skipping" % file)
else:
files.append(file)
self.filelist.files = files
files = self.filelist.files
if os.sep!='/':
files = [f.replace(os.sep,'/') for f in files]
self.execute(write_file, (self.manifest, files),
"writing manifest file '%s'" % self.manifest) |
def match(self, *args):
"""
Indicate whether or not to enter a case suite.
usage:
``` py
for case in switch(value):
if case('A'):
pass
elif case(1, 3):
pass # for mulit-match.
else:
pass # for default.
```
"""
if not args:
raise SyntaxError('cannot case empty pattern.')
return self.match_args(self._value, args) |
def _find_match(self, position):
""" Given a valid position in the text document, try to find the
position of the matching bracket. Returns -1 if unsuccessful.
"""
# Decide what character to search for and what direction to search in.
document = self._text_edit.document()
start_char = document.characterAt(position)
search_char = self._opening_map.get(start_char)
if search_char:
increment = 1
else:
search_char = self._closing_map.get(start_char)
if search_char:
increment = -1
else:
return -1
# Search for the character.
char = start_char
depth = 0
while position >= 0 and position < document.characterCount():
if char == start_char:
depth += 1
elif char == search_char:
depth -= 1
if depth == 0:
break
position += increment
char = document.characterAt(position)
else:
position = -1
return position |
def _selection_for_character(self, position):
""" Convenience method for selecting a character.
"""
selection = QtGui.QTextEdit.ExtraSelection()
cursor = self._text_edit.textCursor()
cursor.setPosition(position)
cursor.movePosition(QtGui.QTextCursor.NextCharacter,
QtGui.QTextCursor.KeepAnchor)
selection.cursor = cursor
selection.format = self.format
return selection |
def _cursor_position_changed(self):
""" Updates the document formatting based on the new cursor position.
"""
# Clear out the old formatting.
self._text_edit.setExtraSelections([])
# Attempt to match a bracket for the new cursor position.
cursor = self._text_edit.textCursor()
if not cursor.hasSelection():
position = cursor.position() - 1
match_position = self._find_match(position)
if match_position != -1:
extra_selections = [ self._selection_for_character(pos)
for pos in (position, match_position) ]
self._text_edit.setExtraSelections(extra_selections) |
def _exc_info(self):
"""Bottleneck to fix up IronPython string exceptions
"""
e = self.exc_info()
if sys.platform == 'cli':
if isinstance(e[0], StringException):
# IronPython throws these StringExceptions, but
# traceback checks type(etype) == str. Make a real
# string here.
e = (str(e[0]), e[1], e[2])
return e |
def run(self, result):
"""Run tests in suite inside of suite fixtures.
"""
# proxy the result for myself
log.debug("suite %s (%s) run called, tests: %s", id(self), self, self._tests)
#import pdb
#pdb.set_trace()
if self.resultProxy:
result, orig = self.resultProxy(result, self), result
else:
result, orig = result, result
try:
self.setUp()
except KeyboardInterrupt:
raise
except:
self.error_context = 'setup'
result.addError(self, self._exc_info())
return
try:
for test in self._tests:
if result.shouldStop:
log.debug("stopping")
break
# each nose.case.Test will create its own result proxy
# so the cases need the original result, to avoid proxy
# chains
test(orig)
finally:
self.has_run = True
try:
self.tearDown()
except KeyboardInterrupt:
raise
except:
self.error_context = 'teardown'
result.addError(self, self._exc_info()) |
def ancestry(self, context):
"""Return the ancestry of the context (that is, all of the
packages and modules containing the context), in order of
descent with the outermost ancestor last.
This method is a generator.
"""
log.debug("get ancestry %s", context)
if context is None:
return
# Methods include reference to module they are defined in, we
# don't want that, instead want the module the class is in now
# (classes are re-ancestored elsewhere).
if hasattr(context, 'im_class'):
context = context.im_class
elif hasattr(context, '__self__'):
context = context.__self__.__class__
if hasattr(context, '__module__'):
ancestors = context.__module__.split('.')
elif hasattr(context, '__name__'):
ancestors = context.__name__.split('.')[:-1]
else:
raise TypeError("%s has no ancestors?" % context)
while ancestors:
log.debug(" %s ancestors %s", context, ancestors)
yield resolve_name('.'.join(ancestors))
ancestors.pop() |
def mixedSuites(self, tests):
"""The complex case where there are tests that don't all share
the same context. Groups tests into suites with common ancestors,
according to the following (essentially tail-recursive) procedure:
Starting with the context of the first test, if it is not
None, look for tests in the remaining tests that share that
ancestor. If any are found, group into a suite with that
ancestor as the context, and replace the current suite with
that suite. Continue this process for each ancestor of the
first test, until all ancestors have been processed. At this
point if any tests remain, recurse with those tests as the
input, returning a list of the common suite (which may be the
suite or test we started with, if no common tests were found)
plus the results of recursion.
"""
if not tests:
return []
head = tests.pop(0)
if not tests:
return [head] # short circuit when none are left to combine
suite = head # the common ancestry suite, so far
tail = tests[:]
context = getattr(head, 'context', None)
if context is not None:
ancestors = [context] + [a for a in self.ancestry(context)]
for ancestor in ancestors:
common = [suite] # tests with ancestor in common, so far
remain = [] # tests that remain to be processed
for test in tail:
found_common = False
test_ctx = getattr(test, 'context', None)
if test_ctx is None:
remain.append(test)
continue
if test_ctx is ancestor:
common.append(test)
continue
for test_ancestor in self.ancestry(test_ctx):
if test_ancestor is ancestor:
common.append(test)
found_common = True
break
if not found_common:
remain.append(test)
if common:
suite = self.makeSuite(common, ancestor)
tail = self.mixedSuites(remain)
return [suite] + tail |
def options(self, parser, env):
"""Register commandline options.
"""
parser.add_option('--collect-only',
action='store_true',
dest=self.enableOpt,
default=env.get('NOSE_COLLECT_ONLY'),
help="Enable collect-only: %s [COLLECT_ONLY]" %
(self.help())) |
def create_inputhook_qt4(mgr, app=None):
"""Create an input hook for running the Qt4 application event loop.
Parameters
----------
mgr : an InputHookManager
app : Qt Application, optional.
Running application to use. If not given, we probe Qt for an
existing application object, and create a new one if none is found.
Returns
-------
A pair consisting of a Qt Application (either the one given or the
one found or created) and a inputhook.
Notes
-----
We use a custom input hook instead of PyQt4's default one, as it
interacts better with the readline packages (issue #481).
The inputhook function works in tandem with a 'pre_prompt_hook'
which automatically restores the hook as an inputhook in case the
latter has been temporarily disabled after having intercepted a
KeyboardInterrupt.
"""
if app is None:
app = QtCore.QCoreApplication.instance()
if app is None:
app = QtGui.QApplication([" "])
# Re-use previously created inputhook if any
ip = InteractiveShell.instance()
if hasattr(ip, '_inputhook_qt4'):
return app, ip._inputhook_qt4
# Otherwise create the inputhook_qt4/preprompthook_qt4 pair of
# hooks (they both share the got_kbdint flag)
got_kbdint = [False]
def inputhook_qt4():
"""PyOS_InputHook python hook for Qt4.
Process pending Qt events and if there's no pending keyboard
input, spend a short slice of time (50ms) running the Qt event
loop.
As a Python ctypes callback can't raise an exception, we catch
the KeyboardInterrupt and temporarily deactivate the hook,
which will let a *second* CTRL+C be processed normally and go
back to a clean prompt line.
"""
try:
allow_CTRL_C()
app = QtCore.QCoreApplication.instance()
if not app: # shouldn't happen, but safer if it happens anyway...
return 0
app.processEvents(QtCore.QEventLoop.AllEvents, 300)
if not stdin_ready():
timer = QtCore.QTimer()
timer.timeout.connect(app.quit)
while not stdin_ready():
timer.start(50)
app.exec_()
timer.stop()
except KeyboardInterrupt:
ignore_CTRL_C()
got_kbdint[0] = True
print("\nKeyboardInterrupt - Ctrl-C again for new prompt")
mgr.clear_inputhook()
except: # NO exceptions are allowed to escape from a ctypes callback
ignore_CTRL_C()
from traceback import print_exc
print_exc()
print("Got exception from inputhook_qt4, unregistering.")
mgr.clear_inputhook()
finally:
allow_CTRL_C()
return 0
def preprompthook_qt4(ishell):
"""'pre_prompt_hook' used to restore the Qt4 input hook
(in case the latter was temporarily deactivated after a
CTRL+C)
"""
if got_kbdint[0]:
mgr.set_inputhook(inputhook_qt4)
got_kbdint[0] = False
ip._inputhook_qt4 = inputhook_qt4
ip.set_hook('pre_prompt_hook', preprompthook_qt4)
return app, inputhook_qt4 |
def get(cls, name=__name__):
"""Return a Mapper instance with the given name.
If the name already exist return its instance.
Does not work if a Mapper was created via its constructor.
Using `Mapper.get()`_ is the prefered way.
Args:
name (str, optional): Name for the newly created instance.
Defaults to `__name__`.
Returns:
Mapper: A mapper instance for the given name.
Raises:
TypeError: If a invalid name was given.
"""
if not isinstance(name, str):
raise TypeError('A mapper name must be a string')
if name not in cls.__instances:
cls.__instances[name] = cls()
cls.__instances[name]._name = name
return cls.__instances[name] |
def url(self, pattern, method=None, type_cast=None):
"""Decorator for registering a path pattern.
Args:
pattern (str): Regex pattern to match a certain path
method (str, optional): Usually used to define one of GET, POST,
PUT, DELETE. You may use whatever fits your situation though.
Defaults to None.
type_cast (dict, optional): Mapping between the param name and
one of `int`, `float` or `bool`. The value reflected by the
provided param name will than be casted to the given type.
Defaults to None.
"""
if not type_cast:
type_cast = {}
def decorator(function):
self.add(pattern, function, method, type_cast)
return function
return decorator |
def s_url(self, path, method=None, type_cast=None):
"""Decorator for registering a simple path.
Args:
path (str): Path to be matched.
method (str, optional): Usually used to define one of GET, POST,
PUT, DELETE. You may use whatever fits your situation though.
Defaults to None.
type_cast (dict, optional): Mapping between the param name and
one of `int`, `float` or `bool`. The value reflected by the
provided param name will than be casted to the given type.
Defaults to None.
"""
if not type_cast:
type_cast = {}
def decorator(function):
self.s_add(path, function, method, type_cast)
return function
return decorator |
def add(self, pattern, function, method=None, type_cast=None):
"""Function for registering a path pattern.
Args:
pattern (str): Regex pattern to match a certain path.
function (function): Function to associate with this path.
method (str, optional): Usually used to define one of GET, POST,
PUT, DELETE. You may use whatever fits your situation though.
Defaults to None.
type_cast (dict, optional): Mapping between the param name and
one of `int`, `float` or `bool`. The value reflected by the
provided param name will than be casted to the given type.
Defaults to None.
"""
if not type_cast:
type_cast = {}
with self._lock:
self._data_store.append({
'pattern': pattern,
'function': function,
'method': method,
'type_cast': type_cast,
}) |
def s_add(self, path, function, method=None, type_cast=None):
"""Function for registering a simple path.
Args:
path (str): Path to be matched.
function (function): Function to associate with this path.
method (str, optional): Usually used to define one of GET, POST,
PUT, DELETE. You may use whatever fits your situation though.
Defaults to None.
type_cast (dict, optional): Mapping between the param name and
one of `int`, `float` or `bool`. The value reflected by the
provided param name will than be casted to the given type.
Defaults to None.
"""
with self._lock:
try:
path = '^/{}'.format(path.lstrip('/'))
path = '{}/$'.format(path.rstrip('/'))
path = path.replace('<', '(?P<')
path = path.replace('>', '>[^/]*)')
self.add(path, function, method, type_cast)
except Exception:
pass |
def call(self, url, method=None, args=None):
"""Calls the first function matching the urls pattern and method.
Args:
url (str): Url for which to call a matching function.
method (str, optional): The method used while registering a
function.
Defaults to None
args (dict, optional): Additional args to be passed to the
matching function.
Returns:
The functions return value or `None` if no function was called.
"""
if not args:
args = {}
if sys.version_info.major == 3:
data = urllib.parse.urlparse(url)
path = data.path.rstrip('/') + '/'
_args = dict(urllib.parse.parse_qs(data.query,
keep_blank_values=True))
elif sys.version_info.major == 2:
data = urlparse.urlparse(url)
path = data.path.rstrip('/') + '/'
_args = dict(urlparse.parse_qs(data.query,
keep_blank_values=True))
for elem in self._data_store:
pattern = elem['pattern']
function = elem['function']
_method = elem['method']
type_cast = elem['type_cast']
result = re.match(pattern, path)
# Found matching method
if result and _method == method:
_args = dict(_args, **result.groupdict())
# Unpack value lists (due to urllib.parse.parse_qs) in case
# theres only one value available
for key, val in _args.items():
if isinstance(_args[key], list) and len(_args[key]) == 1:
_args[key] = _args[key][0]
# Apply typ-casting if necessary
for key, val in type_cast.items():
# Not within available _args, no type-cast required
if key not in _args:
continue
# Is None or empty, no type-cast required
if not _args[key]:
continue
# Try and cast the values
if isinstance(_args[key], list):
for i, _val in enumerate(_args[key]):
_args[key][i] = self._cast(_val, val)
else:
_args[key] = self._cast(_args[key], val)
requiered_args = self._get_function_args(function)
for key, val in args.items():
if key in requiered_args:
_args[key] = val
return function(**_args)
return None |
def execute(self, source=None, hidden=False, interactive=False):
""" Reimplemented to the store history.
"""
if not hidden:
history = self.input_buffer if source is None else source
executed = super(HistoryConsoleWidget, self).execute(
source, hidden, interactive)
if executed and not hidden:
# Save the command unless it was an empty string or was identical
# to the previous command.
history = history.rstrip()
if history and (not self._history or self._history[-1] != history):
self._history.append(history)
# Emulate readline: reset all history edits.
self._history_edits = {}
# Move the history index to the most recent item.
self._history_index = len(self._history)
return executed |
def _up_pressed(self, shift_modifier):
""" Called when the up key is pressed. Returns whether to continue
processing the event.
"""
prompt_cursor = self._get_prompt_cursor()
if self._get_cursor().blockNumber() == prompt_cursor.blockNumber():
# Bail out if we're locked.
if self._history_locked() and not shift_modifier:
return False
# Set a search prefix based on the cursor position.
col = self._get_input_buffer_cursor_column()
input_buffer = self.input_buffer
if self._history_index == len(self._history) or \
(self._history_prefix and col != len(self._history_prefix)):
self._history_index = len(self._history)
self._history_prefix = input_buffer[:col]
# Perform the search.
self.history_previous(self._history_prefix,
as_prefix=not shift_modifier)
# Go to the first line of the prompt for seemless history scrolling.
# Emulate readline: keep the cursor position fixed for a prefix
# search.
cursor = self._get_prompt_cursor()
if self._history_prefix:
cursor.movePosition(QtGui.QTextCursor.Right,
n=len(self._history_prefix))
else:
cursor.movePosition(QtGui.QTextCursor.EndOfLine)
self._set_cursor(cursor)
return False
return True |
def _down_pressed(self, shift_modifier):
""" Called when the down key is pressed. Returns whether to continue
processing the event.
"""
end_cursor = self._get_end_cursor()
if self._get_cursor().blockNumber() == end_cursor.blockNumber():
# Bail out if we're locked.
if self._history_locked() and not shift_modifier:
return False
# Perform the search.
replaced = self.history_next(self._history_prefix,
as_prefix=not shift_modifier)
# Emulate readline: keep the cursor position fixed for a prefix
# search. (We don't need to move the cursor to the end of the buffer
# in the other case because this happens automatically when the
# input buffer is set.)
if self._history_prefix and replaced:
cursor = self._get_prompt_cursor()
cursor.movePosition(QtGui.QTextCursor.Right,
n=len(self._history_prefix))
self._set_cursor(cursor)
return False
return True |
def history_previous(self, substring='', as_prefix=True):
""" If possible, set the input buffer to a previous history item.
Parameters:
-----------
substring : str, optional
If specified, search for an item with this substring.
as_prefix : bool, optional
If True, the substring must match at the beginning (default).
Returns:
--------
Whether the input buffer was changed.
"""
index = self._history_index
replace = False
while index > 0:
index -= 1
history = self._get_edited_history(index)
if (as_prefix and history.startswith(substring)) \
or (not as_prefix and substring in history):
replace = True
break
if replace:
self._store_edits()
self._history_index = index
self.input_buffer = history
return replace |
def history_next(self, substring='', as_prefix=True):
""" If possible, set the input buffer to a subsequent history item.
Parameters:
-----------
substring : str, optional
If specified, search for an item with this substring.
as_prefix : bool, optional
If True, the substring must match at the beginning (default).
Returns:
--------
Whether the input buffer was changed.
"""
index = self._history_index
replace = False
while self._history_index < len(self._history):
index += 1
history = self._get_edited_history(index)
if (as_prefix and history.startswith(substring)) \
or (not as_prefix and substring in history):
replace = True
break
if replace:
self._store_edits()
self._history_index = index
self.input_buffer = history
return replace |
def _handle_execute_reply(self, msg):
""" Handles replies for code execution, here only session history length
"""
msg_id = msg['parent_header']['msg_id']
info = self._request_info['execute'].pop(msg_id,None)
if info and info.kind == 'save_magic' and not self._hidden:
content = msg['content']
status = content['status']
if status == 'ok':
self._max_session_history=(int(content['user_expressions']['hlen'])) |
def _history_locked(self):
""" Returns whether history movement is locked.
"""
return (self.history_lock and
(self._get_edited_history(self._history_index) !=
self.input_buffer) and
(self._get_prompt_cursor().blockNumber() !=
self._get_end_cursor().blockNumber())) |
def _get_edited_history(self, index):
""" Retrieves a history item, possibly with temporary edits.
"""
if index in self._history_edits:
return self._history_edits[index]
elif index == len(self._history):
return unicode()
return self._history[index] |
def _set_history(self, history):
""" Replace the current history with a sequence of history items.
"""
self._history = list(history)
self._history_edits = {}
self._history_index = len(self._history) |
def _store_edits(self):
""" If there are edits to the current input buffer, store them.
"""
current = self.input_buffer
if self._history_index == len(self._history) or \
self._history[self._history_index] != current:
self._history_edits[self._history_index] = current |
def t_NAME(t):
r'[A-Za-z_][A-Za-z0-9_]*'
# to simplify lexing, we match identifiers and keywords as a single thing
# if it's a keyword, we change the type to the name of that keyword
if t.value.upper() in reserved:
t.type = t.value.upper()
t.value = t.value.upper()
return t |
def t_STRING(t):
r"'([^'\\]+|\\'|\\\\)*'"
t.value = t.value.replace(r'\\', chr(92)).replace(r"\'", r"'")[1:-1]
return t |
def p_postpositions(p):
'''
postpositions : LIMIT NUMBER postpositions
| ORDER BY colspec postpositions
| empty
'''
if len(p) > 2:
if p[1] == "LIMIT":
postposition = {
"limit": p[2]
}
rest = p[3] if p[3] else {}
elif p[1:3] == ["ORDER", "BY"]:
postposition = {
"order by": p[3]
}
rest = p[4] if p[4] else {}
else:
breakpoint()
p[0] = {**postposition, **rest}
else:
p[0] = {} |
def p_colspec(p):
'''
colspec : STAR
| NAME
| function
| NAME COMMA colspec
| function COMMA colspec
'''
rest = p[3] if len(p) > 3 else []
if p[1] == "*":
p[0] = [{"type": "star"}]
elif isinstance(p[1], dict) and p[1].get("type") == "function":
p[0] = [p[1], *rest]
elif p[1]:
p[0] = [
{
"type": "name",
"value": p[1],
},
*rest,
]
else:
p[0] = [] |
def p_expression(p):
'''
expression : value
| expression AND expression
| expression OR expression
| expression EQUALS expression
| NOT expression
| LPAREN expression RPAREN
'''
if len(p) < 3:
p[0] = p[1]
elif len(p) == 3: # not
p[0] = {
"op": "not",
"args": [p[2]],
}
elif p[1] == "(":
p[0] = p[2]
else:
p[0] = {
"op": p[2].lower(),
"args": [p[1], p[3]],
} |
def OnTimeToClose(self, evt):
"""Event handler for the button click."""
print("See ya later!")
sys.stdout.flush()
self.cleanup_consoles(evt)
self.Close()
# Not sure why, but our IPython kernel seems to prevent normal WX
# shutdown, so an explicit exit() call is needed.
sys.exit() |
def upgrade_dir(srcdir, tgtdir):
""" Copy over all files in srcdir to tgtdir w/ native line endings
Creates .upgrade_report in tgtdir that stores md5sums of all files
to notice changed files b/w upgrades.
"""
def pr(s):
print s
junk = ['.svn','ipythonrc*','*.pyc', '*.pyo', '*~', '.hg']
def ignorable(p):
for pat in junk:
if p.startswith(pat) or p.fnmatch(pat):
return True
return False
modded = []
files = [path(srcdir).relpathto(p) for p in path(srcdir).walkfiles()]
#print files
rep = tgtdir / '.upgrade_report'
try:
rpt = pickle.load(rep.open())
except:
rpt = {}
for f in files:
if ignorable(f):
continue
src = srcdir / f
tgt = tgtdir / f
if not tgt.isfile():
pr("Creating %s" % str(tgt))
tgt.write_text(src.text())
rpt[str(tgt)] = hashlib.md5(tgt.text()).hexdigest()
else:
cont = tgt.text()
sum = rpt.get(str(tgt), None)
#print sum
if sum and hashlib.md5(cont).hexdigest() == sum:
pr("%s: Unedited, installing new version" % tgt)
tgt.write_text(src.text())
rpt[str(tgt)] = hashlib.md5(tgt.text()).hexdigest()
else:
pr(' == Modified, skipping %s, diffs below == ' % tgt)
#rpt[str(tgt)] = hashlib.md5(tgt.bytes()).hexdigest()
real = showdiff(tgt,src)
pr('') # empty line
if not real:
pr("(Ok, it was identical, only upgrading checksum)")
rpt[str(tgt)] = hashlib.md5(tgt.text()).hexdigest()
else:
modded.append(tgt)
#print rpt
pickle.dump(rpt, rep.open('w'))
if modded:
print "\n\nDelete the following files manually (and rerun %upgrade)\nif you need a full upgrade:"
for m in modded:
print m |
def prepare_files(self, finder):
"""
Prepare process. Create temp directories, download and/or unpack files.
"""
from pip.index import Link
unnamed = list(self.unnamed_requirements)
reqs = list(self.requirements.values())
while reqs or unnamed:
if unnamed:
req_to_install = unnamed.pop(0)
else:
req_to_install = reqs.pop(0)
install = True
best_installed = False
not_found = None
# ############################################# #
# # Search for archive to fulfill requirement # #
# ############################################# #
if not self.ignore_installed and not req_to_install.editable:
req_to_install.check_if_exists()
if req_to_install.satisfied_by:
if self.upgrade:
if not self.force_reinstall and not req_to_install.url:
try:
url = finder.find_requirement(
req_to_install, self.upgrade)
except BestVersionAlreadyInstalled:
best_installed = True
install = False
except DistributionNotFound as exc:
not_found = exc
else:
# Avoid the need to call find_requirement again
req_to_install.url = url.url
if not best_installed:
# don't uninstall conflict if user install and
# conflict is not user install
if not (self.use_user_site
and not dist_in_usersite(
req_to_install.satisfied_by
)):
req_to_install.conflicts_with = \
req_to_install.satisfied_by
req_to_install.satisfied_by = None
else:
install = False
if req_to_install.satisfied_by:
if best_installed:
logger.info(
'Requirement already up-to-date: %s',
req_to_install,
)
else:
logger.info(
'Requirement already satisfied (use --upgrade to '
'upgrade): %s',
req_to_install,
)
if req_to_install.editable:
logger.info('Obtaining %s', req_to_install)
elif install:
if (req_to_install.url
and req_to_install.url.lower().startswith('file:')):
path = url_to_path(req_to_install.url)
logger.info('Processing %s', display_path(path))
else:
logger.info('Collecting %s', req_to_install)
with indent_log():
# ################################ #
# # vcs update or unpack archive # #
# ################################ #
is_wheel = False
if req_to_install.editable:
if req_to_install.source_dir is None:
location = req_to_install.build_location(self.src_dir)
req_to_install.source_dir = location
else:
location = req_to_install.source_dir
if not os.path.exists(self.build_dir):
_make_build_dir(self.build_dir)
req_to_install.update_editable(not self.is_download)
if self.is_download:
req_to_install.run_egg_info()
req_to_install.archive(self.download_dir)
else:
req_to_install.run_egg_info()
elif install:
# @@ if filesystem packages are not marked
# editable in a req, a non deterministic error
# occurs when the script attempts to unpack the
# build directory
# NB: This call can result in the creation of a temporary
# build directory
location = req_to_install.build_location(
self.build_dir,
)
unpack = True
url = None
# If a checkout exists, it's unwise to keep going. version
# inconsistencies are logged later, but do not fail the
# installation.
if os.path.exists(os.path.join(location, 'setup.py')):
raise PreviousBuildDirError(
"pip can't proceed with requirements '%s' due to a"
" pre-existing build directory (%s). This is "
"likely due to a previous installation that failed"
". pip is being responsible and not assuming it "
"can delete this. Please delete it and try again."
% (req_to_install, location)
)
else:
# FIXME: this won't upgrade when there's an existing
# package unpacked in `location`
if req_to_install.url is None:
if not_found:
raise not_found
url = finder.find_requirement(
req_to_install,
upgrade=self.upgrade,
)
else:
# FIXME: should req_to_install.url already be a
# link?
url = Link(req_to_install.url)
assert url
if url:
try:
if (
url.filename.endswith(wheel_ext)
and self.wheel_download_dir
):
# when doing 'pip wheel`
download_dir = self.wheel_download_dir
do_download = True
else:
download_dir = self.download_dir
do_download = self.is_download
unpack_url(
url, location, download_dir,
do_download, session=self.session,
)
except requests.HTTPError as exc:
logger.critical(
'Could not install requirement %s because '
'of error %s',
req_to_install,
exc,
)
raise InstallationError(
'Could not install requirement %s because '
'of HTTP error %s for URL %s' %
(req_to_install, exc, url)
)
else:
unpack = False
if unpack:
is_wheel = url and url.filename.endswith(wheel_ext)
if self.is_download:
req_to_install.source_dir = location
if not is_wheel:
# FIXME:https://github.com/pypa/pip/issues/1112
req_to_install.run_egg_info()
if url and url.scheme in vcs.all_schemes:
req_to_install.archive(self.download_dir)
elif is_wheel:
req_to_install.source_dir = location
req_to_install.url = url.url
else:
req_to_install.source_dir = location
req_to_install.run_egg_info()
req_to_install.assert_source_matches_version()
# req_to_install.req is only avail after unpack for URL
# pkgs repeat check_if_exists to uninstall-on-upgrade
# (#14)
if not self.ignore_installed:
req_to_install.check_if_exists()
if req_to_install.satisfied_by:
if self.upgrade or self.ignore_installed:
# don't uninstall conflict if user install and
# conflict is not user install
if not (self.use_user_site
and not dist_in_usersite(
req_to_install.satisfied_by)):
req_to_install.conflicts_with = \
req_to_install.satisfied_by
req_to_install.satisfied_by = None
else:
logger.info(
'Requirement already satisfied (use '
'--upgrade to upgrade): %s',
req_to_install,
)
install = False
# ###################### #
# # parse dependencies # #
# ###################### #
if (req_to_install.extras):
logger.debug(
"Installing extra requirements: %r",
','.join(req_to_install.extras),
)
if is_wheel:
dist = list(
pkg_resources.find_distributions(location)
)[0]
else: # sdists
if req_to_install.satisfied_by:
dist = req_to_install.satisfied_by
else:
dist = req_to_install.get_dist()
# FIXME: shouldn't be globally added:
if dist.has_metadata('dependency_links.txt'):
finder.add_dependency_links(
dist.get_metadata_lines('dependency_links.txt')
)
if not self.ignore_dependencies:
for subreq in dist.requires(
req_to_install.extras):
if self.has_requirement(
subreq.project_name):
# FIXME: check for conflict
continue
subreq = InstallRequirement(
str(subreq),
req_to_install,
isolated=self.isolated,
)
reqs.append(subreq)
self.add_requirement(subreq)
if not self.has_requirement(req_to_install.name):
# 'unnamed' requirements will get added here
self.add_requirement(req_to_install)
# cleanup tmp src
if (self.is_download or
req_to_install._temp_build_dir is not None):
self.reqs_to_cleanup.append(req_to_install)
if install:
self.successfully_downloaded.append(req_to_install) |
def cleanup_files(self):
"""Clean up files, remove builds."""
logger.debug('Cleaning up...')
with indent_log():
for req in self.reqs_to_cleanup:
req.remove_temporary_source()
if self._pip_has_created_build_dir():
logger.debug('Removing temporary dir %s...', self.build_dir)
rmtree(self.build_dir) |
def install(self, install_options, global_options=(), *args, **kwargs):
"""
Install everything in this set (after having downloaded and unpacked
the packages)
"""
to_install = [r for r in self.requirements.values()[::-1]
if not r.satisfied_by]
# DISTRIBUTE TO SETUPTOOLS UPGRADE HACK (1 of 3 parts)
# move the distribute-0.7.X wrapper to the end because it does not
# install a setuptools package. by moving it to the end, we ensure it's
# setuptools dependency is handled first, which will provide the
# setuptools package
# TODO: take this out later
distribute_req = pkg_resources.Requirement.parse("distribute>=0.7")
for req in to_install:
if (req.name == 'distribute'
and req.installed_version is not None
and req.installed_version in distribute_req):
to_install.remove(req)
to_install.append(req)
if to_install:
logger.info(
'Installing collected packages: %s',
', '.join([req.name for req in to_install]),
)
with indent_log():
for requirement in to_install:
# DISTRIBUTE TO SETUPTOOLS UPGRADE HACK (1 of 3 parts)
# when upgrading from distribute-0.6.X to the new merged
# setuptools in py2, we need to force setuptools to uninstall
# distribute. In py3, which is always using distribute, this
# conversion is already happening in distribute's
# pkg_resources. It's ok *not* to check if setuptools>=0.7
# because if someone were actually trying to ugrade from
# distribute to setuptools 0.6.X, then all this could do is
# actually help, although that upgade path was certainly never
# "supported"
# TODO: remove this later
if requirement.name == 'setuptools':
try:
# only uninstall distribute<0.7. For >=0.7, setuptools
# will also be present, and that's what we need to
# uninstall
distribute_requirement = \
pkg_resources.Requirement.parse("distribute<0.7")
existing_distribute = \
pkg_resources.get_distribution("distribute")
if existing_distribute in distribute_requirement:
requirement.conflicts_with = existing_distribute
except pkg_resources.DistributionNotFound:
# distribute wasn't installed, so nothing to do
pass
if requirement.conflicts_with:
logger.info(
'Found existing installation: %s',
requirement.conflicts_with,
)
with indent_log():
requirement.uninstall(auto_confirm=True)
try:
requirement.install(
install_options,
global_options,
*args,
**kwargs
)
except:
# if install did not succeed, rollback previous uninstall
if (requirement.conflicts_with
and not requirement.install_succeeded):
requirement.rollback_uninstall()
raise
else:
if (requirement.conflicts_with
and requirement.install_succeeded):
requirement.commit_uninstall()
requirement.remove_temporary_source()
self.successfully_installed = to_install |
def load_record(index_series_tuple, kwargs):
'''
Generates an instance of Record() from a tuple of the form (index, pandas.Series)
with associated parameters kwargs
Paremeters
----------
index_series_tuple : tuple
tuple consisting of (index, pandas.Series)
kwargs : dict
aditional arguments
Returns
-------
Record : object
'''
index_record = index_series_tuple[0]
series = index_series_tuple[1]
record = Record()
record.series = series
record.index_record = index_record
record.set_attributes(kwargs)
return record |
def build_collection(df, **kwargs):
'''
Generates a list of Record objects given a DataFrame.
Each Record instance has a series attribute which is a pandas.Series of the same attributes
in the DataFrame.
Optional data can be passed in through kwargs which will be included by the name of each object.
parameters
----------
df : pandas.DataFrame
kwargs : alternate arguments to be saved by name to the series of each object
Returns
-------
collection : list
list of Record objects where each Record represents one row from a dataframe
Examples
--------
This is how we generate a Record Collection from a DataFrame.
>>> import pandas as pd
>>> import turntable
>>>
>>> df = pd.DataFrame({'Artist':"""Michael Jackson, Pink Floyd, Whitney Houston, Meat Loaf,
Eagles, Fleetwood Mac, Bee Gees, AC/DC""".split(', '),
>>> 'Album' :"""Thriller, The Dark Side of the Moon, The Bodyguard, Bat Out of Hell,
Their Greatest Hits (1971-1975), Rumours, Saturday Night Fever, Back in Black""".split(', ')})
>>> collection = turntable.press.build_collection(df, my_favorite_record = 'nevermind')
>>> record = collection[0]
>>> print record.series
'''
print 'Generating the Record Collection...\n'
df['index_original'] = df.index
df.reset_index(drop=True, inplace=True)
if pd.__version__ >= '0.15.0':
d = df.T.to_dict(orient='series')
else:
d = df.T.to_dict(outtype='series')
collection = [load_record(item, kwargs) for item in d.items()]
return collection |
def collection_to_df(collection):
'''
Converts a collection back into a pandas DataFrame
parameters
----------
collection : list
list of Record objects where each Record represents one row from a dataframe
Returns
-------
df : pandas.DataFrame
DataFrame of length=len(collection) where each row represents one Record
'''
return pd.concat([record.series for record in collection], axis=1).T |
def spin_frame(df, method):
'''
Runs the full turntable process on a pandas DataFrame
parameters
----------
df : pandas.DataFrame
each row represents a record
method : def method(record)
function used to process each row
Returns
-------
df : pandas.DataFrame
DataFrame processed by method
Example
-------
>>> import pandas as pd
>>> import turntable
>>>
>>> df = pd.DataFrame({'Artist':"""Michael Jackson, Pink Floyd, Whitney Houston, Meat Loaf, Eagles, Fleetwood Mac, Bee Gees, AC/DC""".split(', '), 'Album':"""Thriller, The Dark Side of the Moon, The Bodyguard, Bat Out of Hell, Their Greatest Hits (1971–1975), Rumours, Saturday Night Fever, Back in Black""".split(', ')})
>>>
>>> def method(record):
>>> record.cost = 40
>>> return record
>>>
>>> turntable.press.spin_frame(df, method)
'''
collection = build_collection(df)
collection = turntable.spin.batch(collection, method)
return collection_to_df(collection) |
def set_attributes(self, kwargs):
'''
Initalizes the given argument structure as properties of the class
to be used by name in specific method execution.
Parameters
----------
kwargs : dictionary
Dictionary of extra attributes,
where keys are attributes names and values attributes values.
'''
for key, value in kwargs.items():
setattr(self, key, value) |
def subscribe(self):
"""Update our SUB socket's subscriptions."""
self.stream.setsockopt(zmq.UNSUBSCRIBE, '')
if '' in self.topics:
self.log.debug("Subscribing to: everything")
self.stream.setsockopt(zmq.SUBSCRIBE, '')
else:
for topic in self.topics:
self.log.debug("Subscribing to: %r"%(topic))
self.stream.setsockopt(zmq.SUBSCRIBE, topic) |
def _extract_level(self, topic_str):
"""Turn 'engine.0.INFO.extra' into (logging.INFO, 'engine.0.extra')"""
topics = topic_str.split('.')
for idx,t in enumerate(topics):
level = getattr(logging, t, None)
if level is not None:
break
if level is None:
level = logging.INFO
else:
topics.pop(idx)
return level, '.'.join(topics) |
def log_message(self, raw):
"""receive and parse a message, then log it."""
if len(raw) != 2 or '.' not in raw[0]:
self.log.error("Invalid log message: %s"%raw)
return
else:
topic, msg = raw
# don't newline, since log messages always newline:
topic,level_name = topic.rsplit('.',1)
level,topic = self._extract_level(topic)
if msg[-1] == '\n':
msg = msg[:-1]
self.log.log(level, "[%s] %s" % (topic, msg)) |
def mergesort(list_of_lists, key=None):
""" Perform an N-way merge operation on sorted lists.
@param list_of_lists: (really iterable of iterable) of sorted elements
(either by naturally or by C{key})
@param key: specify sort key function (like C{sort()}, C{sorted()})
Yields tuples of the form C{(item, iterator)}, where the iterator is the
built-in list iterator or something you pass in, if you pre-generate the
iterators.
This is a stable merge; complexity O(N lg N)
Examples::
>>> print list(mergesort([[1,2,3,4],
... [2,3.25,3.75,4.5,6,7],
... [2.625,3.625,6.625,9]]))
[1, 2, 2, 2.625, 3, 3.25, 3.625, 3.75, 4, 4.5, 6, 6.625, 7, 9]
# note stability
>>> print list(mergesort([[1,2,3,4],
... [2,3.25,3.75,4.5,6,7],
... [2.625,3.625,6.625,9]],
... key=int))
[1, 2, 2, 2.625, 3, 3.25, 3.75, 3.625, 4, 4.5, 6, 6.625, 7, 9]
>>> print list(mergesort([[4, 3, 2, 1],
... [7, 6, 4.5, 3.75, 3.25, 2],
... [9, 6.625, 3.625, 2.625]],
... key=lambda x: -x))
[9, 7, 6.625, 6, 4.5, 4, 3.75, 3.625, 3.25, 3, 2.625, 2, 2, 1]
"""
heap = []
for i, itr in enumerate(iter(pl) for pl in list_of_lists):
try:
item = itr.next()
if key:
toadd = (key(item), i, item, itr)
else:
toadd = (item, i, itr)
heap.append(toadd)
except StopIteration:
pass
heapq.heapify(heap)
if key:
while heap:
_, idx, item, itr = heap[0]
yield item
try:
item = itr.next()
heapq.heapreplace(heap, (key(item), idx, item, itr) )
except StopIteration:
heapq.heappop(heap)
else:
while heap:
item, idx, itr = heap[0]
yield item
try:
heapq.heapreplace(heap, (itr.next(), idx, itr))
except StopIteration:
heapq.heappop(heap) |
def remote_iterator(view,name):
"""Return an iterator on an object living on a remote engine.
"""
view.execute('it%s=iter(%s)'%(name,name), block=True)
while True:
try:
result = view.apply_sync(lambda x: x.next(), Reference('it'+name))
# This causes the StopIteration exception to be raised.
except RemoteError as e:
if e.ename == 'StopIteration':
raise StopIteration
else:
raise e
else:
yield result |
def convert_to_this_nbformat(nb, orig_version=1):
"""Convert a notebook to the v2 format.
Parameters
----------
nb : NotebookNode
The Python representation of the notebook to convert.
orig_version : int
The original version of the notebook to convert.
"""
if orig_version == 1:
newnb = new_notebook()
ws = new_worksheet()
for cell in nb.cells:
if cell.cell_type == u'code':
newcell = new_code_cell(input=cell.get('code'),prompt_number=cell.get('prompt_number'))
elif cell.cell_type == u'text':
newcell = new_text_cell(u'markdown',source=cell.get('text'))
ws.cells.append(newcell)
newnb.worksheets.append(ws)
return newnb
else:
raise ValueError('Cannot convert a notebook from v%s to v2' % orig_version) |
def get_supported_platform():
"""Return this platform's maximum compatible version.
distutils.util.get_platform() normally reports the minimum version
of Mac OS X that would be required to *use* extensions produced by
distutils. But what we want when checking compatibility is to know the
version of Mac OS X that we are *running*. To allow usage of packages that
explicitly require a newer version of Mac OS X, we must also know the
current version of the OS.
If this condition occurs for any other platform with a version in its
platform strings, this function should be extended accordingly.
"""
plat = get_build_platform(); m = macosVersionString.match(plat)
if m is not None and sys.platform == "darwin":
try:
plat = 'macosx-%s-%s' % ('.'.join(_macosx_vers()[:2]), m.group(3))
except ValueError:
pass # not Mac OS X
return plat |
def get_importer(path_item):
"""Retrieve a PEP 302 "importer" for the given path item
If there is no importer, this returns a wrapper around the builtin import
machinery. The returned importer is only cached if it was created by a
path hook.
"""
try:
importer = sys.path_importer_cache[path_item]
except KeyError:
for hook in sys.path_hooks:
try:
importer = hook(path_item)
except ImportError:
pass
else:
break
else:
importer = None
sys.path_importer_cache.setdefault(path_item,importer)
if importer is None:
try:
importer = ImpWrapper(path_item)
except ImportError:
pass
return importer |
def StringIO(*args, **kw):
"""Thunk to load the real StringIO on demand"""
global StringIO
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
return StringIO(*args,**kw) |
def parse_version(s):
"""Convert a version string to a chronologically-sortable key
This is a rough cross between distutils' StrictVersion and LooseVersion;
if you give it versions that would work with StrictVersion, then it behaves
the same; otherwise it acts like a slightly-smarter LooseVersion. It is
*possible* to create pathological version coding schemes that will fool
this parser, but they should be very rare in practice.
The returned value will be a tuple of strings. Numeric portions of the
version are padded to 8 digits so they will compare numerically, but
without relying on how numbers compare relative to strings. Dots are
dropped, but dashes are retained. Trailing zeros between alpha segments
or dashes are suppressed, so that e.g. "2.4.0" is considered the same as
"2.4". Alphanumeric parts are lower-cased.
The algorithm assumes that strings like "-" and any alpha string that
alphabetically follows "final" represents a "patch level". So, "2.4-1"
is assumed to be a branch or patch of "2.4", and therefore "2.4.1" is
considered newer than "2.4-1", which in turn is newer than "2.4".
Strings like "a", "b", "c", "alpha", "beta", "candidate" and so on (that
come before "final" alphabetically) are assumed to be pre-release versions,
so that the version "2.4" is considered newer than "2.4a1".
Finally, to handle miscellaneous cases, the strings "pre", "preview", and
"rc" are treated as if they were "c", i.e. as though they were release
candidates, and therefore are not as new as a version string that does not
contain them, and "dev" is replaced with an '@' so that it sorts lower than
than any other pre-release tag.
"""
parts = []
for part in _parse_version_parts(s.lower()):
if part.startswith('*'):
# remove trailing zeros from each series of numeric parts
while parts and parts[-1]=='00000000':
parts.pop()
parts.append(part)
return tuple(parts) |
def _override_setuptools(req):
"""Return True when distribute wants to override a setuptools dependency.
We want to override when the requirement is setuptools and the version is
a variant of 0.6.
"""
if req.project_name == 'setuptools':
if not len(req.specs):
# Just setuptools: ok
return True
for comparator, version in req.specs:
if comparator in ['==', '>=', '>']:
if '0.7' in version:
# We want some setuptools not from the 0.6 series.
return False
return True
return False |
def add(self, dist, entry=None, insert=True, replace=False):
"""Add `dist` to working set, associated with `entry`
If `entry` is unspecified, it defaults to the ``.location`` of `dist`.
On exit from this routine, `entry` is added to the end of the working
set's ``.entries`` (if it wasn't already present).
`dist` is only added to the working set if it's for a project that
doesn't already have a distribution in the set, unless `replace=True`.
If it's added, any callbacks registered with the ``subscribe()`` method
will be called.
"""
if insert:
dist.insert_on(self.entries, entry)
if entry is None:
entry = dist.location
keys = self.entry_keys.setdefault(entry,[])
keys2 = self.entry_keys.setdefault(dist.location,[])
if not replace and dist.key in self.by_key:
return # ignore hidden distros
self.by_key[dist.key] = dist
if dist.key not in keys:
keys.append(dist.key)
if dist.key not in keys2:
keys2.append(dist.key)
self._added_new(dist) |
def resolve(self, requirements, env=None, installer=None,
replacement=True, replace_conflicting=False):
"""List all distributions needed to (recursively) meet `requirements`
`requirements` must be a sequence of ``Requirement`` objects. `env`,
if supplied, should be an ``Environment`` instance. If
not supplied, it defaults to all distributions available within any
entry or distribution in the working set. `installer`, if supplied,
will be invoked with each requirement that cannot be met by an
already-installed distribution; it should return a ``Distribution`` or
``None``.
Unless `replace_conflicting=True`, raises a VersionConflict exception if
any requirements are found on the path that have the correct name but
the wrong version. Otherwise, if an `installer` is supplied it will be
invoked to obtain the correct version of the requirement and activate
it.
"""
requirements = list(requirements)[::-1] # set up the stack
processed = {} # set of processed requirements
best = {} # key -> dist
to_activate = []
while requirements:
req = requirements.pop(0) # process dependencies breadth-first
if _override_setuptools(req) and replacement:
req = Requirement.parse('distribute')
if req in processed:
# Ignore cyclic or redundant dependencies
continue
dist = best.get(req.key)
if dist is None:
# Find the best distribution and add it to the map
dist = self.by_key.get(req.key)
if dist is None or (dist not in req and replace_conflicting):
ws = self
if env is None:
if dist is None:
env = Environment(self.entries)
else:
# Use an empty environment and workingset to avoid
# any further conflicts with the conflicting
# distribution
env = Environment([])
ws = WorkingSet([])
dist = best[req.key] = env.best_match(req, ws, installer)
if dist is None:
#msg = ("The '%s' distribution was not found on this "
# "system, and is required by this application.")
#raise DistributionNotFound(msg % req)
# unfortunately, zc.buildout uses a str(err)
# to get the name of the distribution here..
raise DistributionNotFound(req)
to_activate.append(dist)
if dist not in req:
# Oops, the "best" so far conflicts with a dependency
raise VersionConflict(dist,req) # XXX put more info here
requirements.extend(dist.requires(req.extras)[::-1])
processed[req] = True
return to_activate |
def find_plugins(self,
plugin_env, full_env=None, installer=None, fallback=True
):
"""Find all activatable distributions in `plugin_env`
Example usage::
distributions, errors = working_set.find_plugins(
Environment(plugin_dirlist)
)
map(working_set.add, distributions) # add plugins+libs to sys.path
print 'Could not load', errors # display errors
The `plugin_env` should be an ``Environment`` instance that contains
only distributions that are in the project's "plugin directory" or
directories. The `full_env`, if supplied, should be an ``Environment``
contains all currently-available distributions. If `full_env` is not
supplied, one is created automatically from the ``WorkingSet`` this
method is called on, which will typically mean that every directory on
``sys.path`` will be scanned for distributions.
`installer` is a standard installer callback as used by the
``resolve()`` method. The `fallback` flag indicates whether we should
attempt to resolve older versions of a plugin if the newest version
cannot be resolved.
This method returns a 2-tuple: (`distributions`, `error_info`), where
`distributions` is a list of the distributions found in `plugin_env`
that were loadable, along with any other distributions that are needed
to resolve their dependencies. `error_info` is a dictionary mapping
unloadable plugin distributions to an exception instance describing the
error that occurred. Usually this will be a ``DistributionNotFound`` or
``VersionConflict`` instance.
"""
plugin_projects = list(plugin_env)
plugin_projects.sort() # scan project names in alphabetic order
error_info = {}
distributions = {}
if full_env is None:
env = Environment(self.entries)
env += plugin_env
else:
env = full_env + plugin_env
shadow_set = self.__class__([])
map(shadow_set.add, self) # put all our entries in shadow_set
for project_name in plugin_projects:
for dist in plugin_env[project_name]:
req = [dist.as_requirement()]
try:
resolvees = shadow_set.resolve(req, env, installer)
except ResolutionError,v:
error_info[dist] = v # save error info
if fallback:
continue # try the next older version of project
else:
break # give up on this project, keep going
else:
map(shadow_set.add, resolvees)
distributions.update(dict.fromkeys(resolvees))
# success, no need to try any more versions of this project
break
distributions = list(distributions)
distributions.sort()
return distributions, error_info |
def add(self,dist):
"""Add `dist` if we ``can_add()`` it and it isn't already added"""
if self.can_add(dist) and dist.has_version():
dists = self._distmap.setdefault(dist.key,[])
if dist not in dists:
dists.append(dist)
if dist.key in self._cache:
_sort_dists(self._cache[dist.key]) |
def get_cache_path(self, archive_name, names=()):
"""Return absolute location in cache for `archive_name` and `names`
The parent directory of the resulting path will be created if it does
not already exist. `archive_name` should be the base filename of the
enclosing egg (which may not be the name of the enclosing zipfile!),
including its ".egg" extension. `names`, if provided, should be a
sequence of path name parts "under" the egg's extraction location.
This method should only be called by resource providers that need to
obtain an extraction location, and only for names they intend to
extract, as it tracks the generated names for possible cleanup later.
"""
extract_path = self.extraction_path or get_default_cache()
target_path = os.path.join(extract_path, archive_name+'-tmp', *names)
try:
_bypass_ensure_directory(target_path)
except:
self.extraction_error()
self.cached_files[target_path] = 1
return target_path |
def parse(cls, src, dist=None):
"""Parse a single entry point from string `src`
Entry point syntax follows the form::
name = some.module:some.attr [extra1,extra2]
The entry name and module name are required, but the ``:attrs`` and
``[extras]`` parts are optional
"""
try:
attrs = extras = ()
name,value = src.split('=',1)
if '[' in value:
value,extras = value.split('[',1)
req = Requirement.parse("x["+extras)
if req.specs: raise ValueError
extras = req.extras
if ':' in value:
value,attrs = value.split(':',1)
if not MODULE(attrs.rstrip()):
raise ValueError
attrs = attrs.rstrip().split('.')
except ValueError:
raise ValueError(
"EntryPoint must be in 'name=module:attrs [extras]' format",
src
)
else:
return cls(name.strip(), value.strip(), attrs, extras, dist) |
def activate(self,path=None):
"""Ensure distribution is importable on `path` (default=sys.path)"""
if path is None: path = sys.path
self.insert_on(path)
if path is sys.path:
fixup_namespace_packages(self.location)
map(declare_namespace, self._get_metadata('namespace_packages.txt')) |
def insert_on(self, path, loc = None):
"""Insert self.location in path before its nearest parent directory"""
loc = loc or self.location
if self.project_name == 'setuptools':
try:
version = self.version
except ValueError:
version = ''
if '0.7' in version:
raise ValueError(
"A 0.7-series setuptools cannot be installed "
"with distribute. Found one at %s" % str(self.location))
if not loc:
return
if path is sys.path:
self.check_version_conflict()
nloc = _normalize_cached(loc)
bdir = os.path.dirname(nloc)
npath= map(_normalize_cached, path)
bp = None
for p, item in enumerate(npath):
if item==nloc:
break
elif item==bdir and self.precedence==EGG_DIST:
# if it's an .egg, give it precedence over its directory
path.insert(p, loc)
npath.insert(p, nloc)
break
else:
path.append(loc)
return
# p is the spot where we found or inserted loc; now remove duplicates
while 1:
try:
np = npath.index(nloc, p+1)
except ValueError:
break
else:
del npath[np], path[np]
p = np # ha!
return |
def _parsed_pkg_info(self):
"""Parse and cache metadata"""
try:
return self._pkg_info
except AttributeError:
from email.parser import Parser
self._pkg_info = Parser().parsestr(self.get_metadata(self.PKG_INFO))
return self._pkg_info |
def _compute_dependencies(self):
"""Recompute this distribution's dependencies."""
from _markerlib import compile as compile_marker
dm = self.__dep_map = {None: []}
reqs = []
# Including any condition expressions
for req in self._parsed_pkg_info.get_all('Requires-Dist') or []:
distvers, mark = self._preparse_requirement(req)
parsed = parse_requirements(distvers).next()
parsed.marker_fn = compile_marker(mark)
reqs.append(parsed)
def reqs_for_extra(extra):
for req in reqs:
if req.marker_fn(override={'extra':extra}):
yield req
common = frozenset(reqs_for_extra(None))
dm[None].extend(common)
for extra in self._parsed_pkg_info.get_all('Provides-Extra') or []:
extra = safe_extra(extra.strip())
dm[extra] = list(frozenset(reqs_for_extra(extra)) - common)
return dm |
def parse_filename(fname):
"""Parse a notebook filename.
This function takes a notebook filename and returns the notebook
format (json/py) and the notebook name. This logic can be
summarized as follows:
* notebook.ipynb -> (notebook.ipynb, notebook, json)
* notebook.json -> (notebook.json, notebook, json)
* notebook.py -> (notebook.py, notebook, py)
* notebook -> (notebook.ipynb, notebook, json)
Parameters
----------
fname : unicode
The notebook filename. The filename can use a specific filename
extention (.ipynb, .json, .py) or none, in which case .ipynb will
be assumed.
Returns
-------
(fname, name, format) : (unicode, unicode, unicode)
The filename, notebook name and format.
"""
if fname.endswith(u'.ipynb'):
format = u'json'
elif fname.endswith(u'.json'):
format = u'json'
elif fname.endswith(u'.py'):
format = u'py'
else:
fname = fname + u'.ipynb'
format = u'json'
name = fname.split('.')[0]
return fname, name, format |
def _collapse_leading_ws(header, txt):
"""
``Description`` header must preserve newlines; all others need not
"""
if header.lower() == 'description': # preserve newlines
return '\n'.join([x[8:] if x.startswith(' ' * 8) else x
for x in txt.strip().splitlines()])
else:
return ' '.join([x.strip() for x in txt.splitlines()]) |
def get_refs(self, location):
"""Return map of named refs (branches or tags) to commit hashes."""
output = call_subprocess([self.cmd, 'show-ref'],
show_stdout=False, cwd=location)
rv = {}
for line in output.strip().splitlines():
commit, ref = line.split(' ', 1)
ref = ref.strip()
ref_name = None
if ref.startswith('refs/remotes/'):
ref_name = ref[len('refs/remotes/'):]
elif ref.startswith('refs/heads/'):
ref_name = ref[len('refs/heads/'):]
elif ref.startswith('refs/tags/'):
ref_name = ref[len('refs/tags/'):]
if ref_name is not None:
rv[ref_name] = commit.strip()
return rv |
def eventFilter(self, obj, event):
""" Reimplemented to handle keyboard input and to auto-hide when the
text edit loses focus.
"""
if obj == self._text_edit:
etype = event.type()
if etype == QtCore.QEvent.KeyPress:
key, text = event.key(), event.text()
if key in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter,
QtCore.Qt.Key_Tab):
self._complete_current()
return True
elif key == QtCore.Qt.Key_Escape:
self.hide()
return True
elif key in (QtCore.Qt.Key_Up, QtCore.Qt.Key_Down,
QtCore.Qt.Key_PageUp, QtCore.Qt.Key_PageDown,
QtCore.Qt.Key_Home, QtCore.Qt.Key_End):
self.keyPressEvent(event)
return True
elif etype == QtCore.QEvent.FocusOut:
self.hide()
return super(CompletionWidget, self).eventFilter(obj, event) |
def hideEvent(self, event):
""" Reimplemented to disconnect signal handlers and event filter.
"""
super(CompletionWidget, self).hideEvent(event)
self._text_edit.cursorPositionChanged.disconnect(self._update_current)
self._text_edit.removeEventFilter(self) |
def showEvent(self, event):
""" Reimplemented to connect signal handlers and event filter.
"""
super(CompletionWidget, self).showEvent(event)
self._text_edit.cursorPositionChanged.connect(self._update_current)
self._text_edit.installEventFilter(self) |
def show_items(self, cursor, items):
""" Shows the completion widget with 'items' at the position specified
by 'cursor'.
"""
text_edit = self._text_edit
point = text_edit.cursorRect(cursor).bottomRight()
point = text_edit.mapToGlobal(point)
height = self.sizeHint().height()
screen_rect = QtGui.QApplication.desktop().availableGeometry(self)
if screen_rect.size().height() - point.y() - height < 0:
point = text_edit.mapToGlobal(text_edit.cursorRect().topRight())
point.setY(point.y() - height)
self.move(point)
self._start_position = cursor.position()
self.clear()
self.addItems(items)
self.setCurrentRow(0)
self.show() |
def _complete_current(self):
""" Perform the completion with the currently selected item.
"""
self._current_text_cursor().insertText(self.currentItem().text())
self.hide() |
def _current_text_cursor(self):
""" Returns a cursor with text between the start position and the
current position selected.
"""
cursor = self._text_edit.textCursor()
if cursor.position() >= self._start_position:
cursor.setPosition(self._start_position,
QtGui.QTextCursor.KeepAnchor)
return cursor |
def _update_current(self):
""" Updates the current item based on the current text.
"""
prefix = self._current_text_cursor().selection().toPlainText()
if prefix:
items = self.findItems(prefix, (QtCore.Qt.MatchStartsWith |
QtCore.Qt.MatchCaseSensitive))
if items:
self.setCurrentItem(items[0])
else:
self.hide()
else:
self.hide() |
def registerAdminSite(appName, excludeModels=[]):
"""Registers the models of the app with the given "appName" for the admin site"""
for model in apps.get_app_config(appName).get_models():
if model not in excludeModels:
admin.site.register(model) |
def virtual_memory():
"""System virtual memory as a namedtuple."""
mem = _psutil_mswindows.get_virtual_mem()
totphys, availphys, totpagef, availpagef, totvirt, freevirt = mem
#
total = totphys
avail = availphys
free = availphys
used = total - avail
percent = usage_percent((total - avail), total, _round=1)
return nt_virtmem_info(total, avail, percent, used, free) |
def swap_memory():
"""Swap system memory as a (total, used, free, sin, sout) tuple."""
mem = _psutil_mswindows.get_virtual_mem()
total = mem[2]
free = mem[3]
used = total - free
percent = usage_percent(used, total, _round=1)
return nt_swapmeminfo(total, used, free, percent, 0, 0) |
def get_disk_usage(path):
"""Return disk usage associated with path."""
try:
total, free = _psutil_mswindows.get_disk_usage(path)
except WindowsError:
err = sys.exc_info()[1]
if not os.path.exists(path):
raise OSError(errno.ENOENT, "No such file or directory: '%s'" % path)
raise
used = total - free
percent = usage_percent(used, total, _round=1)
return nt_diskinfo(total, used, free, percent) |
def disk_partitions(all):
"""Return disk partitions."""
rawlist = _psutil_mswindows.get_disk_partitions(all)
return [nt_partition(*x) for x in rawlist] |
def get_system_cpu_times():
"""Return system CPU times as a named tuple."""
user, system, idle = 0, 0, 0
# computes system global times summing each processor value
for cpu_time in _psutil_mswindows.get_system_cpu_times():
user += cpu_time[0]
system += cpu_time[1]
idle += cpu_time[2]
return _cputimes_ntuple(user, system, idle) |
def get_system_per_cpu_times():
"""Return system per-CPU times as a list of named tuples."""
ret = []
for cpu_t in _psutil_mswindows.get_system_cpu_times():
user, system, idle = cpu_t
item = _cputimes_ntuple(user, system, idle)
ret.append(item)
return ret |
def get_system_users():
"""Return currently connected users as a list of namedtuples."""
retlist = []
rawlist = _psutil_mswindows.get_system_users()
for item in rawlist:
user, hostname, tstamp = item
nt = nt_user(user, None, hostname, tstamp)
retlist.append(nt)
return retlist |
def system(cmd):
"""Win32 version of os.system() that works with network shares.
Note that this implementation returns None, as meant for use in IPython.
Parameters
----------
cmd : str
A command to be executed in the system shell.
Returns
-------
None : we explicitly do NOT return the subprocess status code, as this
utility is meant to be used extensively in IPython, where any return value
would trigger :func:`sys.displayhook` calls.
"""
with AvoidUNCPath() as path:
if path is not None:
cmd = '"pushd %s &&"%s' % (path, cmd)
with Win32ShellCommandController(cmd) as scc:
scc.run() |
def run(self, stdout_func = None, stdin_func = None, stderr_func = None):
"""Runs the process, using the provided functions for I/O.
The function stdin_func should return strings whenever a
character or characters become available.
The functions stdout_func and stderr_func are called whenever
something is printed to stdout or stderr, respectively.
These functions are called from different threads (but not
concurrently, because of the GIL).
"""
if stdout_func == None and stdin_func == None and stderr_func == None:
return self._run_stdio()
if stderr_func != None and self.mergeout:
raise RuntimeError("Shell command was initiated with "
"merged stdin/stdout, but a separate stderr_func "
"was provided to the run() method")
# Create a thread for each input/output handle
stdin_thread = None
threads = []
if stdin_func:
stdin_thread = threading.Thread(target=self._stdin_thread,
args=(self.hstdin, self.piProcInfo.hProcess,
stdin_func, stdout_func))
threads.append(threading.Thread(target=self._stdout_thread,
args=(self.hstdout, stdout_func)))
if not self.mergeout:
if stderr_func == None:
stderr_func = stdout_func
threads.append(threading.Thread(target=self._stdout_thread,
args=(self.hstderr, stderr_func)))
# Start the I/O threads and the process
if ResumeThread(self.piProcInfo.hThread) == 0xFFFFFFFF:
raise ctypes.WinError()
if stdin_thread is not None:
stdin_thread.start()
for thread in threads:
thread.start()
# Wait for the process to complete
if WaitForSingleObject(self.piProcInfo.hProcess, INFINITE) == \
WAIT_FAILED:
raise ctypes.WinError()
# Wait for the I/O threads to complete
for thread in threads:
thread.join()
# Wait for the stdin thread to complete
if stdin_thread is not None:
stdin_thread.join() |
def _stdin_raw_nonblock(self):
"""Use the raw Win32 handle of sys.stdin to do non-blocking reads"""
# WARNING: This is experimental, and produces inconsistent results.
# It's possible for the handle not to be appropriate for use
# with WaitForSingleObject, among other things.
handle = msvcrt.get_osfhandle(sys.stdin.fileno())
result = WaitForSingleObject(handle, 100)
if result == WAIT_FAILED:
raise ctypes.WinError()
elif result == WAIT_TIMEOUT:
print(".", end='')
return None
else:
data = ctypes.create_string_buffer(256)
bytesRead = DWORD(0)
print('?', end='')
if not ReadFile(handle, data, 256,
ctypes.byref(bytesRead), None):
raise ctypes.WinError()
# This ensures the non-blocking works with an actual console
# Not checking the error, so the processing will still work with
# other handle types
FlushConsoleInputBuffer(handle)
data = data.value
data = data.replace('\r\n', '\n')
data = data.replace('\r', '\n')
print(repr(data) + " ", end='')
return data |
def _stdin_raw_block(self):
"""Use a blocking stdin read"""
# The big problem with the blocking read is that it doesn't
# exit when it's supposed to in all contexts. An extra
# key-press may be required to trigger the exit.
try:
data = sys.stdin.read(1)
data = data.replace('\r', '\n')
return data
except WindowsError as we:
if we.winerror == ERROR_NO_DATA:
# This error occurs when the pipe is closed
return None
else:
# Otherwise let the error propagate
raise we |
def _stdout_raw(self, s):
"""Writes the string to stdout"""
print(s, end='', file=sys.stdout)
sys.stdout.flush() |
def _stderr_raw(self, s):
"""Writes the string to stdout"""
print(s, end='', file=sys.stderr)
sys.stderr.flush() |
def _run_stdio(self):
"""Runs the process using the system standard I/O.
IMPORTANT: stdin needs to be asynchronous, so the Python
sys.stdin object is not used. Instead,
msvcrt.kbhit/getwch are used asynchronously.
"""
# Disable Line and Echo mode
#lpMode = DWORD()
#handle = msvcrt.get_osfhandle(sys.stdin.fileno())
#if GetConsoleMode(handle, ctypes.byref(lpMode)):
# set_console_mode = True
# if not SetConsoleMode(handle, lpMode.value &
# ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT)):
# raise ctypes.WinError()
if self.mergeout:
return self.run(stdout_func = self._stdout_raw,
stdin_func = self._stdin_raw_block)
else:
return self.run(stdout_func = self._stdout_raw,
stdin_func = self._stdin_raw_block,
stderr_func = self._stderr_raw) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.