code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def get_review_requests(self):
"""
:calls: `GET /repos/:owner/:repo/pulls/:number/requested_reviewers <https://developer.github.com/v3/pulls/review_requests/>`_
:rtype: tuple of :class:`github.PaginatedList.PaginatedList` of :class:`github.NamedUser.NamedUser` and of :class:`github.PaginatedList... | :calls: `GET /repos/:owner/:repo/pulls/:number/requested_reviewers <https://developer.github.com/v3/pulls/review_requests/>`_
:rtype: tuple of :class:`github.PaginatedList.PaginatedList` of :class:`github.NamedUser.NamedUser` and of :class:`github.PaginatedList.PaginatedList` of :class:`github.Team.Team` |
def list_dfu_devices(*args, **kwargs):
"""Prints a lits of devices detected in DFU mode."""
devices = get_dfu_devices(*args, **kwargs)
if not devices:
print("No DFU capable devices found")
return
for device in devices:
print("Bus {} Device {:03d}: ID {:04x}:{:04x}"
... | Prints a lits of devices detected in DFU mode. |
def delete_resource(resource_name, key, identifier_fields, profile='pagerduty', subdomain=None, api_key=None):
'''
delete any pagerduty resource
Helper method for absent()
example:
delete_resource("users", key, ["id","name","email"]) # delete by id or name or email
'''
resource = ... | delete any pagerduty resource
Helper method for absent()
example:
delete_resource("users", key, ["id","name","email"]) # delete by id or name or email |
def __make_points(self, measurement, additional_tags, ts, fields):
"""
Parameters
----------
measurement : string
measurement type (e.g. monitoring, overall_meta, net_codes, proto_codes, overall_quantiles)
additional_tags : dict
custom additional tags for ... | Parameters
----------
measurement : string
measurement type (e.g. monitoring, overall_meta, net_codes, proto_codes, overall_quantiles)
additional_tags : dict
custom additional tags for this points
ts : integer
timestamp
fields : dict
... |
def reset(self):
"""
Reset the game so the grid is zeros (or default items)
"""
self.grid = [[0 for dummy_l in range(self.grid_width)] for dummy_l in range(self.grid_height)] | Reset the game so the grid is zeros (or default items) |
def stabilize(self, test_func, error, timeoutSecs=10, retryDelaySecs=0.5):
'''Repeatedly test a function waiting for it to return True.
Arguments:
test_func -- A function that will be run repeatedly
error -- A function that will be run to produce an error message
... | Repeatedly test a function waiting for it to return True.
Arguments:
test_func -- A function that will be run repeatedly
error -- A function that will be run to produce an error message
it will be called with (node, timeTakenSecs, numberOfRetries)
... |
def confirm_authorization_request(self):
"""When consumer confirm the authorization."""
server = self.server
scope = request.values.get('scope') or ''
scopes = scope.split()
credentials = dict(
client_id=request.values.get('client_id'),
redirect_uri=reques... | When consumer confirm the authorization. |
def serialize_operator_less_than(self, op):
"""
Serializer for :meth:`SpiffWorkflow.operators.NotEqual`.
Example::
<less-than>
<value>text</value>
<value><attribute>foobar</attribute></value>
</less-than>
"""
elem = etree.... | Serializer for :meth:`SpiffWorkflow.operators.NotEqual`.
Example::
<less-than>
<value>text</value>
<value><attribute>foobar</attribute></value>
</less-than> |
def GetRawDevice(path):
"""Resolves the raw device that contains the path.
Args:
path: A path to examine.
Returns:
A pathspec to read the raw device as well as the modified path to read
within the raw device. This is usually the path without the mount point.
Raises:
IOError: if the path does ... | Resolves the raw device that contains the path.
Args:
path: A path to examine.
Returns:
A pathspec to read the raw device as well as the modified path to read
within the raw device. This is usually the path without the mount point.
Raises:
IOError: if the path does not exist or some unexpected ... |
def v1_label_negative_inference(request, response,
visid_to_dbid, dbid_to_visid,
label_store, cid):
'''Return inferred negative labels.
The route for this endpoint is:
``/dossier/v1/label/<cid>/negative-inference``.
Negative labels are in... | Return inferred negative labels.
The route for this endpoint is:
``/dossier/v1/label/<cid>/negative-inference``.
Negative labels are inferred by first getting all other content ids
connected to ``cid`` through a negative label. For each directly
adjacent ``cid'``, the connected components of ``cid... |
def get_or_default(func=None, default=None):
"""
Wrapper around Django's ORM `get` functionality.
Wrap anything that raises ObjectDoesNotExist exception
and provide the default value if necessary.
`default` by default is None. `default` can be any callable,
if it is callable it will be called wh... | Wrapper around Django's ORM `get` functionality.
Wrap anything that raises ObjectDoesNotExist exception
and provide the default value if necessary.
`default` by default is None. `default` can be any callable,
if it is callable it will be called when ObjectDoesNotExist
exception will be raised. |
def _get_os(osvi = None):
"""
Determines the current operating system.
This function allows you to quickly tell apart major OS differences.
For more detailed information call L{GetVersionEx} instead.
@note:
Wine reports itself as Windows XP 32 bits
(even if the Linux host is 64 bit... | Determines the current operating system.
This function allows you to quickly tell apart major OS differences.
For more detailed information call L{GetVersionEx} instead.
@note:
Wine reports itself as Windows XP 32 bits
(even if the Linux host is 64 bits).
ReactOS may report itself ... |
def _get_event_cls(view_obj, events_map):
""" Helper function to get event class.
:param view_obj: Instance of View that processes the request.
:param events_map: Map of events from which event class should be
picked.
:returns: Found event class.
"""
request = view_obj.request
view_... | Helper function to get event class.
:param view_obj: Instance of View that processes the request.
:param events_map: Map of events from which event class should be
picked.
:returns: Found event class. |
def construct_message(self, email=None):
""" construct the email message """
# add subject, from and to
self.multipart['Subject'] = self.subject
self.multipart['From'] = self.config['EMAIL']
self.multipart['Date'] = formatdate(localtime=True)
if email is None and se... | construct the email message |
def _is_paste(keys):
"""
Return `True` when we should consider this list of keys as a paste
event. Pasted text on windows will be turned into a
`Keys.BracketedPaste` event. (It's not 100% correct, but it is probably
the best possible way to detect pasting of text and handle that
... | Return `True` when we should consider this list of keys as a paste
event. Pasted text on windows will be turned into a
`Keys.BracketedPaste` event. (It's not 100% correct, but it is probably
the best possible way to detect pasting of text and handle that
correctly.) |
def setVisible(self, state):
"""
Sets the visible state for this line edit.
:param state | <bool>
"""
super(XLineEdit, self).setVisible(state)
self.adjustStyleSheet()
self.adjustTextMargins() | Sets the visible state for this line edit.
:param state | <bool> |
def handle_failed_login(self, login_result):
"""If Two Factor Authentication (2FA/2SV) is enabled, the initial
login will fail with a predictable error. Catching this error allows us
to begin the authentication process.
Other types of errors can be treated in a similar way.
"""
... | If Two Factor Authentication (2FA/2SV) is enabled, the initial
login will fail with a predictable error. Catching this error allows us
to begin the authentication process.
Other types of errors can be treated in a similar way. |
def right_click(self, x, y, n=1, pre_dl=None, post_dl=None):
"""Right click at ``(x, y)`` on screen for ``n`` times.
at begin.
**中文文档**
在屏幕的 ``(x, y)`` 坐标处右键单击 ``n`` 次。
"""
self.delay(pre_dl)
self.m.click(x, y, 2, n)
self.delay(post_dl) | Right click at ``(x, y)`` on screen for ``n`` times.
at begin.
**中文文档**
在屏幕的 ``(x, y)`` 坐标处右键单击 ``n`` 次。 |
def check_selection(self):
"""
Check if selected text is r/w,
otherwise remove read-only parts of selection
"""
if self.current_prompt_pos is None:
self.set_cursor_position('eof')
else:
self.truncate_selection(self.current_prompt_pos) | Check if selected text is r/w,
otherwise remove read-only parts of selection |
def get_composition_query_session_for_repository(self, repository_id, proxy):
"""Gets a composition query session for the given repository.
arg: repository_id (osid.id.Id): the Id of the repository
arg proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.CompositionQuerySes... | Gets a composition query session for the given repository.
arg: repository_id (osid.id.Id): the Id of the repository
arg proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.CompositionQuerySession) - a
CompositionQuerySession
raise: NotFound - repository_i... |
def convert_bbox_to_albumentations(bbox, source_format, rows, cols, check_validity=False):
"""Convert a bounding box from a format specified in `source_format` to the format used by albumentations:
normalized coordinates of bottom-left and top-right corners of the bounding box in a form of
`[x_min, y_min, x... | Convert a bounding box from a format specified in `source_format` to the format used by albumentations:
normalized coordinates of bottom-left and top-right corners of the bounding box in a form of
`[x_min, y_min, x_max, y_max]` e.g. `[0.15, 0.27, 0.67, 0.5]`.
Args:
bbox (list): bounding box
... |
def unregister(self, token_to_remove):
"""
Unregister a filter function.
:param token_to_remove: The token as returned by :meth:`register`.
Unregister a function from the filter chain using the token returned by
:meth:`register`.
"""
for i, (_, token, _) in enum... | Unregister a filter function.
:param token_to_remove: The token as returned by :meth:`register`.
Unregister a function from the filter chain using the token returned by
:meth:`register`. |
def fromexportreg(cls, bundle, export_reg):
# type: (Bundle, ExportRegistration) -> RemoteServiceAdminEvent
"""
Creates a RemoteServiceAdminEvent object from an ExportRegistration
"""
exc = export_reg.get_exception()
if exc:
return RemoteServiceAdminEvent(
... | Creates a RemoteServiceAdminEvent object from an ExportRegistration |
def delete_intent(self,
name,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None):
"""
Deletes the specified intent.
Example:
>>> import... | Deletes the specified intent.
Example:
>>> import dialogflow_v2
>>>
>>> client = dialogflow_v2.IntentsClient()
>>>
>>> name = client.intent_path('[PROJECT]', '[INTENT]')
>>>
>>> client.delete_intent(name)
Args:
... |
def save_state(self, fname):
"""
Save the state of this node (the alpha/ksize/id/immediate neighbors)
to a cache file with the given fname.
"""
log.info("Saving state to %s", fname)
data = {
'ksize': self.ksize,
'alpha': self.alpha,
'id... | Save the state of this node (the alpha/ksize/id/immediate neighbors)
to a cache file with the given fname. |
def RgbToWebSafe(r, g, b, alt=False):
'''Convert the color from RGB to 'web safe' RGB
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
:alt:
If True, use the alternative color inste... | Convert the color from RGB to 'web safe' RGB
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
:alt:
If True, use the alternative color instead of the nearest one.
Can be used fo... |
def apply_widget_css_class(self, field_name):
"""
Applies CSS classes to widgets if available.
The method uses the `get_widget_css_class` method to determine if the widget
CSS class should be changed. If a CSS class is returned, it is appended to
the current value of the class p... | Applies CSS classes to widgets if available.
The method uses the `get_widget_css_class` method to determine if the widget
CSS class should be changed. If a CSS class is returned, it is appended to
the current value of the class property of the widget instance.
:param field_name: A fiel... |
def labels(self, include_missing=False, include_transforms_for_dims=False):
"""Gets labels for each cube's dimension.
Args
include_missing (bool): Include labels for missing values
Returns
labels (list of lists): Labels for each dimension
"""
return [
... | Gets labels for each cube's dimension.
Args
include_missing (bool): Include labels for missing values
Returns
labels (list of lists): Labels for each dimension |
def analyze_all(self, analysis_directory = None):
'''This function runs the analysis and creates the plots and summary file.'''
for analysis_set in self.analysis_sets:
self.analyze(analysis_set, analysis_directory = analysis_directory) | This function runs the analysis and creates the plots and summary file. |
def get_rate_limits(self):
"""
Returns a dict with the current rate limit information for domain
and status requests.
"""
resp, body = self.method_get("/limits")
rate_limits = body.get("limits", {}).get("rate")
ret = []
for rate_limit in rate_limits:
... | Returns a dict with the current rate limit information for domain
and status requests. |
def validate(self, skip_utf8_validation=False):
"""
validate the ABNF frame.
skip_utf8_validation: skip utf8 validation.
"""
if self.rsv1 or self.rsv2 or self.rsv3:
raise WebSocketProtocolException("rsv is not implemented, yet")
if self.opcode not in ABNF.OPC... | validate the ABNF frame.
skip_utf8_validation: skip utf8 validation. |
def normalized_energy_at_conditions(self, pH, V):
"""
Energy at an electrochemical condition, compatible with
numpy arrays for pH/V input
Args:
pH (float): pH at condition
V (float): applied potential at condition
Returns:
energy normalized b... | Energy at an electrochemical condition, compatible with
numpy arrays for pH/V input
Args:
pH (float): pH at condition
V (float): applied potential at condition
Returns:
energy normalized by number of non-O/H atoms at condition |
def create_default_units_and_dimensions():
"""
Adds the units and the dimensions reading a json file. It adds only dimensions and units that are not inside the db
It is possible adding new dimensions and units to the DB just modifiyin the json file
"""
default_units_file_location = os.path.r... | Adds the units and the dimensions reading a json file. It adds only dimensions and units that are not inside the db
It is possible adding new dimensions and units to the DB just modifiyin the json file |
def callCount(cls, spy, number): #pylint: disable=invalid-name
"""
Checking the inspector is called number times
Args: SinonSpy, number
"""
cls.__is_spy(spy)
if not (spy.callCount == number):
raise cls.failException(cls.message) | Checking the inspector is called number times
Args: SinonSpy, number |
def run(self, clock, generalLedger):
"""
Execute the activity at the current clock cycle.
:param clock: The clock containing the current execution time and
period information.
:param generalLedger: The general ledger into which to create the
transactions.
"""... | Execute the activity at the current clock cycle.
:param clock: The clock containing the current execution time and
period information.
:param generalLedger: The general ledger into which to create the
transactions. |
def _children(self):
"""Yield all direct children of this object."""
if self.declarations:
yield self.declarations
if isinstance(self.condition, CodeExpression):
yield self.condition
if self.increment:
yield self.increment
for codeobj in self.b... | Yield all direct children of this object. |
def protect(self, password=None, read_protect=False, protect_from=0):
"""Set lock bits to disable future memory modifications.
If *password* is None, all memory pages except the 16-bit
counter in page 41 are protected by setting the relevant lock
bits (note that lock bits can not be res... | Set lock bits to disable future memory modifications.
If *password* is None, all memory pages except the 16-bit
counter in page 41 are protected by setting the relevant lock
bits (note that lock bits can not be reset). If valid NDEF
management data is found in page 4, protect() also set... |
def deprecated(msg=''):
"""Deprecate decorated method."""
@decorator.decorator
def wrap(function, *args, **kwargs):
if not kwargs.pop('disable_warning', False):
warn(msg, DeprecationWarning)
return function(*args, **kwargs)
return wrap | Deprecate decorated method. |
def clear(self):
"""
Clear out the multi-frame
:return:
"""
for slot in self._slots:
slot.grid_forget()
slot.destroy()
self._slots = [] | Clear out the multi-frame
:return: |
def match_agent_id(self, agent_id, match):
"""Matches the agent identified by the given ``Id``.
arg: agent_id (osid.id.Id): the Id of the ``Agent``
arg: match (boolean): ``true`` if a positive match, ``false``
for a negative match
raise: NullArgument - ``agent_id`... | Matches the agent identified by the given ``Id``.
arg: agent_id (osid.id.Id): the Id of the ``Agent``
arg: match (boolean): ``true`` if a positive match, ``false``
for a negative match
raise: NullArgument - ``agent_id`` is ``null``
*compliance: mandatory -- This m... |
def member_create(self, params, member_id):
"""start new mongod instances as part of replica set
Args:
params - member params
member_id - member index
return member config
"""
member_config = params.get('rsParams', {})
server_id = params.pop('serv... | start new mongod instances as part of replica set
Args:
params - member params
member_id - member index
return member config |
def sync_next_id(self):
"""
Determines the highest-numbered ID in this table, and sets
the table's .next_id attribute to the next highest ID in
sequence. If the .next_id attribute is already set to a
value greater than the highest value found, then it is left
unmodified. The return value is the ID identif... | Determines the highest-numbered ID in this table, and sets
the table's .next_id attribute to the next highest ID in
sequence. If the .next_id attribute is already set to a
value greater than the highest value found, then it is left
unmodified. The return value is the ID identified by this
method. If the ta... |
def gp_ccX():
"""fit experimental data"""
inDir, outDir = getWorkDirs()
data, alldata = OrderedDict(), None
for infile in os.listdir(inDir):
# get key and import data
key = os.path.splitext(infile)[0].replace('_', '/')
data_import = np.loadtxt(open(os.path.join(inDir, infile), 'r... | fit experimental data |
def get_file_info_web(self, fname, delim='<BR>\n'):
"""
gathers info on a python program in list and formats as string
"""
txt = ''
f = mod_file.File(fname[0])
txt += '<sup>' + f.name + '</sup>' + delim
txt += '<sup>' + fname[1] + '</sup>' + delim
txt +=... | gathers info on a python program in list and formats as string |
def qurl(url, add=None, exclude=None, remove=None):
"""
Returns the url with changed parameters
"""
urlp = list(urlparse(url))
qp = parse_qsl(urlp[4])
# Add parameters
add = add if add else {}
for name, value in add.items():
if isinstance(value, (list, tuple)):
# App... | Returns the url with changed parameters |
def sigmask(self, sigsetsize=None):
"""
Gets the current sigmask. If it's blank, a new one is created (of sigsetsize).
:param sigsetsize: the size (in *bytes* of the sigmask set)
:return: the sigmask
"""
if self._sigmask is None:
if sigsetsize is not None:
... | Gets the current sigmask. If it's blank, a new one is created (of sigsetsize).
:param sigsetsize: the size (in *bytes* of the sigmask set)
:return: the sigmask |
def monitor_module(module, summary_writer,
track_data=True,
track_grad=True,
track_update=True,
track_update_ratio=False, # this is usually unnecessary
bins=51):
""" Allows for remote monitoring of a module's params and b... | Allows for remote monitoring of a module's params and buffers.
The following may be monitored:
1. Forward Values - Histograms of the values for parameter and buffer tensors
2. Gradient Values - Histograms of the gradients for parameter and buffer tensors
3. Update Values - Histograms of the change... |
def shell(filepath, wsgiapp, interpreter, models):
"""
Runs a python shell.
Usage:
$ wsgicli shell app.py app -i ipython
"""
model_base_classes = get_model_base_classes()
imported_objects = {}
if models and model_base_classes:
insert_import_path_to_sys_modules(filepath)
... | Runs a python shell.
Usage:
$ wsgicli shell app.py app -i ipython |
def _authenticated_call_geocoder(self, url, timeout=DEFAULT_SENTINEL):
"""
Wrap self._call_geocoder, handling tokens.
"""
if self.token is None or int(time()) > self.token_expiry:
self._refresh_authentication_token()
request = Request(
"&".join((url, urlen... | Wrap self._call_geocoder, handling tokens. |
def main(argv: Sequence[str] = SYS_ARGV) -> int:
"""Execute CLI commands."""
args = default_parser().parse_args(argv)
try:
seq = POPULATIONS[args.population] # type: Sequence
except KeyError:
try:
with open(args.population, 'r', encoding=args.encoding) as file_:
... | Execute CLI commands. |
def map_E_to_height(self, alat, alon, height, newheight, E):
"""Performs mapping of electric field along the magnetic field.
It is assumed that the electric field is perpendicular to B.
Parameters
==========
alat : (N,) array_like or float
Modified apex latitude
... | Performs mapping of electric field along the magnetic field.
It is assumed that the electric field is perpendicular to B.
Parameters
==========
alat : (N,) array_like or float
Modified apex latitude
alon : (N,) array_like or float
Modified apex longitude... |
def get_module_functions(modules):
"""Finds functions that do not have implemented derivatives.
Args:
modules: A list of Python modules. Functions contained in these modules
will be checked for membership in 'implemented', and if not found,
will be added to an 'unimplemented' set
implemente... | Finds functions that do not have implemented derivatives.
Args:
modules: A list of Python modules. Functions contained in these modules
will be checked for membership in 'implemented', and if not found,
will be added to an 'unimplemented' set
implemented: A Python object containing implemente... |
def iter_schemas(self, schema: Schema) -> Iterable[Tuple[str, Any]]:
"""
Build zero or more JSON schemas for a marshmallow schema.
Generates: name, schema pairs.
"""
if not schema:
return
yield self.to_tuple(schema)
for name, field in self.iter_fie... | Build zero or more JSON schemas for a marshmallow schema.
Generates: name, schema pairs. |
def get_field_label(self, field_name, field=None):
""" Return a label to display for a field """
label = None
if field is not None:
label = getattr(field, 'verbose_name', None)
if label is None:
label = getattr(field, 'name', None)
if label is None... | Return a label to display for a field |
def apply(self, q, bindings, cuts):
""" Apply a set of filters, which can be given as a set of tuples in
the form (ref, operator, value), or as a string in query form. If it
is ``None``, no filter will be applied. """
info = []
for (ref, operator, value) in self.parse(cuts):
... | Apply a set of filters, which can be given as a set of tuples in
the form (ref, operator, value), or as a string in query form. If it
is ``None``, no filter will be applied. |
def make_url_absolute(self, url, resolve_base=False):
"""
Make url absolute using previous request url as base url.
"""
if self.config['url']:
if resolve_base:
ubody = self.doc.unicode_body()
base_url = find_base_url(ubody)
if ... | Make url absolute using previous request url as base url. |
def _init_usrgos(self, goids):
"""Return user GO IDs which have GO Terms."""
usrgos = set()
goids_missing = set()
_go2obj = self.gosubdag.go2obj
for goid in goids:
if goid in _go2obj:
usrgos.add(goid)
else:
goids_missing.add... | Return user GO IDs which have GO Terms. |
def text_height(text):
"""Return the total height of the <text> and the length from the
base point to the top of the text box."""
(d1, d2, ymin, ymax) = get_dimension(text)
return (ymax - ymin, ymax) | Return the total height of the <text> and the length from the
base point to the top of the text box. |
def read_links_file(self,file_path):
'''
Read links and associated categories for specified articles
in text file seperated by a space
Args:
file_path (str): The path to text file with news article links
and category
Returns:
... | Read links and associated categories for specified articles
in text file seperated by a space
Args:
file_path (str): The path to text file with news article links
and category
Returns:
articles: Array of tuples that contains article link & ... |
def parse_keypair_lines(content, delim='|', kv_sep='='):
"""
Parses a set of entities, where each entity is a set of key-value pairs
contained all on one line. Each entity is parsed into a dictionary and
added to the list returned from this function.
"""
r = []
if content:
for row i... | Parses a set of entities, where each entity is a set of key-value pairs
contained all on one line. Each entity is parsed into a dictionary and
added to the list returned from this function. |
def render_pdf_file_to_image_files__ghostscript_png(pdf_file_name,
root_output_file_path,
res_x=150, res_y=150):
"""Use Ghostscript to render a PDF file to .png images. The root_output_file_path
is prepended... | Use Ghostscript to render a PDF file to .png images. The root_output_file_path
is prepended to all the output files, which have numbers and extensions added.
Return the command output. |
def exchange_additional_URL(self, handle, old, new):
'''
Exchange an URL in the 10320/LOC entry against another, keeping the same id
and other attributes.
:param handle: The handle to modify.
:param old: The URL to replace.
:param new: The URL to set as new URL.
... | Exchange an URL in the 10320/LOC entry against another, keeping the same id
and other attributes.
:param handle: The handle to modify.
:param old: The URL to replace.
:param new: The URL to set as new URL. |
def render(self, template=None, additional=None):
"""
Render single model to its html representation.
You may set template path in render function argument,
or model's variable named 'template_path',
or get default name: $app_label$/models/$model_name$.html
Sett... | Render single model to its html representation.
You may set template path in render function argument,
or model's variable named 'template_path',
or get default name: $app_label$/models/$model_name$.html
Settings:
* MODEL_RENDER_DEFAULT_EXTENSION
set default... |
def set_item(filename, item):
"""
Save entry to JSON file
"""
with atomic_write(os.fsencode(str(filename))) as temp_file:
with open(os.fsencode(str(filename))) as products_file:
# load the JSON data into memory
products_data = json.load(products_file)
# check if U... | Save entry to JSON file |
def _get_measure_outcome(self, qubit):
"""Simulate the outcome of measurement of a qubit.
Args:
qubit (int): the qubit to measure
Return:
tuple: pair (outcome, probability) where outcome is '0' or '1' and
probability is the probability of the returned outcom... | Simulate the outcome of measurement of a qubit.
Args:
qubit (int): the qubit to measure
Return:
tuple: pair (outcome, probability) where outcome is '0' or '1' and
probability is the probability of the returned outcome. |
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
... | Detailed list of servers |
def match(self, path):
"""Matches a fully qualified path template string.
Args:
path (str): A fully qualified path template string.
Returns:
dict: Var names to matched binding values.
Raises:
ValidationException: If path can't be matched to the temp... | Matches a fully qualified path template string.
Args:
path (str): A fully qualified path template string.
Returns:
dict: Var names to matched binding values.
Raises:
ValidationException: If path can't be matched to the template. |
def bft(self):
""" Generator that returns each element of the tree in Breadth-first order"""
queue = deque([self])
while queue:
node = queue.pop()
yield node
if hasattr(node, "childs"):
queue.extendleft(node.childs) | Generator that returns each element of the tree in Breadth-first order |
def build_subtree_strut(self, result, *args, **kwargs):
"""
Returns a dictionary in form of
{node:Resource, children:{node_id: Resource}}
:param result:
:return:
"""
return self.service.build_subtree_strut(result=result, *args, **kwargs) | Returns a dictionary in form of
{node:Resource, children:{node_id: Resource}}
:param result:
:return: |
def get_group_summary(self, group_id, **kwargs): # noqa: E501
"""Get group information. # noqa: E501
An endpoint for getting general information about the group. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/policy-groups/{group-id} -H 'Authorization: Bearer API_KEY'` # noqa: E50... | Get group information. # noqa: E501
An endpoint for getting general information about the group. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/policy-groups/{group-id} -H 'Authorization: Bearer API_KEY'` # noqa: E501
This method makes a synchronous HTTP request by default. To make... |
def load_remotes(extra_path=None, load_user=True):
"""Load the YAML remotes file, which sort of combines the Accounts file with part of the
remotes sections from the main config
:return: An `AttrDict`
"""
from os.path import getmtime
try:
remotes_file = find_config_file(REMOTES_FILE, ... | Load the YAML remotes file, which sort of combines the Accounts file with part of the
remotes sections from the main config
:return: An `AttrDict` |
def addKwdArgsToSig(sigStr, kwArgsDict):
""" Alter the passed function signature string to add the given kewords """
retval = sigStr
if len(kwArgsDict) > 0:
retval = retval.strip(' ,)') # open up the r.h.s. for more args
for k in kwArgsDict:
if retval[-1] != '(': retval += ", "
... | Alter the passed function signature string to add the given kewords |
def _generate_union(self, union_type):
"""
Emits a JSDoc @typedef for a union type.
"""
union_name = fmt_type_name(union_type)
self._emit_jsdoc_header(union_type.doc)
self.emit(' * @typedef {Object} %s' % union_name)
variant_types = []
for variant in union... | Emits a JSDoc @typedef for a union type. |
def snapshot(self, filename="tmp.png"):
"""
Take a screenshot and save it to `tmp.png` filename by default
Args:
filename: name of file where to store the screenshot
Returns:
display the screenshot
"""
if not filename:
filename = "tm... | Take a screenshot and save it to `tmp.png` filename by default
Args:
filename: name of file where to store the screenshot
Returns:
display the screenshot |
def render_field_errors(field):
"""
Render field errors as html.
"""
if field.errors:
html = """<p class="help-block">Error: {errors}</p>""".format(
errors='. '.join(field.errors)
)
return HTMLString(html)
return None | Render field errors as html. |
def detect(self, app):
"""
Given an app, run detect script on it to determine whether it can be
built with this pack. Return True/False.
"""
script = os.path.join(self.folder, 'bin', 'detect')
cmd = '%s %s' % (script, app.folder)
result = run(cmd)
return ... | Given an app, run detect script on it to determine whether it can be
built with this pack. Return True/False. |
def get_model_spec_ting(atomic_number):
"""
X_u_template[0:2] are teff, logg, vturb in km/s
X_u_template[:,3] -> onward, put atomic number
atomic_number is 6 for C, 7 for N
"""
DATA_DIR = "/Users/annaho/Data/LAMOST/Mass_And_Age"
temp = np.load("%s/X_u_template_KGh_res=1800.npz" %DATA_DIR)
... | X_u_template[0:2] are teff, logg, vturb in km/s
X_u_template[:,3] -> onward, put atomic number
atomic_number is 6 for C, 7 for N |
def event(self, *topics, **kwargs):
"""Topic callback registry.
callback func should receive two args: topic and pk, and then process
the replication job.
Note: The callback func must return True/False. When passed a list of
pks, the func should return a list of True/False with... | Topic callback registry.
callback func should receive two args: topic and pk, and then process
the replication job.
Note: The callback func must return True/False. When passed a list of
pks, the func should return a list of True/False with the same length
of pks.
:para... |
def launch_image(
# players info
player: Player,
nth_player: int,
num_players: int,
# game settings
headless: bool,
game_name: str,
map_name: str,
game_type: GameType,
game_speed: int,
timeout: Optional[int],
hide_names: bo... | :raises docker,errors.APIError
:raises DockerException |
def data_parallelism(daisy_chain_variables=True,
all_workers=False,
ps_replicas=0,
ps_job="/job:ps",
ps_gpu=0,
schedule="continuous_train_and_eval",
sync=False,
worker_gpu=1... | See data_parallelism_from_flags. |
def op(name,
data,
bucket_count=None,
display_name=None,
description=None,
collections=None):
"""Create a legacy histogram summary op.
Arguments:
name: A unique name for the generated summary node.
data: A `Tensor` of any shape. Must be castable to `float64`.
bucket_c... | Create a legacy histogram summary op.
Arguments:
name: A unique name for the generated summary node.
data: A `Tensor` of any shape. Must be castable to `float64`.
bucket_count: Optional positive `int`. The output will have this
many buckets, except in two edge cases. If there is no data, then
... |
def _wait_for_result(self):
"""Wait for the sensor to be ready for measurement."""
basetime = 0.018 if self._low_res else 0.128
sleep(basetime * (self._mtreg / 69.0) + self._delay) | Wait for the sensor to be ready for measurement. |
def del_team(self, team, sync=True):
"""
delete team from this OS instance
:param team: the team to be deleted from this OS instance
:param sync: If sync=True(default) synchronize with Ariane server. If sync=False,
add the team object on list to be removed on next save().
... | delete team from this OS instance
:param team: the team to be deleted from this OS instance
:param sync: If sync=True(default) synchronize with Ariane server. If sync=False,
add the team object on list to be removed on next save().
:return: |
def _build_id_tuple(params, spec):
"""
Builds a 2-element tuple used to identify fields by grabbing the class_
and tag from an Asn1Value class and the params dict being passed to it
:param params:
A dict of params to pass to spec
:param spec:
An Asn1Value class
:return:
... | Builds a 2-element tuple used to identify fields by grabbing the class_
and tag from an Asn1Value class and the params dict being passed to it
:param params:
A dict of params to pass to spec
:param spec:
An Asn1Value class
:return:
A 2-element integer tuple in the form (class_... |
def format_output(old_maps, new_maps):
""" This function takes the returned dict from `transform` and converts
it to the same datatype as the input.
Parameters
----------
old_maps : {FieldArray, dict}
The mapping object to add new maps to.
new_maps : dict
... | This function takes the returned dict from `transform` and converts
it to the same datatype as the input.
Parameters
----------
old_maps : {FieldArray, dict}
The mapping object to add new maps to.
new_maps : dict
A dict with key as parameter name and valu... |
def subsite_upcoming_events(context):
"""
Displays a list of all upcoming events in this site.
"""
request = context['request']
home = request.site.root_page
return {'request': request,
'events': getAllUpcomingEvents(request, home=home)} | Displays a list of all upcoming events in this site. |
def get_student_item_dict(self, anonymous_user_id=None):
"""Create a student_item_dict from our surrounding context.
See also: submissions.api for details.
Args:
anonymous_user_id(str): A unique anonymous_user_id for (user, course) pair.
Returns:
(dict): The stu... | Create a student_item_dict from our surrounding context.
See also: submissions.api for details.
Args:
anonymous_user_id(str): A unique anonymous_user_id for (user, course) pair.
Returns:
(dict): The student item associated with this XBlock instance. This
... |
def rotate(self, img):
""" Rotate image if exif says it needs it """
try:
exif = image2exif.get_exif(img)
except AttributeError:
# image format doesn't support exif
return img
orientation = exif.get('Orientation', 1)
landscape = img.h... | Rotate image if exif says it needs it |
def all_hosts(self):
"""List of hosts, passives, and arbiters known to this server."""
return set(imap(common.clean_node, itertools.chain(
self._doc.get('hosts', []),
self._doc.get('passives', []),
self._doc.get('arbiters', [])))) | List of hosts, passives, and arbiters known to this server. |
def _generate_union_class(self, ns, data_type):
# type: (ApiNamespace, Union) -> None
"""Defines a Python class that represents a union in Stone."""
self.emit(self._class_declaration_for_type(ns, data_type))
with self.indent():
self.emit('"""')
if data_type.doc:
... | Defines a Python class that represents a union in Stone. |
def aitoffImageToSphere(x, y):
"""
Inverse Hammer-Aitoff projection (deg).
"""
x = x - 360.*(x>180)
x = np.asarray(np.radians(x))
y = np.asarray(np.radians(y))
z = np.sqrt(1. - (x / 4.)**2 - (y / 2.)**2) # rad
lon = 2. * np.arctan2((2. * z**2) - 1, (z / 2.) * x)
lat = np.arcsin( y * ... | Inverse Hammer-Aitoff projection (deg). |
def sortedbyAge(self):
'''
Sorting the pop. base of the age
'''
ageAll = numpy.zeros(self.length)
for i in range(self.length):
ageAll[i] = self.Ind[i].age
ageSorted = ageAll.argsort()
return ageSorted[::-1] | Sorting the pop. base of the age |
def _print_checker_doc(checker_name, info, stream=None):
"""Helper method for print_full_documentation.
Also used by doc/exts/pylint_extensions.py.
"""
if not stream:
stream = sys.stdout
doc = info.get("doc")
module = info.get("module")
msgs = info.g... | Helper method for print_full_documentation.
Also used by doc/exts/pylint_extensions.py. |
def sort_by_ref(vcf_file, data):
"""Sort a VCF file by genome reference and position, adding contig information.
"""
out_file = "%s-prep.vcf.gz" % utils.splitext_plus(vcf_file)[0]
if not utils.file_uptodate(out_file, vcf_file):
with file_transaction(data, out_file) as tx_out_file:
he... | Sort a VCF file by genome reference and position, adding contig information. |
def do_POST(self):
"""Handles the HTTP POST request.
Attempts to interpret all HTTP POST requests as XML-RPC calls,
which are forwarded to the server's _dispatch method for handling.
"""
# Check that the path is legal
if not self.is_rpc_path_valid():
self.re... | Handles the HTTP POST request.
Attempts to interpret all HTTP POST requests as XML-RPC calls,
which are forwarded to the server's _dispatch method for handling. |
def act(self, cmd_name, params=None):
""" Run the specified command with its parameters."""
command = getattr(self, cmd_name)
if params:
command(params)
else:
command() | Run the specified command with its parameters. |
def discrete_rainbow(N=7, cmap=cm.Set1, usepreset=True, shuffle=False, \
plot=False):
"""
Return a discrete colormap and the set of colors.
modified from
<http://www.scipy.org/Cookbook/Matplotlib/ColormapTransformations>
cmap: colormap instance, eg. cm.jet.
N: Number of co... | Return a discrete colormap and the set of colors.
modified from
<http://www.scipy.org/Cookbook/Matplotlib/ColormapTransformations>
cmap: colormap instance, eg. cm.jet.
N: Number of colors.
Example
>>> x = resize(arange(100), (5,100))
>>> djet = cmap_discretize(cm.jet, 5)
>>> imshow(x,... |
def normalize_unicode(text):
"""
Normalize any unicode characters to ascii equivalent
https://docs.python.org/2/library/unicodedata.html#unicodedata.normalize
"""
if isinstance(text, six.text_type):
return unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode('utf8')
else:... | Normalize any unicode characters to ascii equivalent
https://docs.python.org/2/library/unicodedata.html#unicodedata.normalize |
def convert_tkinter_size_to_Wx(size):
"""
Converts size in characters to size in pixels
:param size: size in characters, rows
:return: size in pixels, pixels
"""
qtsize = size
if size[1] is not None and size[1] < DEFAULT_PIXEL_TO_CHARS_CUTOFF: # change from character based size to pi... | Converts size in characters to size in pixels
:param size: size in characters, rows
:return: size in pixels, pixels |
def iterate(t_table, wordlist, stanzas, schemes, rprobs, maxsteps):
"""
Iterate EM and return final probabilities
"""
data_probs = numpy.zeros(len(stanzas))
old_data_probs = None
probs = None
num_words = len(wordlist)
ctr = 0
for ctr in range(maxsteps):
logging.info("Iterati... | Iterate EM and return final probabilities |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.