code
stringlengths 52
7.75k
| docs
stringlengths 1
5.85k
|
---|---|
def get_ips(self, instance_id):
instance = self._load_instance(instance_id)
IPs = sum(instance.networks.values(), [])
return IPs | Retrieves all IP addresses associated to a given instance.
:return: tuple (IPs) |
def is_instance_running(self, instance_id):
# Here, it's always better if we update the instance.
instance = self._load_instance(instance_id, force_reload=True)
return instance.status == 'ACTIVE' | Checks if the instance is up and running.
:param str instance_id: instance identifier
:return: bool - True if running, False otherwise |
def _load_instance(self, instance_id, force_reload=True):
if force_reload:
try:
# Remove from cache and get from server again
vm = self.nova_client.servers.get(instance_id)
except NotFound:
raise InstanceNotFoundError(
"Instance `{instance_id}` not found"
.format(instance_id=instance_id))
# update caches
self._instances[instance_id] = vm
self._cached_instances[instance_id] = vm
# if instance is known, return it
if instance_id in self._instances:
return self._instances[instance_id]
# else, check (cached) list from provider
if instance_id not in self._cached_instances:
# Refresh the cache, just in case
self._cached_instances = dict(
(vm.id, vm) for vm in self.nova_client.servers.list())
if instance_id in self._cached_instances:
inst = self._cached_instances[instance_id]
self._instances[instance_id] = inst
return inst
# If we reached this point, the instance was not found neither
# in the caches nor on the website.
raise InstanceNotFoundError(
"Instance `{instance_id}` not found"
.format(instance_id=instance_id)) | Return instance with the given id.
For performance reasons, the instance ID is first searched for in the
collection of VM instances started by ElastiCluster
(`self._instances`), then in the list of all instances known to the
cloud provider at the time of the last update
(`self._cached_instances`), and finally the cloud provider is directly
queried.
:param str instance_id: instance identifier
:param bool force_reload:
if ``True``, skip searching caches and reload instance from server
and immediately reload instance data from cloud provider
:return: py:class:`novaclient.v1_1.servers.Server` - instance
:raises: `InstanceError` is returned if the instance can't
be found in the local cache or in the cloud. |
async def post(self):
post = (await self.region._get_messages(
fromid=self._post_id, limit=1))[0]
assert post.id == self._post_id
return post | Get the message lodged.
Returns
-------
an :class:`aionationstates.ApiQuery` of :class:`aionationstates.Post` |
async def resolution(self):
resolutions = await asyncio.gather(
aionationstates.ga.resolution_at_vote,
aionationstates.sc.resolution_at_vote,
)
for resolution in resolutions:
if (resolution is not None
and resolution.name == self.resolution_name):
return resolution
raise aionationstates.NotFound | Get the resolution voted on.
Returns
-------
awaitable of :class:`aionationstates.ResolutionAtVote`
The resolution voted for.
Raises
------
aionationstates.NotFound
If the resolution has since been passed or defeated. |
async def proposal(self):
proposals = await aionationstates.wa.proposals()
for proposal in proposals:
if (proposal.name == self.proposal_name):
return proposal
raise aionationstates.NotFound | Get the proposal in question.
Actually just the first proposal with the same name, but the
chance of a collision is tiny.
Returns
-------
awaitable of :class:`aionationstates.Proposal`
The proposal submitted.
Raises
------
aionationstates.NotFound
If the proposal has since been withdrawn or promoted. |
def create_free_shipping_promotion(cls, free_shipping_promotion, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._create_free_shipping_promotion_with_http_info(free_shipping_promotion, **kwargs)
else:
(data) = cls._create_free_shipping_promotion_with_http_info(free_shipping_promotion, **kwargs)
return data | Create FreeShippingPromotion
Create a new FreeShippingPromotion
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_free_shipping_promotion(free_shipping_promotion, async=True)
>>> result = thread.get()
:param async bool
:param FreeShippingPromotion free_shipping_promotion: Attributes of freeShippingPromotion to create (required)
:return: FreeShippingPromotion
If the method is called asynchronously,
returns the request thread. |
def delete_free_shipping_promotion_by_id(cls, free_shipping_promotion_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._delete_free_shipping_promotion_by_id_with_http_info(free_shipping_promotion_id, **kwargs)
else:
(data) = cls._delete_free_shipping_promotion_by_id_with_http_info(free_shipping_promotion_id, **kwargs)
return data | Delete FreeShippingPromotion
Delete an instance of FreeShippingPromotion by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_free_shipping_promotion_by_id(free_shipping_promotion_id, async=True)
>>> result = thread.get()
:param async bool
:param str free_shipping_promotion_id: ID of freeShippingPromotion to delete. (required)
:return: None
If the method is called asynchronously,
returns the request thread. |
def get_free_shipping_promotion_by_id(cls, free_shipping_promotion_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._get_free_shipping_promotion_by_id_with_http_info(free_shipping_promotion_id, **kwargs)
else:
(data) = cls._get_free_shipping_promotion_by_id_with_http_info(free_shipping_promotion_id, **kwargs)
return data | Find FreeShippingPromotion
Return single instance of FreeShippingPromotion by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_free_shipping_promotion_by_id(free_shipping_promotion_id, async=True)
>>> result = thread.get()
:param async bool
:param str free_shipping_promotion_id: ID of freeShippingPromotion to return (required)
:return: FreeShippingPromotion
If the method is called asynchronously,
returns the request thread. |
def list_all_free_shipping_promotions(cls, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._list_all_free_shipping_promotions_with_http_info(**kwargs)
else:
(data) = cls._list_all_free_shipping_promotions_with_http_info(**kwargs)
return data | List FreeShippingPromotions
Return a list of FreeShippingPromotions
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_free_shipping_promotions(async=True)
>>> result = thread.get()
:param async bool
:param int page: page number
:param int size: page size
:param str sort: page order
:return: page[FreeShippingPromotion]
If the method is called asynchronously,
returns the request thread. |
def replace_free_shipping_promotion_by_id(cls, free_shipping_promotion_id, free_shipping_promotion, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._replace_free_shipping_promotion_by_id_with_http_info(free_shipping_promotion_id, free_shipping_promotion, **kwargs)
else:
(data) = cls._replace_free_shipping_promotion_by_id_with_http_info(free_shipping_promotion_id, free_shipping_promotion, **kwargs)
return data | Replace FreeShippingPromotion
Replace all attributes of FreeShippingPromotion
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.replace_free_shipping_promotion_by_id(free_shipping_promotion_id, free_shipping_promotion, async=True)
>>> result = thread.get()
:param async bool
:param str free_shipping_promotion_id: ID of freeShippingPromotion to replace (required)
:param FreeShippingPromotion free_shipping_promotion: Attributes of freeShippingPromotion to replace (required)
:return: FreeShippingPromotion
If the method is called asynchronously,
returns the request thread. |
def update_free_shipping_promotion_by_id(cls, free_shipping_promotion_id, free_shipping_promotion, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._update_free_shipping_promotion_by_id_with_http_info(free_shipping_promotion_id, free_shipping_promotion, **kwargs)
else:
(data) = cls._update_free_shipping_promotion_by_id_with_http_info(free_shipping_promotion_id, free_shipping_promotion, **kwargs)
return data | Update FreeShippingPromotion
Update attributes of FreeShippingPromotion
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_free_shipping_promotion_by_id(free_shipping_promotion_id, free_shipping_promotion, async=True)
>>> result = thread.get()
:param async bool
:param str free_shipping_promotion_id: ID of freeShippingPromotion to update. (required)
:param FreeShippingPromotion free_shipping_promotion: Attributes of freeShippingPromotion to update. (required)
:return: FreeShippingPromotion
If the method is called asynchronously,
returns the request thread. |
def df_routes(self, value):
'''
.. versionadded:: 0.11.3
'''
self._df_routes = value
try:
self.emit('routes-set', self._df_routes.copy())
except TypeError:
pasf df_routes(self, value):
'''
.. versionadded:: 0.11.3
'''
self._df_routes = value
try:
self.emit('routes-set', self._df_routes.copy())
except TypeError:
pass | .. versionadded:: 0.11.3 |
def append_surface(self, name, surface, alpha=1.):
'''
Append Cairo surface as new layer on top of existing layers.
Args
----
name (str) : Name of layer.
surface (cairo.ImageSurface) : Surface to render.
alpha (float) : Alpha/transparency level in the range `[0, 1]`.
'''
self.insert_surface(position=self.df_surfaces.index.shape[0],
name=name, surface=surface, alpha=alphaf append_surface(self, name, surface, alpha=1.):
'''
Append Cairo surface as new layer on top of existing layers.
Args
----
name (str) : Name of layer.
surface (cairo.ImageSurface) : Surface to render.
alpha (float) : Alpha/transparency level in the range `[0, 1]`.
'''
self.insert_surface(position=self.df_surfaces.index.shape[0],
name=name, surface=surface, alpha=alpha) | Append Cairo surface as new layer on top of existing layers.
Args
----
name (str) : Name of layer.
surface (cairo.ImageSurface) : Surface to render.
alpha (float) : Alpha/transparency level in the range `[0, 1]`. |
def remove_surface(self, name):
'''
Remove layer from rendering stack and flatten remaining layers.
Args
----
name (str) : Name of layer.
'''
self.df_surfaces.drop(name, axis=0, inplace=True)
# Order of layers may have changed after removing a layer. Trigger
# refresh of surfaces.
self.reorder_surfaces(self.df_surfaces.indexf remove_surface(self, name):
'''
Remove layer from rendering stack and flatten remaining layers.
Args
----
name (str) : Name of layer.
'''
self.df_surfaces.drop(name, axis=0, inplace=True)
# Order of layers may have changed after removing a layer. Trigger
# refresh of surfaces.
self.reorder_surfaces(self.df_surfaces.index) | Remove layer from rendering stack and flatten remaining layers.
Args
----
name (str) : Name of layer. |
def render_static_electrode_state_shapes(self):
'''
Render **static** states reported by the electrode controller.
**Static** electrode states are applied while a protocol is **running**
_or_ while **real-time** control is activated.
See also :meth:`render_electrode_shapes()`.
.. versionadded:: 0.12
'''
df_shapes = self.canvas.df_canvas_shapes.copy()
if self.electrode_states.shape[0]:
df_shapes['state'] = self.electrode_states.ix[df_shapes.id].values
else:
df_shapes['state'] = 0
df_shapes = df_shapes.loc[df_shapes.state > 0].dropna(subset=['state'])
return self.render_electrode_shapes(df_shapes=df_shapesf render_static_electrode_state_shapes(self):
'''
Render **static** states reported by the electrode controller.
**Static** electrode states are applied while a protocol is **running**
_or_ while **real-time** control is activated.
See also :meth:`render_electrode_shapes()`.
.. versionadded:: 0.12
'''
df_shapes = self.canvas.df_canvas_shapes.copy()
if self.electrode_states.shape[0]:
df_shapes['state'] = self.electrode_states.ix[df_shapes.id].values
else:
df_shapes['state'] = 0
df_shapes = df_shapes.loc[df_shapes.state > 0].dropna(subset=['state'])
return self.render_electrode_shapes(df_shapes=df_shapes) | Render **static** states reported by the electrode controller.
**Static** electrode states are applied while a protocol is **running**
_or_ while **real-time** control is activated.
See also :meth:`render_electrode_shapes()`.
.. versionadded:: 0.12 |
def render_registration(self):
'''
Render pinned points on video frame as red rectangle.
'''
surface = self.get_surface()
if self.canvas is None or self.df_canvas_corners.shape[0] == 0:
return surface
corners = self.df_canvas_corners.copy()
corners['w'] = 1
transform = self.canvas.shapes_to_canvas_transform
canvas_corners = corners.values.dot(transform.T.values).T
points_x = canvas_corners[0]
points_y = canvas_corners[1]
cairo_context = cairo.Context(surface)
cairo_context.move_to(points_x[0], points_y[0])
for x, y in zip(points_x[1:], points_y[1:]):
cairo_context.line_to(x, y)
cairo_context.line_to(points_x[0], points_y[0])
cairo_context.set_source_rgb(1, 0, 0)
cairo_context.stroke()
return surfacf render_registration(self):
'''
Render pinned points on video frame as red rectangle.
'''
surface = self.get_surface()
if self.canvas is None or self.df_canvas_corners.shape[0] == 0:
return surface
corners = self.df_canvas_corners.copy()
corners['w'] = 1
transform = self.canvas.shapes_to_canvas_transform
canvas_corners = corners.values.dot(transform.T.values).T
points_x = canvas_corners[0]
points_y = canvas_corners[1]
cairo_context = cairo.Context(surface)
cairo_context.move_to(points_x[0], points_y[0])
for x, y in zip(points_x[1:], points_y[1:]):
cairo_context.line_to(x, y)
cairo_context.line_to(points_x[0], points_y[0])
cairo_context.set_source_rgb(1, 0, 0)
cairo_context.stroke()
return surface | Render pinned points on video frame as red rectangle. |
def render(self):
'''
.. versionchanged:: 0.12
Add ``dynamic_electrode_state_shapes`` layer to show dynamic
electrode actuations.
'''
# Render each layer and update data frame with new content for each
# surface.
surface_names = ('background', 'shapes', 'connections', 'routes',
'channel_labels', 'static_electrode_state_shapes',
'dynamic_electrode_state_shapes', 'registration')
for k in surface_names:
self.set_surface(k, getattr(self, 'render_' + k)())
self.emit('surfaces-reset', self.df_surfaces)
self.cairo_surface = flatten_surfaces(self.df_surfacesf render(self):
'''
.. versionchanged:: 0.12
Add ``dynamic_electrode_state_shapes`` layer to show dynamic
electrode actuations.
'''
# Render each layer and update data frame with new content for each
# surface.
surface_names = ('background', 'shapes', 'connections', 'routes',
'channel_labels', 'static_electrode_state_shapes',
'dynamic_electrode_state_shapes', 'registration')
for k in surface_names:
self.set_surface(k, getattr(self, 'render_' + k)())
self.emit('surfaces-reset', self.df_surfaces)
self.cairo_surface = flatten_surfaces(self.df_surfaces) | .. versionchanged:: 0.12
Add ``dynamic_electrode_state_shapes`` layer to show dynamic
electrode actuations. |
def on_widget__button_press_event(self, widget, event):
'''
Called when any mouse button is pressed.
.. versionchanged:: 0.11
Do not trigger `route-electrode-added` event if `ALT` key is
pressed.
'''
if self.mode == 'register_video' and event.button == 1:
self.start_event = event.copy()
return
elif self.mode == 'control':
shape = self.canvas.find_shape(event.x, event.y)
if shape is None: return
state = event.get_state()
if event.button == 1:
# Start a new route.
self._route = Route(self.device)
self._route.append(shape)
self.last_pressed = shape
if not (state & gtk.gdk.MOD1_MASK):
# `<Alt>` key is not held down.
self.emit('route-electrode-added', shapef on_widget__button_press_event(self, widget, event):
'''
Called when any mouse button is pressed.
.. versionchanged:: 0.11
Do not trigger `route-electrode-added` event if `ALT` key is
pressed.
'''
if self.mode == 'register_video' and event.button == 1:
self.start_event = event.copy()
return
elif self.mode == 'control':
shape = self.canvas.find_shape(event.x, event.y)
if shape is None: return
state = event.get_state()
if event.button == 1:
# Start a new route.
self._route = Route(self.device)
self._route.append(shape)
self.last_pressed = shape
if not (state & gtk.gdk.MOD1_MASK):
# `<Alt>` key is not held down.
self.emit('route-electrode-added', shape) | Called when any mouse button is pressed.
.. versionchanged:: 0.11
Do not trigger `route-electrode-added` event if `ALT` key is
pressed. |
def register_global_command(self, command, title=None, group=None):
'''
.. versionadded:: 0.13
Register global command (i.e., not specific to electrode or route).
Add global command to context menu.
'''
commands = self.global_commands.setdefault(group, OrderedDict())
if title is None:
title = (command[:1].upper() + command[1:]).replace('_', ' ')
commands[command] = titlf register_global_command(self, command, title=None, group=None):
'''
.. versionadded:: 0.13
Register global command (i.e., not specific to electrode or route).
Add global command to context menu.
'''
commands = self.global_commands.setdefault(group, OrderedDict())
if title is None:
title = (command[:1].upper() + command[1:]).replace('_', ' ')
commands[command] = title | .. versionadded:: 0.13
Register global command (i.e., not specific to electrode or route).
Add global command to context menu. |
def register_electrode_command(self, command, title=None, group=None):
'''
Register electrode command.
Add electrode plugin command to context menu.
'''
commands = self.electrode_commands.setdefault(group, OrderedDict())
if title is None:
title = (command[:1].upper() + command[1:]).replace('_', ' ')
commands[command] = titlf register_electrode_command(self, command, title=None, group=None):
'''
Register electrode command.
Add electrode plugin command to context menu.
'''
commands = self.electrode_commands.setdefault(group, OrderedDict())
if title is None:
title = (command[:1].upper() + command[1:]).replace('_', ' ')
commands[command] = title | Register electrode command.
Add electrode plugin command to context menu. |
def register_route_command(self, command, title=None, group=None):
'''
Register route command.
Add route plugin command to context menu.
'''
commands = self.route_commands.setdefault(group, OrderedDict())
if title is None:
title = (command[:1].upper() + command[1:]).replace('_', ' ')
commands[command] = titlf register_route_command(self, command, title=None, group=None):
'''
Register route command.
Add route plugin command to context menu.
'''
commands = self.route_commands.setdefault(group, OrderedDict())
if title is None:
title = (command[:1].upper() + command[1:]).replace('_', ' ')
commands[command] = title | Register route command.
Add route plugin command to context menu. |
def list_all_gateways(cls, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._list_all_gateways_with_http_info(**kwargs)
else:
(data) = cls._list_all_gateways_with_http_info(**kwargs)
return data | List Gateways
Return a list of Gateways
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_gateways(async=True)
>>> result = thread.get()
:param async bool
:param int page: page number
:param int size: page size
:param str sort: page order
:return: page[Gateway]
If the method is called asynchronously,
returns the request thread. |
def list_of_dictionaries_to_mysql_inserts(
log,
datalist,
tableName):
log.debug('starting the ``list_of_dictionaries_to_mysql_inserts`` function')
if not len(datalist):
return "NO MATCH"
inserts = []
for d in datalist:
insertCommand = convert_dictionary_to_mysql_table(
log=log,
dictionary=d,
dbTableName="testing_table",
uniqueKeyList=[],
dateModified=False,
returnInsertOnly=True,
replace=True,
batchInserts=False
)
inserts.append(insertCommand)
output = ";\n".join(inserts) + ";"
log.debug('completed the ``list_of_dictionaries_to_mysql_inserts`` function')
return output | Convert a python list of dictionaries to pretty csv output
**Key Arguments:**
- ``log`` -- logger
- ``datalist`` -- a list of dictionaries
- ``tableName`` -- the name of the table to create the insert statements for
**Return:**
- ``output`` -- the mysql insert statements (as a string)
**Usage:**
.. code-block:: python
from fundamentals.files import list_of_dictionaries_to_mysql_inserts
mysqlInserts = list_of_dictionaries_to_mysql_inserts(
log=log,
datalist=dataList,
tableName="my_new_table"
)
print mysqlInserts
this output the following:
.. code-block:: plain
INSERT INTO `testing_table` (a_newKey,and_another,dateCreated,uniqueKey2,uniquekey1) VALUES ("cool" ,"super cool" ,"2016-09-14T13:17:26" ,"burgers" ,"cheese") ON DUPLICATE KEY UPDATE a_newKey="cool", and_another="super cool", dateCreated="2016-09-14T13:17:26", uniqueKey2="burgers", uniquekey1="cheese" ;
...
... |
def after(self):
d = Deferred()
self._after_deferreds.append(d)
return d.chain | Return a deferred that will fire after the request is finished.
Returns:
Deferred: a new deferred that will fire appropriately |
def after_response(self, request, fn, *args, **kwargs):
self._requests[id(request)]["callbacks"].append((fn, args, kwargs)) | Call the given callable after the given request has its response.
Arguments:
request:
the request to piggyback
fn (callable):
a callable that takes at least two arguments, the request and
the response (in that order), along with any additional
positional and keyword arguments passed to this function which
will be passed along. If the callable returns something other
than ``None``, it will be used as the new response. |
def plot_degbandshalffill():
ulim = [3.45, 5.15, 6.85, 8.55]
bands = range(1, 5)
for band, u_int in zip(bands, ulim):
name = 'Z_half_'+str(band)+'band'
dop = [0.5]
data = ssplt.calc_z(band, dop, np.arange(0, u_int, 0.1),0., name)
plt.plot(data['u_int'], data['zeta'][0, :, 0], label='$N={}$'.format(str(band)))
ssplt.label_saves('Z_half_multiorb.png') | Plot of Quasiparticle weight for degenerate
half-filled bands, showing the Mott transition |
def plot_dop(bands, int_max, dop, hund_cu, name):
data = ssplt.calc_z(bands, dop, np.arange(0, int_max, 0.1), hund_cu, name)
ssplt.plot_curves_z(data, name) | Plot of Quasiparticle weight for N degenerate bands
under selected doping shows transition only at half-fill
the rest are metallic states |
def plot_dop_phase(bands, int_max, hund_cu):
name = 'Z_dop_phase_'+str(bands)+'bands_U'+str(int_max)+'J'+str(hund_cu)
dop = np.sort(np.hstack((np.linspace(0.01,0.99,50),
np.arange(1./2./bands, 1, 1/2/bands))))
data = ssplt.calc_z(bands, dop, np.arange(0, int_max, 0.1), hund_cu, name)
ssplt.imshow_z(data, name)
ssplt.surf_z(data, name) | Phase plot of Quasiparticle weight for N degenerate bands
under doping shows transition only at interger filling
the rest are metallic states |
def create_store_credit(cls, store_credit, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._create_store_credit_with_http_info(store_credit, **kwargs)
else:
(data) = cls._create_store_credit_with_http_info(store_credit, **kwargs)
return data | Create StoreCredit
Create a new StoreCredit
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_store_credit(store_credit, async=True)
>>> result = thread.get()
:param async bool
:param StoreCredit store_credit: Attributes of storeCredit to create (required)
:return: StoreCredit
If the method is called asynchronously,
returns the request thread. |
def delete_store_credit_by_id(cls, store_credit_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._delete_store_credit_by_id_with_http_info(store_credit_id, **kwargs)
else:
(data) = cls._delete_store_credit_by_id_with_http_info(store_credit_id, **kwargs)
return data | Delete StoreCredit
Delete an instance of StoreCredit by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_store_credit_by_id(store_credit_id, async=True)
>>> result = thread.get()
:param async bool
:param str store_credit_id: ID of storeCredit to delete. (required)
:return: None
If the method is called asynchronously,
returns the request thread. |
def get_store_credit_by_id(cls, store_credit_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._get_store_credit_by_id_with_http_info(store_credit_id, **kwargs)
else:
(data) = cls._get_store_credit_by_id_with_http_info(store_credit_id, **kwargs)
return data | Find StoreCredit
Return single instance of StoreCredit by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_store_credit_by_id(store_credit_id, async=True)
>>> result = thread.get()
:param async bool
:param str store_credit_id: ID of storeCredit to return (required)
:return: StoreCredit
If the method is called asynchronously,
returns the request thread. |
def list_all_store_credits(cls, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._list_all_store_credits_with_http_info(**kwargs)
else:
(data) = cls._list_all_store_credits_with_http_info(**kwargs)
return data | List StoreCredits
Return a list of StoreCredits
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_store_credits(async=True)
>>> result = thread.get()
:param async bool
:param int page: page number
:param int size: page size
:param str sort: page order
:return: page[StoreCredit]
If the method is called asynchronously,
returns the request thread. |
def replace_store_credit_by_id(cls, store_credit_id, store_credit, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._replace_store_credit_by_id_with_http_info(store_credit_id, store_credit, **kwargs)
else:
(data) = cls._replace_store_credit_by_id_with_http_info(store_credit_id, store_credit, **kwargs)
return data | Replace StoreCredit
Replace all attributes of StoreCredit
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.replace_store_credit_by_id(store_credit_id, store_credit, async=True)
>>> result = thread.get()
:param async bool
:param str store_credit_id: ID of storeCredit to replace (required)
:param StoreCredit store_credit: Attributes of storeCredit to replace (required)
:return: StoreCredit
If the method is called asynchronously,
returns the request thread. |
def update_store_credit_by_id(cls, store_credit_id, store_credit, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._update_store_credit_by_id_with_http_info(store_credit_id, store_credit, **kwargs)
else:
(data) = cls._update_store_credit_by_id_with_http_info(store_credit_id, store_credit, **kwargs)
return data | Update StoreCredit
Update attributes of StoreCredit
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_store_credit_by_id(store_credit_id, store_credit, async=True)
>>> result = thread.get()
:param async bool
:param str store_credit_id: ID of storeCredit to update. (required)
:param StoreCredit store_credit: Attributes of storeCredit to update. (required)
:return: StoreCredit
If the method is called asynchronously,
returns the request thread. |
def on_mouse_motion(x, y, dx, dy):
mouse.x, mouse.y = x, y
mouse.move()
window.update_caption(mouse) | 当鼠标没有按下时移动的时候触发 |
def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
mouse.x, mouse.y = x, y
mouse.move() | 当鼠标按下并且移动的时候触发 |
def on_mouse_press(x, y, button, modifiers):
if button == MouseKeyCode.LEFT:
mouse.press()
elif button == MouseKeyCode.RIGHT:
mouse.right_press()
# 判断是否有图形的点击事件被触发了
shapes = list(all_shapes)
while shapes:
shape = shapes.pop()
if(shape._press and shape_clicked(shape)):
shape._press() | 按下鼠标时 |
def on_mouse_release(x, y, button, modifiers):
if button == MouseKeyCode.LEFT:
mouse.release()
elif button == MouseKeyCode.RIGHT:
mouse.right_release() | 松开鼠标时 |
def _register_extensions(self, namespace):
# Register any extension classes for this class.
extmanager = ExtensionManager(
'extensions.classes.{}'.format(namespace),
propagate_map_exceptions=True
)
if extmanager.extensions:
extmanager.map(util.register_extension_class, base=self)
# Register any extension methods for this class.
extmanager = ExtensionManager(
'extensions.methods.{}'.format(namespace),
propagate_map_exceptions=True
)
if extmanager.extensions:
extmanager.map(util.register_extension_method, base=self) | Register any extensions under the given namespace. |
def acls(self):
if self._acls is None:
self._acls = InstanceAcls(instance=self)
return self._acls | The instance bound ACLs operations layer. |
def all(self):
return self._instance._client.acls.all(self._instance.name) | Get all ACLs for this instance. |
def create(self, cidr_mask, description, **kwargs):
return self._instance._client.acls.create(
self._instance.name,
cidr_mask,
description,
**kwargs
) | Create an ACL for this instance.
See :py:meth:`Acls.create` for call signature. |
def get(self, acl):
return self._instance._client.acls.get(self._instance.name, acl) | Get the ACL specified by ID belonging to this instance.
See :py:meth:`Acls.get` for call signature. |
def is_number(num, if_bool=False):
if isinstance(num, bool):
return if_bool
elif isinstance(num, int):
return True
try:
number = float(num)
return not (isnan(number) or isinf(number))
except (TypeError, ValueError):
return False | :return: True if num is either an actual number, or an object that converts to one |
def _VarintDecoder(mask):
def DecodeVarint(buffer, pos):
result = 0
shift = 0
while 1:
if pos > len(buffer) -1:
raise NotEnoughDataException( "Not enough data to decode varint" )
b = buffer[pos]
result |= ((b & 0x7f) << shift)
pos += 1
if not (b & 0x80):
result &= mask
return (result, pos)
shift += 7
if shift >= 64:
raise _DecodeError('Too many bytes when decoding varint.')
return DecodeVarint | Return an encoder for a basic varint value (does not include tag).
Decoded values will be bitwise-anded with the given mask before being
returned, e.g. to limit them to 32 bits. The returned decoder does not
take the usual "end" parameter -- the caller is expected to do bounds checking
after the fact (often the caller can defer such checking until later). The
decoder returns a (value, new_pos) pair. |
def _SignedVarintDecoder(mask):
def DecodeVarint(buffer, pos):
result = 0
shift = 0
while 1:
if pos > len(buffer) -1:
raise NotEnoughDataException( "Not enough data to decode varint" )
b = local_ord(buffer[pos])
result |= ((b & 0x7f) << shift)
pos += 1
if not (b & 0x80):
if result > 0x7fffffffffffffff:
result -= (1 << 64)
result |= ~mask
else:
result &= mask
return (result, pos)
shift += 7
if shift >= 64:
raise _DecodeError('Too many bytes when decoding varint.')
return DecodeVarint | Like _VarintDecoder() but decodes signed values. |
def varintSize(value):
if value <= 0x7f: return 1
if value <= 0x3fff: return 2
if value <= 0x1fffff: return 3
if value <= 0xfffffff: return 4
if value <= 0x7ffffffff: return 5
if value <= 0x3ffffffffff: return 6
if value <= 0x1ffffffffffff: return 7
if value <= 0xffffffffffffff: return 8
if value <= 0x7fffffffffffffff: return 9
return 10 | Compute the size of a varint value. |
def signedVarintSize(value):
if value < 0: return 10
if value <= 0x7f: return 1
if value <= 0x3fff: return 2
if value <= 0x1fffff: return 3
if value <= 0xfffffff: return 4
if value <= 0x7ffffffff: return 5
if value <= 0x3ffffffffff: return 6
if value <= 0x1ffffffffffff: return 7
if value <= 0xffffffffffffff: return 8
if value <= 0x7fffffffffffffff: return 9
return 10 | Compute the size of a signed varint value. |
def _VarintEncoder():
local_chr = chr
def EncodeVarint(write, value):
bits = value & 0x7f
value >>= 7
while value:
write(0x80|bits)
bits = value & 0x7f
value >>= 7
return write(bits)
return EncodeVarint | Return an encoder for a basic varint value. |
def _SignedVarintEncoder():
local_chr = chr
def EncodeSignedVarint(write, value):
if value < 0:
value += (1 << 64)
bits = value & 0x7f
value >>= 7
while value:
write(0x80|bits)
bits = value & 0x7f
value >>= 7
return write(bits)
return EncodeSignedVarint | Return an encoder for a basic signed varint value. |
def match(value, query):
if type(query) in [str, int, float, type(None)]:
return value == query
elif type(query) == dict and len(query.keys()) == 1:
for op in query:
if op == "$eq": return value == query[op]
elif op == "$lt": return value < query[op]
elif op == "$lte": return value <= query[op]
elif op == "$gt": return value > query[op]
elif op == "$gte": return value >= query[op]
elif op == "$ne": return value != query[op]
elif op == "$in": return value in query[op]
elif op == "$nin": return value not in query[op]
else: GeoQLError("Not a valid query operator: " + op)
else:
raise GeoQLError("Not a valid query: " + str(query)) | Determine whether a value satisfies a query. |
def features_properties_null_remove(obj):
features = obj['features']
for i in tqdm(range(len(features))):
if 'properties' in features[i]:
properties = features[i]['properties']
features[i]['properties'] = {p:properties[p] for p in properties if properties[p] is not None}
return obj | Remove any properties of features in the collection that have
entries mapping to a null (i.e., None) value |
def features_tags_parse_str_to_dict(obj):
features = obj['features']
for i in tqdm(range(len(features))):
tags = features[i]['properties'].get('tags')
if tags is not None:
try:
tags = json.loads("{" + tags.replace("=>", ":") + "}")
except:
try:
tags = eval("{" + tags.replace("=>", ":") + "}")
except:
tags = None
if type(tags) == dict:
features[i]['properties']['tags'] = {k:tags[k] for k in tags}
elif tags is None and 'tags' in features[i]['properties']:
del features[i]['properties']['tags']
return obj | Parse tag strings of all features in the collection into a Python
dictionary, if possible. |
def features_keep_by_property(obj, query):
features_keep = []
for feature in tqdm(obj['features']):
if all([match(feature['properties'].get(prop), qry) for (prop, qry) in query.items()]):
features_keep.append(feature)
obj['features'] = features_keep
return obj | Filter all features in a collection by retaining only those that
satisfy the provided query. |
def features_keep_within_radius(obj, center, radius, units):
features_keep = []
for feature in tqdm(obj['features']):
if all([getattr(geopy.distance.vincenty((lat,lon), center), units) < radius for (lon,lat) in geojson.utils.coords(feature)]):
features_keep.append(feature)
obj['features'] = features_keep
return obj | Filter all features in a collection by retaining only those that
fall within the specified radius. |
def features_keep_using_features(obj, bounds):
# Build an R-tree index of bound features and their shapes.
bounds_shapes = [
(feature, shapely.geometry.shape(feature['geometry']))
for feature in tqdm(bounds['features'])
if feature['geometry'] is not None
]
index = rtree.index.Index()
for i in tqdm(range(len(bounds_shapes))):
(feature, shape) = bounds_shapes[i]
index.insert(i, shape.bounds)
features_keep = []
for feature in tqdm(obj['features']):
if 'geometry' in feature and 'coordinates' in feature['geometry']:
coordinates = feature['geometry']['coordinates']
if any([
shape.contains(shapely.geometry.Point(lon, lat))
for (lon, lat) in coordinates
for (feature, shape) in [bounds_shapes[i]
for i in index.nearest((lon,lat,lon,lat), 1)]
]):
features_keep.append(feature)
continue
obj['features'] = features_keep
return obj | Filter all features in a collection by retaining only those that
fall within the features in the second collection. |
def features_node_edge_graph(obj):
points = {}
features = obj['features']
for feature in tqdm(obj['features']):
for (lon, lat) in geojson.utils.coords(feature):
points.setdefault((lon, lat), 0)
points[(lon, lat)] += 1
points = [p for (p, c) in points.items() if c > 1]
features = [geojson.Point(p) for p in points]
# For each feature, split it into "edge" features
# that occur between every point.
for f in tqdm(obj['features']):
seqs = []
seq = []
for point in geojson.utils.coords(f):
if len(seq) > 0:
seq.append(point)
if point in points:
seq.append(point)
if len(seq) > 1 and seq[0] in points:
seqs.append(seq)
seq = [point]
for seq in seqs:
features.append(geojson.Feature(geometry={"coordinates":seq, "type":f['geometry']['type']}, properties=f['properties'], type=f['type']))
obj['features'] = features
return obj | Transform the features into a more graph-like structure by
appropriately splitting LineString features into two-point
"edges" that connect Point "nodes". |
def get_conn(filename):
conn = sqlite3.connect(filename)
conn.row_factory = _dict_factory
return conn | Returns new sqlite3.Connection object with _dict_factory() as row factory |
def conn_is_open(conn):
if conn is None:
return False
try:
get_table_names(conn)
return True
# # Idea taken from
# # http: // stackoverflow.com / questions / 1981392 / how - to - tell - if -python - sqlite - database - connection - or -cursor - is -closed
# conn.execute("select id from molecule limit 1")
# return True
except sqlite3.ProgrammingError as e:
# print(e)
return False | Tests sqlite3 connection, returns T/F |
def cursor_to_data_header(cursor):
n = 0
data, header = [], {}
for row in cursor:
if n == 0:
header = row.keys()
data.append(row.values())
return data, list(header) | Fetches all rows from query ("cursor") and returns a pair (data, header)
Returns: (data, header), where
- data is a [num_rows]x[num_cols] sequence of sequences;
- header is a [num_cols] list containing the field names |
def get_table_info(conn, tablename):
r = conn.execute("pragma table_info('{}')".format(tablename))
ret = TableInfo(((row["name"], row) for row in r))
return ret | Returns TableInfo object |
def find(self, **kwargs):
if len(kwargs) != 1:
raise ValueError("One and only one keyword argument accepted")
key = list(kwargs.keys())[0]
value = list(kwargs.values())[0]
ret = None
for row in self.values():
if row[key] == value:
ret = row
break
return ret | Finds row matching specific field value
Args:
**kwargs: (**only one argument accepted**) fielname=value, e.g., formula="OH"
Returns: list element or None |
def early_warning(iterable, name='this generator'):
''' This function logs an early warning that the generator is empty.
This is handy for times when you're manually playing with generators and
would appreciate the console warning you ahead of time that your generator
is now empty, instead of being surprised with a StopIteration or
GeneratorExit exception when youre trying to test something. '''
nxt = None
prev = next(iterable)
while 1:
try:
nxt = next(iterable)
except:
warning(' {} is now empty'.format(name))
yield prev
break
else:
yield prev
prev = nxf early_warning(iterable, name='this generator'):
''' This function logs an early warning that the generator is empty.
This is handy for times when you're manually playing with generators and
would appreciate the console warning you ahead of time that your generator
is now empty, instead of being surprised with a StopIteration or
GeneratorExit exception when youre trying to test something. '''
nxt = None
prev = next(iterable)
while 1:
try:
nxt = next(iterable)
except:
warning(' {} is now empty'.format(name))
yield prev
break
else:
yield prev
prev = nxt | This function logs an early warning that the generator is empty.
This is handy for times when you're manually playing with generators and
would appreciate the console warning you ahead of time that your generator
is now empty, instead of being surprised with a StopIteration or
GeneratorExit exception when youre trying to test something. |
def post(self, data, request, id):
if id:
# can't post to individual user
raise errors.MethodNotAllowed()
user = self._dict_to_model(data)
user.save()
# according to REST, return 201 and Location header
return Response(201, None, {
'Location': '%s%d' % (reverse('user'), user.pk)}) | Create a new resource using POST |
def get(self, request, id):
if id:
return self._get_one(id)
else:
return self._get_all() | Get one user or all users |
def put(self, data, request, id):
if not id:
# can't update the whole container
raise errors.MethodNotAllowed()
userdata = self._dict_to_model(data)
userdata.pk = id
try:
userdata.save(force_update=True)
except DatabaseError:
# can't udpate non-existing user
raise errors.NotFound() | Update a single user. |
def delete(self, request, id):
if not id:
# can't delete the whole container
raise errors.MethodNotAllowed()
try:
models.User.objects.get(pk=id).delete()
except models.User.DoesNotExist:
# we never had it, so it's definitely deleted
pass | Delete a single user. |
def _get_one(self, id):
try:
return self._to_dict(models.User.objects.get(pk=id))
except models.User.DoesNotExist:
raise errors.NotFound() | Get one user from db and turn into dict |
def _get_all(self):
return [self._to_dict(row) for row in models.User.objects.all()] | Get all users from db and turn into list of dicts |
def _dict_to_model(self, data):
try:
# we can do this because we have same fields
# in the representation and in the model:
user = models.User(**data)
except TypeError:
# client sent bad data
raise errors.BadRequest()
else:
return user | Create new user model instance based on the received data.
Note that the created user is not saved into database. |
def captures(self, uuid, withTitles=False):
picker = lambda x: x.get('capture', [])
return self._get((uuid,), picker, withTitles='yes' if withTitles else 'no') | Return the captures for a given uuid
optional value withTitles=yes |
def uuid(self, type, val):
picker = lambda x: x.get('uuid', x)
return self._get((type, val), picker) | Return the item-uuid for a identifier |
def search(self, q, field=None, page=None, per_page=None):
def picker(results):
if type(results['result']) == list:
return results['result']
else:
return [results['result']]
return self._get(('search',), picker, q=q, field=field, page=page, per_page=per_page) | Search across all (without field) or in specific field
(valid fields at http://www.loc.gov/standards/mods/mods-outline.html) |
def mods(self, uuid):
picker = lambda x: x.get('mods', {})
return self._get(('mods', uuid), picker) | Return a mods record for a given uuid |
def _get(self, components, picker, **params):
url = '/'.join((self.base,) + components)
headers = {"Authorization": "Token token=" + self._token}
params['page'] = params.get('page') or self.page
params['per_page'] = params.get('per_page') or self.per_page
r = requests.get(".".join([url, self.format]),
params=params,
headers=headers)
_next = self._nextify(components, picker, params)
return Result(r, picker, _next) | Generic get which handles call to api and setting of results
Return: Results object |
def convert_datetext_to_dategui(datetext, ln=None, secs=False):
assert ln is None, 'setting language is not supported'
try:
datestruct = convert_datetext_to_datestruct(datetext)
if datestruct == datestruct_default:
raise ValueError
if secs:
output_format = "d MMM Y, H:mm:ss"
else:
output_format = "d MMM Y, H:mm"
dt = datetime.fromtimestamp(time.mktime(datestruct))
return babel_format_datetime(dt, output_format)
except ValueError:
return _("N/A") | Convert: '2005-11-16 15:11:57' => '16 nov 2005, 15:11'
Or optionally with seconds:
'2005-11-16 15:11:57' => '16 nov 2005, 15:11:57'
Month is internationalized |
def get_datetext(year, month, day):
input_format = "%Y-%m-%d"
try:
datestruct = time.strptime("%i-%i-%i" % (year, month, day),
input_format)
return strftime(datetext_format, datestruct)
except:
return datetext_default | year=2005, month=11, day=16 => '2005-11-16 00:00:00 |
def get_i18n_day_name(day_nb, display='short', ln=None):
ln = default_ln(ln)
_ = gettext_set_language(ln)
if display == 'short':
days = {0: _("Sun"),
1: _("Mon"),
2: _("Tue"),
3: _("Wed"),
4: _("Thu"),
5: _("Fri"),
6: _("Sat")}
else:
days = {0: _("Sunday"),
1: _("Monday"),
2: _("Tuesday"),
3: _("Wednesday"),
4: _("Thursday"),
5: _("Friday"),
6: _("Saturday")}
return days[day_nb] | Get the string representation of a weekday, internationalized
@param day_nb: number of weekday UNIX like.
=> 0=Sunday
@param ln: language for output
@return: the string representation of the day |
def get_i18n_month_name(month_nb, display='short', ln=None):
ln = default_ln(ln)
_ = gettext_set_language(ln)
if display == 'short':
months = {0: _("Month"),
1: _("Jan"),
2: _("Feb"),
3: _("Mar"),
4: _("Apr"),
5: _("May"),
6: _("Jun"),
7: _("Jul"),
8: _("Aug"),
9: _("Sep"),
10: _("Oct"),
11: _("Nov"),
12: _("Dec")}
else:
months = {0: _("Month"),
1: _("January"),
2: _("February"),
3: _("March"),
4: _("April"),
5: _("May "), # trailing space distinguishes short/long form
6: _("June"),
7: _("July"),
8: _("August"),
9: _("September"),
10: _("October"),
11: _("November"),
12: _("December")}
return months[month_nb].strip() | Get a non-numeric representation of a month, internationalized.
@param month_nb: number of month, (1 based!)
=>1=jan,..,12=dec
@param ln: language for output
@return: the string representation of month |
def create_day_selectbox(name, selected_day=0, ln=None):
ln = default_ln(ln)
_ = gettext_set_language(ln)
out = "<select name=\"%s\">\n" % name
for i in range(0, 32):
out += " <option value=\"%i\"" % i
if (i == selected_day):
out += " selected=\"selected\""
if (i == 0):
out += ">%s</option>\n" % _("Day")
else:
out += ">%i</option>\n" % i
out += "</select>\n"
return out | Creates an HTML menu for day selection. (0..31 values).
@param name: name of the control (i.e. name of the var you'll get)
@param selected_day: preselect a day. Use 0 for the label 'Day'
@param ln: language of the menu
@return: html a string |
def create_month_selectbox(name, selected_month=0, ln=None):
ln = default_ln(ln)
out = "<select name=\"%s\">\n" % name
for i in range(0, 13):
out += "<option value=\"%i\"" % i
if (i == selected_month):
out += " selected=\"selected\""
out += ">%s</option>\n" % get_i18n_month_name(i, ln)
out += "</select>\n"
return out | Creates an HTML menu for month selection. Value of selected field is
numeric.
@param name: name of the control, your form will be sent with name=value...
@param selected_month: preselect a month. use 0 for the Label 'Month'
@param ln: language of the menu
@return: html as string |
def create_year_selectbox(name, from_year=-1, length=10, selected_year=0,
ln=None):
ln = default_ln(ln)
_ = gettext_set_language(ln)
if from_year < 0:
from_year = time.localtime()[0]
out = "<select name=\"%s\">\n" % name
out += ' <option value="0"'
if selected_year == 0:
out += ' selected="selected"'
out += ">%s</option>\n" % _("Year")
for i in range(from_year, from_year + length):
out += "<option value=\"%i\"" % i
if (i == selected_year):
out += " selected=\"selected\""
out += ">%i</option>\n" % i
out += "</select>\n"
return out | Creates an HTML menu (dropdownbox) for year selection.
@param name: name of control( i.e. name of the variable you'll get)
@param from_year: year on which to begin. if <0 assume it is current year
@param length: number of items in menu
@param selected_year: initial selected year (if in range), else: label is
selected
@param ln: language
@return: html as string |
def guess_datetime(datetime_string):
if CFG_HAS_EGENIX_DATETIME:
try:
return Parser.DateTimeFromString(datetime_string).timetuple()
except ValueError:
pass
else:
for format in (None, '%x %X', '%X %x', '%Y-%M-%dT%h:%m:%sZ'):
try:
return time.strptime(datetime_string, format)
except ValueError:
pass
raise ValueError("It is not possible to guess the datetime format of %s" %
datetime_string) | Try to guess the datetime contained in a string of unknow format.
@param datetime_string: the datetime representation.
@type datetime_string: string
@return: the guessed time.
@rtype: L{time.struct_time}
@raises ValueError: in case it's not possible to guess the time. |
def get_time_estimator(total):
t1 = time.time()
count = [0]
def estimate_needed_time(step=1):
count[0] += step
t2 = time.time()
t3 = 1.0 * (t2 - t1) / count[0] * (total - count[0])
return t3, t3 + t1
return estimate_needed_time | Given a total amount of items to compute, return a function that,
if called every time an item is computed (or every step items are computed)
will give a time estimation for how long it will take to compute the whole
set of itmes. The function will return two values: the first is the number
of seconds that are still needed to compute the whole set, the second value
is the time in the future when the operation is expected to end. |
def get_dst(date_obj):
dst = 0
if date_obj.year >= 1900:
tmp_date = time.mktime(date_obj.timetuple())
# DST is 1 so reduce time with 1 hour.
dst = time.localtime(tmp_date)[-1]
return dst | Determine if dst is locally enabled at this time |
def utc_to_localtime(
date_str,
fmt="%Y-%m-%d %H:%M:%S",
input_fmt="%Y-%m-%dT%H:%M:%SZ"):
date_struct = datetime.strptime(date_str, input_fmt)
date_struct += timedelta(hours=get_dst(date_struct))
date_struct -= timedelta(seconds=time.timezone)
return strftime(fmt, date_struct) | Convert UTC to localtime
Reference:
- (1) http://www.openarchives.org/OAI/openarchivesprotocol.html#Dates
- (2) http://www.w3.org/TR/NOTE-datetime
This function works only with dates complying with the
"Complete date plus hours, minutes and seconds" profile of
ISO 8601 defined by (2), and linked from (1).
Eg: 1994-11-05T13:15:30Z |
def njsd_all(network, ref, query, file, verbose=True):
graph, gene_set_total = util.parse_network(network)
ref_gene_expression_dict = util.parse_gene_expression(ref, mean=True)
query_gene_expression_dict = util.parse_gene_expression(query, mean=False)
maximally_ambiguous_gene_experession_dict = util.get_maximally_ambiguous_network(query_gene_expression_dict)
gene_set_present = set(query_gene_expression_dict.keys())
with open(file, 'w') as outFile:
print('nJSD_NT', 'nJSD_TA', 'tITH', sep='\t', file=outFile)
normal_to_tumor_njsd = entropy.njsd(network=graph,
ref_gene_expression_dict=ref_gene_expression_dict,
query_gene_expression_dict=query_gene_expression_dict,
gene_set=gene_set_present)
tumor_to_ambiguous_njsd = entropy.njsd(network=graph,
ref_gene_expression_dict=maximally_ambiguous_gene_experession_dict,
query_gene_expression_dict=query_gene_expression_dict,
gene_set=gene_set_present)
tITH = normal_to_tumor_njsd / (normal_to_tumor_njsd + tumor_to_ambiguous_njsd)
with open(file, 'a') as outFile:
print(normal_to_tumor_njsd, tumor_to_ambiguous_njsd, tITH, sep='\t', file=outFile)
return normal_to_tumor_njsd / (normal_to_tumor_njsd + tumor_to_ambiguous_njsd) | Compute transcriptome-wide nJSD between reference and query expression profiles.
Attribute:
network (str): File path to a network file.
ref (str): File path to a reference expression file.
query (str): File path to a query expression file. |
def create_collection(cls, collection, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._create_collection_with_http_info(collection, **kwargs)
else:
(data) = cls._create_collection_with_http_info(collection, **kwargs)
return data | Create Collection
Create a new Collection
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_collection(collection, async=True)
>>> result = thread.get()
:param async bool
:param Collection collection: Attributes of collection to create (required)
:return: Collection
If the method is called asynchronously,
returns the request thread. |
def delete_collection_by_id(cls, collection_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._delete_collection_by_id_with_http_info(collection_id, **kwargs)
else:
(data) = cls._delete_collection_by_id_with_http_info(collection_id, **kwargs)
return data | Delete Collection
Delete an instance of Collection by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_collection_by_id(collection_id, async=True)
>>> result = thread.get()
:param async bool
:param str collection_id: ID of collection to delete. (required)
:return: None
If the method is called asynchronously,
returns the request thread. |
def get_collection_by_id(cls, collection_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._get_collection_by_id_with_http_info(collection_id, **kwargs)
else:
(data) = cls._get_collection_by_id_with_http_info(collection_id, **kwargs)
return data | Find Collection
Return single instance of Collection by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_collection_by_id(collection_id, async=True)
>>> result = thread.get()
:param async bool
:param str collection_id: ID of collection to return (required)
:return: Collection
If the method is called asynchronously,
returns the request thread. |
def list_all_collections(cls, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._list_all_collections_with_http_info(**kwargs)
else:
(data) = cls._list_all_collections_with_http_info(**kwargs)
return data | List Collections
Return a list of Collections
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_collections(async=True)
>>> result = thread.get()
:param async bool
:param int page: page number
:param int size: page size
:param str sort: page order
:return: page[Collection]
If the method is called asynchronously,
returns the request thread. |
def replace_collection_by_id(cls, collection_id, collection, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._replace_collection_by_id_with_http_info(collection_id, collection, **kwargs)
else:
(data) = cls._replace_collection_by_id_with_http_info(collection_id, collection, **kwargs)
return data | Replace Collection
Replace all attributes of Collection
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.replace_collection_by_id(collection_id, collection, async=True)
>>> result = thread.get()
:param async bool
:param str collection_id: ID of collection to replace (required)
:param Collection collection: Attributes of collection to replace (required)
:return: Collection
If the method is called asynchronously,
returns the request thread. |
def update_collection_by_id(cls, collection_id, collection, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._update_collection_by_id_with_http_info(collection_id, collection, **kwargs)
else:
(data) = cls._update_collection_by_id_with_http_info(collection_id, collection, **kwargs)
return data | Update Collection
Update attributes of Collection
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_collection_by_id(collection_id, collection, async=True)
>>> result = thread.get()
:param async bool
:param str collection_id: ID of collection to update. (required)
:param Collection collection: Attributes of collection to update. (required)
:return: Collection
If the method is called asynchronously,
returns the request thread. |
def setupModule(
self):
import pymysql as ms
## VARIABLES ##
logging.config.dictConfig(yaml.load(self.loggerConfig))
log = logging.getLogger(__name__)
connDict = yaml.load(self.dbConfig)
dbConn = ms.connect(
host=connDict['host'],
user=connDict['user'],
passwd=connDict['password'],
db=connDict['db'],
use_unicode=True,
charset='utf8',
local_infile=1,
client_flag=ms.constants.CLIENT.MULTI_STATEMENTS,
connect_timeout=3600
)
dbConn.autocommit(True)
return log, dbConn, self.pathToInputDir, self.pathToOutputDir | *The setupModule method*
**Return:**
- ``log`` -- a logger
- ``dbConn`` -- a database connection to a test database (details from yaml settings file)
- ``pathToInputDir`` -- path to modules own test input directory
- ``pathToOutputDir`` -- path to modules own test output directory |
def _handle_call(self, actual_call, stubbed_call):
self._actual_calls.append(actual_call)
use_call = stubbed_call or actual_call
return use_call.return_value | Extends Stub call handling behavior to be callable by default. |
def formatted_args(self):
arg_reprs = list(map(repr, self.args))
kwarg_reprs = ['%s=%s' % (k, repr(v)) for k, v in self.kwargs.items()]
return '(%s)' % ', '.join(arg_reprs + kwarg_reprs) | Format call arguments as a string.
This is used to make test failure messages more helpful by referring
to calls using a string that matches how they were, or should have been
called.
>>> call = Call('arg1', 'arg2', kwarg='kwarg')
>>> call.formatted_args
"('arg1', 'arg2', kwarg='kwarg')" |
def passing(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
return self | Assign expected call args/kwargs to this call.
Returns `self` for the common case of chaining a call to `Call.returns`
>>> Call().passing('foo', bar='baz')
<Call args=('foo',) kwargs={'bar': 'baz'}> |
def check(self):
#for path in self.path.values():
# if not os.path.exists(path):
# raise RuntimeError("File '{}' is missing".format(path))
for tool in ('cd-hit', 'prank', 'hmmbuild', 'hmmpress', 'hmmscan', 'phmmer', 'mafft', 'meme'):
if not self.pathfinder.exists(tool):
raise RuntimeError("Dependency {} is missing".format(tool)) | Check if data and third party tools are available
:raises: RuntimeError |
def generate_non_rabs(self):
logging.info('Building non-Rab DB')
run_cmd([self.pathfinder['cd-hit'], '-i', self.path['non_rab_db'], '-o', self.output['non_rab_db'],
'-d', '100', '-c', str(config['param']['non_rab_db_identity_threshold']), '-g', '1', '-T', self.cpu])
os.remove(self.output['non_rab_db'] + '.clstr') | Shrink the non-Rab DB size by reducing sequence redundancy. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.