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(
... | 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._... |
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.r... | 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.No... |
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_fre... | 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 =... |
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)... | 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, asy... |
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... | 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, asyn... |
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(**kwa... | 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()
... |
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_p... | 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_shi... |
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_pro... | 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_p... |
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
'''
... | .. 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 th... | 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... | 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()`.
... | 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... | 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', 'sha... | .. 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... | 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())
... | .. 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]... | 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() + comma... | 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 pa... |
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... | 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 ... |
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 ad... |
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, :... | 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... | 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, **kwa... | 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
... |
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_... | 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()... |
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(stor... | 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()
... |
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
... |
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._replac... | 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 = thr... |
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_s... | 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... |
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(s... | 按下鼠标时 |
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(ut... | 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):
r... | 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 t... |
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... | 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 <... | 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 <= 0xfffff... | 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... | 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}
... | 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:
... | 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['feat... | 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.i... | 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... | 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... | 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:
... | 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 sur... | 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 w... |
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, {
'Lo... | 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:
... | 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
... | 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:
... | 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=pa... | 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... | 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 = "... | 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"),
... | 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"),
... | 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 (... | 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_i1... | 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 sele... | 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: la... |
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:
re... | 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 t... |
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_struc... | 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 li... |
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 = uti... | 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)
... | 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
... |
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(colle... | 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()
... |
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,... | 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()
... |
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
:par... |
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... | 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(... |
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... | 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()
... |
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'],
... | *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 tes... |
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... |
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.pathfinde... | 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... | 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.