code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|
def json_schema(self, schema_id=None, is_main_schema=True):
Schema = self.__class__
s = self._schema
i = self._ignore_extra_keys
flavor = _priority(s)
if flavor != DICT and is_main_schema:
raise ValueError("The main schema must be a dict.")
if flavo... | Generate a draft-07 JSON schema dict representing the Schema.
This method can only be called when the Schema's value is a dict.
This method must be called with a schema_id. Calling it without one
is used in a recursive context for sub schemas. |
def getOr(subject, predicate, *args, **kwargs):
if (subject, predicate, None) in get_graph():
return Metadata(node=get_graph().objects(subject, predicate).__next__())
return Metadata(*args, **kwargs) | Retrieve a metadata node or generate a new one
:param subject: Subject to which the metadata node should be connected
:param predicate: Predicate by which the metadata node should be connected
:return: Metadata for given node
:rtype: Metadata |
def pop(self, *args):
value = list.pop(self, *args)
index = self._dict.pop(value.id)
if len(args) == 0 or args == [-1]:
return value
_dict = self._dict
for i, j in iteritems(_dict):
if j > index:
_dict[i] = j - ... | remove and return item at index (default last). |
def delete_disk(kwargs=None, conn=None, call=None):
if call != :
raise SaltCloudSystemExit(
)
if kwargs is None:
kwargs = {}
if not in kwargs:
raise SaltCloudSystemExit()
if not conn:
conn = get_conn()
try:
data = conn.delete_dis... | .. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True |
def slices(self):
return (slice(self.iymin, self.iymax), slice(self.ixmin, self.ixmax)) | The bounding box as a tuple of `slice` objects.
The slice tuple is in numpy axis order (i.e. ``(y, x)``) and
therefore can be used to slice numpy arrays. |
def get_installed_classes(cls):
installed_classes = {}
for entry_point in pkg_resources.iter_entry_points(cls.entry_point):
try:
plugin = entry_point.load()
except ImportError as e:
logger.error(
"Could not load plugin ... | Iterates over installed plugins associated with the `entry_point` and
returns a dictionary of viable ones keyed off of their names.
A viable installed plugin is one that is both loadable *and* a subclass
of the Pluggable subclass in question. |
def configKeyButtons( self, enableButtons = [], bounceTime = DEF_BOUNCE_TIME_NORMAL, pullUpDown = GPIO.PUD_UP, event = GPIO.BOTH ):
for key in enableButtons:
self.setKeyButton( key["id"], key["callback"], bounceTime, pullUpDown, event )
pass | !
\~english
Config multi key buttons IO and event on same time
@param enableButtons: an array of key button configs. eg. <br>
[{ "id":BUTTON_ACT_A, "callback": aCallbackFun }, ... ]
@param bounceTime: Default set to DEF_BOUNCE_TIME_NORMAL
@param pullUpDown: Defau... |
def remove_all_listeners(self, event=None):
if event is not None:
self._registered_events[event] = OrderedDict()
else:
self._registered_events = defaultdict(OrderedDict) | Remove all functions for all events, or one event if one is specifed.
:param event: Optional event you wish to remove all functions from |
def proc_polyline(self, tokens):
pts = [(p["x"], p["y"]) for p in tokens["points"]]
component = Polyline(pen=self.pen, points=pts)
return component | Returns the components of a polyline. |
def set_wallpaper(image):
desktop_env = system.get_name()
if desktop_env in [, , , , ]:
uri = % image
SCHEMA =
KEY =
if desktop_env == :
uri = image
SCHEMA =
KEY =
try:
from gi.repository import Gio
gsettings = Gio.Settings.new(SCHEMA)
gsettings.set_string(KEY, uri)
except ... | Set the desktop wallpaper.
Sets the desktop wallpaper to an image.
Args:
image (str): The path to the image to be set as wallpaper. |
def list_vnets(access_token, subscription_id):
endpoint = .join([get_rm_endpoint(),
, subscription_id,
,
, NETWORK_API])
return do_get(endpoint, access_token) | List the VNETs in a subscription .
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
Returns:
HTTP response. JSON body of VNets list with properties. |
def get_resource_area_by_host(self, area_id, host_id):
route_values = {}
if area_id is not None:
route_values[] = self._serialize.url(, area_id, )
query_parameters = {}
if host_id is not None:
query_parameters[] = self._serialize.query(, host_id, )
... | GetResourceAreaByHost.
[Preview API]
:param str area_id:
:param str host_id:
:rtype: :class:`<ResourceAreaInfo> <azure.devops.v5_0.location.models.ResourceAreaInfo>` |
def do_quit(self, _: argparse.Namespace) -> bool:
self._should_quit = True
return self._STOP_AND_EXIT | Exit this application |
def cached(cls, timeout=60, cache_none=False):
return CachedModel(cls=cls, timeout=timeout, cache_none=cache_none) | Cache queries
:param timeout: cache timeout
:param cache_none: cache None result
Usage::
>>> Model.cached(60).query({...}) |
def setCamera(self, camera_name, bit_depth=16):
self.coeffs[] = camera_name
self.coeffs[] = bit_depth | Args:
camera_name (str): Name of the camera
bit_depth (int): depth (bit) of the camera sensor |
def _cache_lookup(word, data_dir, native=False):
trans_dir = "translations"
if native:
trans_dir += "_native"
logger.debug("Cache lookup: %s", word)
filename = data_dir.joinpath(trans_dir, "{}.html".format(word))
if filename.is_file():
with open(filename, mode="r") as f:
... | Checks if word is in cache.
Parameters
----------
word : str
Word to check in cache.
data_dir : pathlib.Path
Cache directory location.
Returns
-------
translation : str or None
Translation of given word. |
def less_than_obs_constraints(self):
obs = self.observation_data
lt_obs = obs.loc[obs.apply(lambda x: self._is_less_const(x.obgnme) \
and x.weight != 0.0,axis=1),"obsnme"]
return lt_obs | get the names of the observations that
are listed as less than inequality constraints. Zero-
weighted obs are skipped
Returns
-------
pandas.Series : obsnme of obseravtions that are non-zero weighted
less than constraints |
def get_review_id(self, id_):
return _get_request(_REVIEW_ID.format(c_api=_C_API_BEGINNING,
api=_API_VERSION,
id_=id_,
at=sel... | Get a particular review id, independent from the user_id and
startup_id |
def find(self, obj, filter_to_class=Ingredient, constructor=None):
if callable(constructor):
obj = constructor(obj, shelf=self)
if isinstance(obj, basestring):
set_descending = obj.startswith()
if set_descending:
obj = obj[1:]
if... | Find an Ingredient, optionally using the shelf.
:param obj: A string or Ingredient
:param filter_to_class: The Ingredient subclass that obj must be an
instance of
:param constructor: An optional callable for building Ingredients
from obj
:return: An Ingredient of subcl... |
def subdevicenames(self) -> Tuple[str, ...]:
self: NetCDFVariableBase
return tuple(self.sequences.keys()) | A |tuple| containing the device names. |
def query_source(self, source):
return self._get_repo_filter(Layer.objects).filter(url=source) | Query by source |
def migrate(move_data=True, update_alias=True):
next_index = PATTERN.replace(, datetime.now().strftime())
es = connections.get_connection()
es.indices.create(index=next_index)
if move_data:
es.reindex(
body={"source": {"index": ALIAS}, "dest": {"index"... | Upgrade function that creates a new index for the data. Optionally it also can
(and by default will) reindex previous copy of the data into the new index
(specify ``move_data=False`` to skip this step) and update the alias to
point to the latest index (set ``update_alias=False`` to skip).
Note that whi... |
def platform_information(_linux_distribution=None):
linux_distribution = _linux_distribution or platform.linux_distribution
distro, release, codename = linux_distribution()
if not distro:
distro, release, codename = parse_os_release()
if not codename and in distro.lower():
debian... | detect platform information from remote host |
def update_remote_archive(self, save_uri, timeout=-1):
return self._client.update_with_zero_body(uri=save_uri, timeout=timeout) | Saves a backup of the appliance to a previously-configured remote location.
Args:
save_uri (dict): The URI for saving the backup to a previously configured location.
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not abort the operatio... |
def write_frames(filename, frames, compression=257, compression_level=6):
from LDAStools import frameCPP
stream = open_gwf(filename, )
if isinstance(frames, frameCPP.FrameH):
frames = [frames]
for frame in frames:
stream.WriteFrame(frame, compression, compression_level) | Write a list of frame objects to a file
**Requires:** |LDAStools.frameCPP|_
Parameters
----------
filename : `str`
path to write into
frames : `list` of `LDAStools.frameCPP.FrameH`
list of frames to write into file
compression : `int`, optional
enum value for compress... |
def spell(self, word: str) -> List[str]:
if not word:
return ""
candidates = (
self.known([word])
or self.known(_edits1(word))
or self.known(_edits2(word))
or [word]
)
candidates.sort(key=self.freq, reverse=True)
... | Return a list of possible words, according to edit distance of 1 and 2,
sorted by frequency of word occurrance in the spelling dictionary
:param str word: A word to check its spelling |
def getPlainText(self, identify=None):
frags = getattr(self, , None)
if frags:
plains = []
for frag in frags:
if hasattr(frag, ):
plains.append(frag.text)
return .join(plains)
elif identify:
text = geta... | Convenience function for templates which want access
to the raw text, without XML tags. |
def get_subtree(self, name):
r
if self._validate_node_name(name):
raise RuntimeError("Argument `name` is not valid")
self._node_in_tree(name)
return self._get_subtree(name) | r"""
Get all node names in a sub-tree.
:param name: Sub-tree root node name
:type name: :ref:`NodeName`
:rtype: list of :ref:`NodeName`
:raises:
* RuntimeError (Argument \`name\` is not valid)
* RuntimeError (Node *[name]* not in tree)
Using the sa... |
def filename(self):
if self._filename:
return self._filename
else:
with tempfile.NamedTemporaryFile(delete=False) as f:
f.write(self._bytes)
return f.name | Returns the provided data as a file location. |
def apply_to_segmentlist(self, seglist):
for i, seg in enumerate(seglist):
seglist[i] = seg.__class__(seg[0] - self.low_window, seg[1] + self.high_window) | Apply our low and high windows to the segments in a
segmentlist. |
def element_focus_should_be_set(self, locator):
self._info("Verifying element focus is set" % locator)
self._check_element_focus(True, locator) | Verifies the element identified by `locator` has focus.
| *Argument* | *Description* | *Example* |
| locator | Selenium 2 element locator | id=my_id | |
def _generate_version(base_version):
pkg_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
if not _is_git_repo(pkg_dir) or not _have_git():
return base_version
if _is_release(pkg_dir, base_version) and not _is_dirty(pkg_dir):
return base_version
return "{base_vers... | Generate a version with information about the git repository |
def merge(
self, reservation_order_id, sources=None, custom_headers=None, raw=False, polling=True, **operation_config):
raw_result = self._merge_initial(
reservation_order_id=reservation_order_id,
sources=sources,
custom_headers=custom_headers,
... | Merges two `Reservation`s.
Merge the specified `Reservation`s into a new `Reservation`. The two
`Reservation`s being merged must have same properties.
:param reservation_order_id: Order Id of the reservation
:type reservation_order_id: str
:param sources: Format of the resource... |
def mutate_unsampled_call_args(self, module, method, wrapped, instance, args, kwargs, transaction):
return args, kwargs | Method called for unsampled wrapped calls. This can e.g. be used to add traceparent headers to the
underlying http call for HTTP instrumentations.
:param module:
:param method:
:param wrapped:
:param instance:
:param args:
:param kwargs:
:param transactio... |
def get_start_and_end_time(self, ref=None):
now = time.localtime(ref)
if self.syear == 0:
self.syear = now.tm_year
month_start_id = now.tm_mon
day_start = find_day_by_offset(self.syear, month_start_id, self.smday)
start_time = get_start_of_day(self.syear, mon... | Specific function to get start time and end time for MonthDayDaterange
:param ref: time in seconds
:type ref: int
:return: tuple with start and end time
:rtype: tuple (int, int) |
def get_previous_request(rid):
request = None
broker_req = relation_get(attribute=, rid=rid,
unit=local_unit())
if broker_req:
request_data = json.loads(broker_req)
request = CephBrokerRq(api_version=request_data[],
request_id... | Return the last ceph broker request sent on a given relation
@param rid: Relation id to query for request |
def _validateurl(self, url):
parsed = urlparse(url)
path = parsed.path.strip("/")
if path:
parts = path.split("/")
url_types = ("admin", "manager", "rest")
if any(i in parts for i in url_types):
while parts.pop() not in url_types:
... | assembles the server url |
def indicator(self, data):
data = self.get_first_hash(data)
super(File, self).indicator(data) | Update the request URI to include the Indicator for specific indicator retrieval.
Args:
data (string): The indicator value |
def verify_rank_integrity(self, tax_id, rank, parent_id, children):
def _lower(n1, n2):
return self.ranks.index(n1) < self.ranks.index(n2)
if rank not in self.ranks:
raise TaxonIntegrityError(.format(rank))
parent_rank = self.rank(parent_id)
if... | Confirm that for each node the parent ranks and children ranks are
coherent |
def warn(self, message, *args, **kwargs):
self.log("warn", message, *args, **kwargs) | alias to message at warning level |
def to_iso(dt):
if isinstance(dt, datetime):
return to_iso_datetime(dt)
elif isinstance(dt, date):
return to_iso_date(dt) | Format a date or datetime into an ISO-8601 string
Support dates before 1900. |
def count_by_key_impl(sequence):
counter = collections.Counter()
for key, _ in sequence:
counter[key] += 1
return six.viewitems(counter) | Implementation for count_by_key_t
:param sequence: sequence of (key, value) pairs
:return: counts by key |
def autogender(self, api_token=None, genderize_all=False):
name_cache = {}
no_gender = not genderize_all
pattern = re.compile(r"(^\w+)\s\w+")
profiles = api.search_profiles(self.db, no_gender=no_gender)
for profile in profiles:
if not profile.name:
... | Autocomplete gender information of unique identities.
Autocomplete unique identities gender using genderize.io
API. Only those unique identities without an assigned
gender will be updated unless `genderize_all` option is given. |
def reverse_deployments(deployments=None):
if deployments is None:
deployments = []
reversed_deployments = []
for i in deployments[::-1]:
deployment = copy.deepcopy(i)
for config in [, ]:
if deployment.get(config):
... | Reverse deployments and the modules/regions in them. |
def apply(self, **kwexpr):
for alias, expr in kwexpr.items():
self._projections.append([alias, expr])
return self | Specify one or more projection expressions to add to each result
### Parameters
- **kwexpr**: One or more key-value pairs for a projection. The key is
the alias for the projection, and the value is the projection
expression itself, for example `apply(square_root="sqrt(@foo)")` |
def save(self, msg=None):
if msg is None:
msg = % self.name
log.debug(msg)
self.repo.addItem(self, msg) | Modify item data and commit to repo.
Git objects are immutable, to save means adding a new item
:param msg: Commit message. |
def matrix(
m, n, lst,
m_text: list=None,
n_text: list=None):
fmt = ""
if n_text:
fmt += " {}\n".format(" ".join(n_text))
for i in range(1, m+1):
if m_text:
fmt += "{:<4.4} ".format(m_text[i-1])
fmt += "|"
for j in ra... | m: row
n: column
lst: items
>>> print(_matrix(2, 3, [(1, 1), (2, 3)]))
|x| | |
| | |x| |
def get_queryset(self):
if self.queryset is None:
raise ImproperlyConfigured(
" must define " % self.__class__.__name__)
return self.queryset() | Check that the queryset is defined and call it. |
def check_domain(self, service_id, version_number, name):
content = self._fetch("/service/%s/version/%d/domain/%s/check" % (service_id, version_number, name))
return FastlyDomainCheck(self, content) | Checks the status of a domain's DNS record. Returns an array of 3 items. The first is the details for the domain. The second is the current CNAME of the domain. The third is a boolean indicating whether or not it has been properly setup to use Fastly. |
async def get_pinstate_report(self, command):
pin = int(command[0])
value = await self.core.get_pin_state(pin)
if value:
reply = json.dumps({"method": "pin_state_reply", "params": value})
else:
reply = json.dumps({"method": "pin_state_reply", "params": "U... | This method retrieves a Firmata pin_state report for a pin..
See: http://firmata.org/wiki/Protocol#Pin_State_Query
:param command: {"method": "get_pin_state", "params": [PIN]}
:returns: {"method": "get_pin_state_reply", "params": [PIN_NUMBER, PIN_MODE, PIN_STATE]} |
def get_notebook_tab_title(notebook, page_num):
child = notebook.get_nth_page(page_num)
tab_label_eventbox = notebook.get_tab_label(child)
return get_widget_title(tab_label_eventbox.get_tooltip_text()) | Helper function that gets a notebook's tab title given its page number
:param notebook: The GTK notebook
:param page_num: The page number of the tab, for which the title is required
:return: The title of the tab |
def selecttabindex(self, window_name, object_name, tab_index):
children = self._get_tab_children(window_name, object_name)
length = len(children)
if tab_index < 0 or tab_index > length:
raise LdtpServerException(u"Invalid tab index %s" % tab_index)
tab_handle = child... | Select tab based on index.
@param window_name: Window name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type... |
def make_name(self, reserved=[]):
if self.title:
if inspect(self).has_identity:
def checkused(c):
return bool(c in reserved or c in self.reserved_names
or self.__class__.query.filter(self.__class__.id != self.id).filter_by(name=c).... | Autogenerates a :attr:`name` from the :attr:`title`. If the auto-generated name is already
in use in this model, :meth:`make_name` tries again by suffixing numbers starting with 2
until an available name is found.
:param reserved: List or set of reserved names unavailable for use |
def accel_move_tab_left(self, *args):
pos = self.get_notebook().get_current_page()
if pos != 0:
self.move_tab(pos, pos - 1)
return True | Callback to move a tab to the left |
def infos(self, type=None, failed=False):
nodes = self.nodes(failed="all")
infos = []
for n in nodes:
infos.extend(n.infos(type=type, failed=failed))
return infos | Get all infos created by the participants nodes.
Return a list of infos produced by nodes associated with the
participant. If specified, ``type`` filters by class. By default, failed
infos are excluded, to include only failed nodes use ``failed=True``,
for all nodes use ``failed=all``. ... |
def _find_usage_cloudtrail(self):
trail_list = self.conn.describe_trails()[]
trail_count = len(trail_list) if trail_list else 0
for trail in trail_list:
data_resource_count = 0
if self.conn._client_config.region_name == trail[]:
response = self.... | Calculate current usage for CloudTrail related metrics |
def postprocess_result(morphresult, trim_phonetic, trim_compound):
word, analysis = morphresult
return {
: deconvert(word),
: [postprocess_analysis(a, trim_phonetic, trim_compound) for a in analysis]
} | Postprocess vabamorf wrapper output. |
def handle_split(self, asset, ratio):
if self.asset != asset:
raise Exception("updating split with the wrong asset!")
raw_share_count = self.amount / float(ratio)
full_share_count = np.floor(raw_share_count)
... | Update the position by the split ratio, and return the resulting
fractional share that will be converted into cash.
Returns the unused cash. |
def flatten2d(d, key_as_tuple=True, delim=,
list_of_dicts=None):
return flattennd(d, 1, key_as_tuple, delim, list_of_dicts=list_of_dicts) | get nested dict as {key:dict,...},
where key is tuple/string of all-1 nested keys
NB: is same as flattennd(d,1,key_as_tuple,delim)
Parameters
----------
d : dict
key_as_tuple : bool
whether keys are list of nested keys or delimited string of nested keys
delim : str
if key_a... |
def save_point(self) -> str:
if self._current_mount is left:
msg = self.save_mount_offset()
self._current_mount = right
elif self._current_mount is types.Mount.LEFT:
msg = self.save_mount_offset()
self._current_mount = types.Mount.RIGHT
el... | Indexes the measured data with the current point as a key and saves the
current position once the 'Enter' key is pressed to the 'actual points'
vector. |
def create_storage_policy(policy_name, policy_dict, service_instance=None):
*policy name
log.trace(%s\, policy_name, policy_dict)
profile_manager = salt.utils.pbm.get_profile_manager(service_instance)
policy_create_spec = pbm.profile.CapabilityBasedProfileCreateSpec()
policy_create_spec.resourc... | Creates a storage policy.
Supported capability types: scalar, set, range.
policy_name
Name of the policy to create.
The value of the argument will override any existing name in
``policy_dict``.
policy_dict
Dictionary containing the changes to apply to the policy.
(... |
def extract_solvent_accessibility_dssp(in_dssp, path=True):
if path:
with open(in_dssp, ) as inf:
dssp_out = inf.read()
else:
dssp_out = in_dssp[:]
dssp_residues = []
go = False
for line in dssp_out.splitlines():
if go:
try:
res_nu... | Uses DSSP to extract solvent accessibilty information on every residue.
Notes
-----
For more information on the solvent accessibility metrics used in dssp, see:
http://swift.cmbi.ru.nl/gv/dssp/HTML/descrip.html#ACC
In the dssp files value is labeled 'ACC'.
Parameters
----------
in_dssp... |
def allow(self, comment, content_object, request):
POST = urlencode({
"blog": settings.AKISMET_BLOG.encode("utf-8"),
"user_ip": comment.ip_address,
"user_agent": request.META.get(, "").
encode("utf-... | Moderates comments. |
def sigmoid_accuracy_one_hot(logits, labels, weights_fn=None):
with tf.variable_scope("sigmoid_accuracy_one_hot", values=[logits, labels]):
del weights_fn
predictions = tf.nn.sigmoid(logits)
labels = tf.argmax(labels, -1)
predictions = tf.argmax(predictions, -1)
_, accuracy = tf.metrics.accurac... | Calculate accuracy for a set, given one-hot labels and logits.
Args:
logits: Tensor of size [batch-size, o=1, p=1, num-classes]
labels: Tensor of size [batch-size, o=1, p=1, num-classes]
weights_fn: Function that takes in labels and weighs examples (unused)
Returns:
accuracy (scalar), weights |
def patch_for_specialized_compiler():
if not in globals():
return
if unpatched:
return
unpatched.update(vars(distutils.msvc9compiler))
distutils.msvc9compiler.find_vcvarsall = find_vcvarsall
distutils.msvc9compiler.query_vcvarsall = query_vcvarsall | Patch functions in distutils.msvc9compiler to use the standalone compiler
build for Python (Windows only). Fall back to original behavior when the
standalone compiler is not available. |
def close_tab(self):
if len(self.tab_pages) > 1:
del self.tab_pages[self.active_tab_index]
self.active_tab_index = max(0, self.active_tab_index - 1)
self._auto_close_new_empty_buffers() | Close active tab. |
def s_l(l, alpha):
a2 = alpha**2
c_a = 0.547
s_l = np.sqrt(old_div(((c_a**(2. * l)) * a2), ((l + 1.) * (2. * l + 1.))))
return s_l | get sigma as a function of degree l from Constable and Parker (1988) |
def interfaces(self):
self._ifaces = []
wifi_ctrl = wifiutil.WifiUtil()
for interface in wifi_ctrl.interfaces():
iface = Interface(interface)
self._ifaces.append(iface)
self._logger.info("Get interface: %s", iface.name())
if not self._iface... | Collect the available wlan interfaces. |
def get_hosts_by_explosion(self, hostgroups):
self.already_exploded = True
if self.rec_tag:
logger.error("[hostgroup::%s] got a loop in hostgroup definition", self.get_name())
return self.get_hosts()
... | Get hosts of this group
:param hostgroups: Hostgroup object
:type hostgroups: alignak.objects.hostgroup.Hostgroups
:return: list of hosts of this group
:rtype: list |
def user_has_group(user, group, superuser_skip=True):
if user.is_superuser and superuser_skip:
return True
return user.groups.filter(name=group).exists() | Check if a user is in a certaing group.
By default, the check is skipped for superusers. |
def attach(self, screen):
if self.listener is not None:
warnings.warn("As of version 0.6.0 the listener queue is "
"restricted to a single element. Existing "
"listener {0} will be replaced."
.format(self.listener... | Adds a given screen to the listener queue.
:param pyte.screens.Screen screen: a screen to attach to. |
def from_json(self, fname):
with open(fname, ) as fp:
for row in json.load(fp):
nn = ServerInfo.from_dict(row)
self[str(nn)] = nn | Read contents of a CSV containing a list of servers. |
def bar_chart_mf(data, path_name):
N = len(data)
ind = np.arange(N)
width = 0.8
fig, ax = pyplot.subplots()
rects1 = ax.bar(ind, data, width, color=)
ax.set_ylabel()
ax.set_xticks(ind+width/2)
labs = [+str(i) for i in range(-N/2+1, N/2+1)]
ax.set_xtic... | Make a bar chart for data on MF quantities. |
def add_state_editor(self, state_m):
state_identifier = self.get_state_identifier(state_m)
if state_identifier in self.closed_tabs:
state_editor_ctrl = self.closed_tabs[state_identifier][]
state_editor_view = state_editor_ctrl.view
handler_id = self.closed_t... | Triggered whenever a state is selected.
:param state_m: The selected state model. |
def Verify(self, public_key):
now = rdfvalue.RDFDatetime.Now().AsDatetime()
if now > self._value.not_valid_after:
raise VerificationError("Certificate expired!")
if now < self._value.not_valid_before:
raise VerificationError("Certificate not yet valid!")
publi... | Verifies the certificate using the given key.
Args:
public_key: The public key to use.
Returns:
True: Everything went well.
Raises:
VerificationError: The certificate did not verify. |
def _context(self):
src_stats = {
src: self._src_path_stats(src) for src in self.src_paths()
}
} | Return the context to pass to the template.
The context is a dict of the form:
{
'css_url': CSS_URL,
'report_name': REPORT_NAME,
'diff_name': DIFF_NAME,
'src_stats': {SRC_PATH: {
'percent_covered': PERCENT_COVERED,
... |
def get_edge_annotations(self, u, v, key: str) -> Optional[AnnotationsDict]:
return self._get_edge_attr(u, v, key, ANNOTATIONS) | Get the annotations for a given edge. |
def write_c_string( self, value ):
self.file.write( value )
self.file.write( b ) | Read a zero terminated (C style) string |
def read_namespace_status(self, name, **kwargs):
kwargs[] = True
if kwargs.get():
return self.read_namespace_status_with_http_info(name, **kwargs)
else:
(data) = self.read_namespace_status_with_http_info(name, **kwargs)
return data | read_namespace_status # noqa: E501
read status of the specified Namespace # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespace_status(name, async_req=True)
>>> res... |
def from_ISO_8601(cls, date_string, time_string, tz_string):
if tz_string:
tz_offset = (int(tz_string[1:3]) * 60) + int(tz_string[3:])
if tz_string[0] == :
tz_offset = -tz_offset
else:
tz_offset = None
if time_string == :
... | Sufficiently general ISO 8601 parser.
Inputs must be in "basic" format, i.e. no '-' or ':' separators.
See https://en.wikipedia.org/wiki/ISO_8601 |
def parameters(self, params):
array = JavaArray(jobject=JavaArray.new_instance("weka.core.setupgenerator.AbstractParameter", len(params)))
for idx, obj in enumerate(params):
array[idx] = obj.jobject
javabridge.call(self.jobject, "setParameters", "([Lweka/core/setupgenerator/... | Sets the list of search parameters to use.
:param params: list of AbstractSearchParameter objects
:type params: list |
def O(self):
N = self.N
tig_to_idx = self.tig_to_idx
O = np.zeros((N, N), dtype=int)
for (at, bt), (strandedness, md, mh) in self.orientations.items():
if not (at in tig_to_idx and bt in tig_to_idx):
continue
ai = tig_to_idx[at]
... | Pairwise strandedness matrix. Each cell contains whether i-th and j-th
contig are the same orientation +1, or opposite orientation -1. |
def add(self, rulefactory):
for rule in rulefactory.get_rules(self):
rule.bind(self)
self._rules.append(rule)
self._rules_by_endpoint.setdefault(rule.endpoint, []).append(rule)
self._remap = True | Add a new rule or factory to the map and bind it. Requires that the
rule is not bound to another map.
:param rulefactory: a :class:`Rule` or :class:`RuleFactory` |
def comparison(self):
node = self.expr()
while self.token.nature in (
Nature.EQ,
Nature.NE,
Nature.LE,
Nature.GE,
Nature.LT,
Nature.GT,
):
token = self.token
if token.nature == Nature.EQ:
... | comparison: expr (('==' | '!=' | '<=' | '>=' | '<' | '>') expr)* |
def create_quiz_report(self, quiz_id, course_id, quiz_report_report_type, include=None, quiz_report_includes_all_versions=None):
path = {}
data = {}
params = {}
path["course_id"] = course_id
path["quiz_id"] = quiz_id
... | Create a quiz report.
Create and return a new report for this quiz. If a previously
generated report matches the arguments and is still current (i.e.
there have been no new submissions), it will be returned.
*Responses*
* <code>400 Bad Request</code> if... |
def getinfo(self):
try:
old_getinfo = AuthServiceProxy(self.__service_url, , self.__timeout, self.__conn, True)
res = old_getinfo()
if not in res:
return res
except JSONRPCException:
pass
network_info = ... | Backwards-compatibility for 0.14 and later |
def _get_randomized_range(val,
provided_range,
default_range):
if val is None:
if provided_range is None:
return default_range
else:
return provided_range
else:
if provided_range is not None:
rai... | Helper to initialize by either value or a range
Returns a range to randomize from |
def find_newline(self, size=-1):
if size < 0:
return self._buffer.find(, self._offset)
return self._buffer.find(, self._offset, self._offset + size) | Search for newline char in buffer starting from current offset.
Args:
size: number of bytes to search. -1 means all.
Returns:
offset of newline char in buffer. -1 if doesn't exist. |
def get_rate(self, zipcode, city=None, state=None, multiple_rates=False):
data = self.make_request_data(zipcode, city, state)
r = requests.get(self.url, params=data)
resp = r.json()
return self.process_response(resp, multiple_rates) | Finds sales tax for given info.
Returns Decimal of the tax rate, e.g. 8.750. |
def load_data_old(self):
units = ""
if len(self.file_objects) == 1 and self.file_objects[0] is not None:
data = self.file_objects[0].variables[self.variable][self.forecast_hours]
if hasattr(self.file_objects[0].variables[self.variable], "units"):
units = ... | Loads time series of 2D data grids from each opened file. The code
handles loading a full time series from one file or individual time steps
from multiple files. Missing files are supported. |
def to_range(obj, score=None, id=None, strand=None):
from jcvi.utils.range import Range
if score or id:
_score = score if score else obj.score
_id = id if id else obj.id
return Range(seqid=obj.seqid, start=obj.start, end=obj.end, \
score=_score, id=_id)
elif strand:... | Given a gffutils object, convert it to a range object |
def parse(inp, format=None, encoding=, force_types=True):
proper_inp = inp
if hasattr(inp, ):
proper_inp = inp.read()
if isinstance(proper_inp, six.text_type):
proper_inp = proper_inp.encode(encoding)
fname = None
if hasattr(inp, ):
fname = inp.name
fmt = ... | Parse input from file-like object, unicode string or byte string.
Args:
inp: file-like object, unicode string or byte string with the markup
format: explicitly override the guessed `inp` markup format
encoding: `inp` encoding, defaults to utf-8
force_types:
if `True`, in... |
def list(self, size=1000, tree_depth=1):
if not tree_depth: return self._map_type()
return list(self.deque(size, tree_depth-1) for x in range(size)) | Creates a random #list
@size: #int number of random values to include in each @tree_depth
@tree_depth: #int dict tree dimensions size, i.e.
1=|[value1, value2]|
2=|[[value1, value2], [value1, value2]]|
-> random #list |
def printArray(self, node, printState: PrintState):
if (
self.nameMapper[node["name"]] not in printState.definedVars
and self.nameMapper[node["name"]] not in printState.globalVars
):
printState.definedVars += [self.nameMapper[node["name"]]]
assert... | Prints out the array declaration in a format of Array class
object declaration. 'arrayName = Array(Type, [bounds])' |
def zeros_like(array, dtype=None, keepmeta=True):
if keepmeta:
return xr.zeros_like(array, dtype)
else:
return dc.zeros(array.shape, dtype) | Create an array of zeros with the same shape and type as the input array.
Args:
array (xarray.DataArray): The shape and data-type of it define
these same attributes of the output array.
dtype (data-type, optional): If specified, this function overrides
the data-type of the o... |
def to_representation(self, instance):
updated_course = copy.deepcopy(instance)
enterprise_customer_catalog = self.context[]
updated_course[] = enterprise_customer_catalog.get_course_enrollment_url(
updated_course[]
)
for course_run in updated_course[]:
... | Return the updated course data dictionary.
Arguments:
instance (dict): The course data.
Returns:
dict: The updated course data. |
def change_cloud_password(
self,
current_password: str,
new_password: str,
new_hint: str = ""
) -> bool:
r = self.send(functions.account.GetPassword())
if not r.has_password:
raise ValueError("There is no cloud password to change")
r.new... | Use this method to change your Two-Step Verification password (Cloud Password) with a new one.
Args:
current_password (``str``):
Your current password.
new_password (``str``):
Your new password.
new_hint (``str``, *optional*):
... |
def sludge(self, column=None, value=None, **kwargs):
return self._resolve_call(, column, value, **kwargs) | Sludge information describes the volumn of sludge produced at a
facility, identification information on a sludge handler, and
classification/permitting information on a facility that handles
sludge, such as a pretreatment POTW.
>>> PCS().sludge('county_name', 'San Francisco') |
def __split_file(self):
if (self.__filename and os.access(self.__filename, os.R_OK)):
fhandle = None
try:
fhandle = os.open(self.__filename, os.O_RDONLY)
except OSError:
print(("CouldnSplit by day found'
self... | Splits combined SAR output file (in ASCII format) in order to
extract info we need for it, in the format we want.
:return: ``List``-style of SAR file sections separated by
the type of info they contain (SAR file sections) without
parsing what is exactly what at this p... |
def __validate_datetime_string(self):
try:
try:
StrictVersion(self._value)
raise TypeConversionError(
"invalid datetime string: version string found {}".format(self._value)
)
except ValueError:
... | This will require validating version string (such as "3.3.5").
A version string could be converted to a datetime value if this
validation is not executed. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.