text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def ensure_timezone(dt, tz=None):
"""
Make sure the datetime <dt> has a timezone set, using timezone <tz> if it
doesn't. <tz> defaults to the local timezone.
"""
if dt.tzinfo is None:
return dt.replace(tzinfo=tz or tzlocal())
else:
return dt | 0.003559 |
def module_for_loader(fxn):
"""Decorator to handle selecting the proper module for loaders.
The decorated function is passed the module to use instead of the module
name. The module passed in to the function is either from sys.modules if
it already exists or is a new module. If the module is new, then _... | 0.001809 |
def extract_statements(self):
"""Process the table to extract Statements."""
for _, (tf, target, effect, refs) in self.df.iterrows():
tf_agent = get_grounded_agent(tf)
target_agent = get_grounded_agent(target)
if effect == 'Activation':
stmt_cls = Incr... | 0.00312 |
def reqTickByTickData(
self, contract: Contract, tickType: str,
numberOfTicks: int = 0, ignoreSize: bool = False) -> Ticker:
"""
Subscribe to tick-by-tick data and return the Ticker that
holds the ticks in ticker.tickByTicks.
https://interactivebrokers.github.io/... | 0.002336 |
def fromFile(cls, filepath):
"""
Creates a proxy instance from the inputted registry file.
:param filepath | <str>
:return <PluginProxy> || None
"""
xdata = ElementTree.parse(nstr(filepath))
xroot = xdata.getroot()
# collect var... | 0.002706 |
def reduce(self, values, inplace=True):
"""
Reduces the distribution to the context of the given variable values.
The formula for the obtained conditional distribution is given by -
For,
.. math:: N(X_j | X_i = x_i) ~ N(mu_{j.i} ; sig_{j.i})
where,
.. math:: mu... | 0.002146 |
def split_sentences(self, text):
"""
Split input text into sentences that match CoreNLP's default format,
but are not yet processed.
:param text: The text of the parent paragraph of the sentences
:return:
"""
if self.model.has_pipe("sentence_boundary_detector"):... | 0.00289 |
def _make_single_run(self):
""" Modifies the trajectory for single runs executed by the environment """
self._is_run = False # to be able to use f_set_crun
self._new_nodes = OrderedDict()
self._new_links = OrderedDict()
self._is_run = True
return self | 0.013378 |
def getATR(reader):
"""Return the ATR of the card inserted into the reader."""
connection = reader.createConnection()
atr = ""
try:
connection.connect()
atr = smartcard.util.toHexString(connection.getATR())
connection.disconnect()
except smartcard.Exceptions.NoCardException:
... | 0.002725 |
def fix_hp_addrs(server):
"""
Works around hpcloud's peculiar "all ip addresses are returned as private
even though one is public" bug. This is also what the official hpfog gem
does in the ``Fog::Compute::HP::Server#public_ip_address`` method.
:param dict server: Contains the server ID, a list of... | 0.001639 |
def integral(self,
xbin1=1, xbin2=-2,
ybin1=1, ybin2=-2,
zbin1=1, zbin2=-2,
width=False,
error=False,
overflow=False):
"""
Compute the integral and error over a range of bins
"""
if xbin... | 0.00578 |
def Click(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
Simulate mouse click at point x, y.
x: int.
y: int.
waitTime: float.
"""
SetCursorPos(x, y)
screenWidth, screenHeight = GetScreenSize()
mouse_event(MouseEventFlag.LeftDown | MouseEventFlag.Absolute, x * 655... | 0.005545 |
def seven_zip(archive, items, self_extracting=False):
"""Create a 7z archive."""
if not isinstance(items, (list, tuple)):
items = [items]
if self_extracting:
return er(_get_sz(), "a", "-ssw", "-sfx", archive, *items)
else:
return er(_get_sz(), "a", "-ssw", archive, *items) | 0.003195 |
def _decoder(self, obj):
""" Decode a toc element leaf-node """
if '__class__' in obj:
elem = eval(obj['__class__'])()
elem.ident = obj['ident']
elem.group = str(obj['group'])
elem.name = str(obj['name'])
elem.ctype = str(obj['ctype'])
... | 0.004556 |
def eplotter(task, data): # CRYSTAL, VASP, EXCITING
'''
eplotter is like bdplotter but less complicated
'''
results, color, fdata = [], None, []
if task == 'optstory':
color = '#CC0000'
clickable = True
for n, i in enumerate(data):
fdata.append([n, i[4]])
... | 0.008393 |
def to(self, unit):
"""Convert to a given unit.
Parameters
----------
unit : str
Name of the unit to convert to.
Returns
-------
u : Unit
new Unit object with the requested unit and computed value.
"""
u = Unit("0cm")
... | 0.004684 |
def getFilterNames(header, filternames=None):
"""
Returns a comma-separated string of filter names extracted from the input
header (PyFITS header object). This function has been hard-coded to
support the following instruments:
ACS, WFPC2, STIS
This function relies on the 'INSTRUME' keywor... | 0.000538 |
def eeg_microstates_clustering(data, n_microstates=4, clustering_method="kmeans", n_jobs=1, n_init=25, occurence_rejection_treshold=0.05, max_refitting=5, verbose=True):
"""
Fit the clustering algorithm.
"""
# Create training set
training_set = data.copy()
if verbose is True:
print("- I... | 0.00356 |
def bokeh_tree(name, rawtext, text, lineno, inliner, options=None, content=None):
''' Link to a URL in the Bokeh GitHub tree, pointing to appropriate tags
for releases, or to master otherwise.
The link text is simply the URL path supplied, so typical usage might
look like:
.. code-block:: none
... | 0.00221 |
def _update_limits_from_api(self):
"""
Call the service's API action to retrieve limit/quota information, and
update AwsLimit objects in ``self.limits`` with this information.
"""
self.connect_resource()
summary = self.resource_conn.AccountSummary()
for k, v in so... | 0.002094 |
def _set_igmp_statistics(self, v, load=False):
"""
Setter method for igmp_statistics, mapped from YANG variable /igmp_snooping_state/igmp_statistics/igmp_statistics (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_igmp_statistics is considered as a private
meth... | 0.004647 |
def as_dict(self):
""" create a dict based on class attributes """
odict = OrderedDict()
for name in self._order:
attr_value = getattr(self, name)
if isinstance(attr_value, List):
_list = []
for item in attr_value:
_list... | 0.004902 |
def tar(self, appname, appversion):
"""
Given an app name and version to be used in the tarball name,
create a tar.bz2 file with all of this folder's contents inside.
Return a Build object with attributes for appname, appversion,
time, and path.
"""
name_tmpl = '... | 0.002179 |
def Ravipudi_Godbold(m, x, D, rhol, rhog, Cpl, kl, mug, mu_b, mu_w=None):
r'''Calculates the two-phase non-boiling heat transfer coefficient of a
liquid and gas flowing inside a tube of any inclination, as in [1]_ and
reviewed in [2]_.
.. math::
Nu = \frac{h_{TP} D}{k_l} = 0.56 \left(\frac{V_... | 0.006114 |
def to_aes_key(password):
"""Compute/Derivate a key to be used in AES encryption from the password
To maintain compatibility with the reference implementation the resulting
key should be a sha256 hash of the sha256 hash of the password
"""
password_hash = hashlib.sha256(password.encode('utf-8')).di... | 0.00266 |
def report(issues, show_urls=False):
"""Summary report about a list of issues, printing number and title.
"""
# titles may have unicode in them, so we must encode everything below
if show_urls:
for i in issues:
print(u'#%d: %s' % (i['number'],
i[... | 0.004292 |
def set_number(self, key, value):
""" set a key's value
"""
storage = self.storage
if not isinstance(value, int):
logger.error("set_number: Value must be an integer")
return
try:
lock.acquire()
storage[key] = value
finally... | 0.004762 |
def get_default_config_help(self):
"""
Returns the help text for the configuration options for this handler
"""
config = super(StatsiteHandler, self).get_default_config_help()
config.update({
'host': '',
'tcpport': '',
'udpport': '',
... | 0.005391 |
def generate_hash_comment(file_path):
"""
Read file with given file_path and return string of format
# SHA1:da39a3ee5e6b4b0d3255bfef95601890afd80709
which is hex representation of SHA1 file content hash
"""
with open(file_path, 'rb') as fp:
hexdigest = hashlib.sha1(fp.read().strip(... | 0.002646 |
def max(self):
"""Return the maximum of ``self``.
See Also
--------
numpy.amax
min
"""
results = [x.ufuncs.max() for x in self.elem]
return np.max(results) | 0.009091 |
def run(self):
"""Run loading of movie appearances.
The wiki page structure for this part cannot be easily handled by simple xpath queries.
We need to iterate over the respective portion of the page and parse appearances.
"""
# make all requests via a cache instance
req... | 0.006295 |
def sensor_offsets_encode(self, mag_ofs_x, mag_ofs_y, mag_ofs_z, mag_declination, raw_press, raw_temp, gyro_cal_x, gyro_cal_y, gyro_cal_z, accel_cal_x, accel_cal_y, accel_cal_z):
'''
Offsets and calibrations values for hardware sensors. This makes it
easier to debug the c... | 0.00545 |
def receive(self, timeout=None):
"""Receive data through websocket"""
log.debug('Receiving')
if not self._socket:
log.warn('No connection')
return
try:
if timeout:
rv = self._socket.poll(timeout)
if not rv:
... | 0.003317 |
def view_package_info(self, package: str='') -> str:
'''View package detail information.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'dumpsys', 'package', package)
return output | 0.017391 |
def traverse_imports(names):
"""
Walks over all the names imported in a dotted_as_names node.
"""
pending = [names]
while pending:
node = pending.pop()
if node.type == token.NAME:
yield node.value
elif node.type == syms.dotted_name:
yield "".join([ch.v... | 0.001653 |
def import_seaborn():
'''import seaborn and handle deprecation of apionly module'''
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
try:
import seaborn.apionly as sns
if (w and issubclass(w[-1].category, UserWarning) and
... | 0.001866 |
def update_director(self, service_id, version_number, name_key, **kwargs):
"""Update the director for a particular service and version."""
body = self._formdata(kwargs, FastlyDirector.FIELDS)
content = self._fetch("/service/%s/version/%d/director/%s" % (service_id, version_number, name_key), method="PUT", body=bo... | 0.019337 |
def get(cls, id=None, condition=None, fields=None, cache=False, engine_name=None, **kwargs):
"""
Get object from Model, if given fields, then only fields will be loaded
into object, other properties will be Lazy
if cache is True or defined __cacheable__=True in Model class, it'l... | 0.007218 |
def get_all_requisite_objectives(self, objective_id=None):
"""Gets a list of Objectives that are the requisites for the given
Objective including the requistes of the requisites, and so on.
In plenary mode, the returned list contains all of the immediate
requisites, or an error results ... | 0.002299 |
def reverse(
self,
query,
reverse_geocode_preference=('StreetAddress', ),
maximum_responses=25,
filtering='',
exactly_one=DEFAULT_SENTINEL,
timeout=DEFAULT_SENTINEL,
):
"""
Return an address by location point.
... | 0.001209 |
def check_float_param(self, param, low, high, name):
"""
Check if the value of the given parameter is in the given range
and a float.
Designed for testing parameters like `mu` and `eps`.
To pass this function the variable `param` must be able to be converted
into a float ... | 0.008651 |
def resolve(self, value=None):
""" Resolve the current expression against the supplied value """
# If we still have an uninitialized matcher init it now
if self.matcher:
self._init_matcher()
# Evaluate the current set of matchers forming the expression
matcher = sel... | 0.002841 |
def get_build_work_items_refs_from_commits(self, commit_ids, project, build_id, top=None):
"""GetBuildWorkItemsRefsFromCommits.
Gets the work items associated with a build, filtered to specific commits.
:param [str] commit_ids: A comma-delimited list of commit IDs.
:param str project: Pr... | 0.006143 |
def handle_tick(self):
"""Internal callback every time 1 second has passed."""
self.uptime += 1
for name, interval in self.ticks.items():
if interval == 0:
continue
self.tick_counters[name] += 1
if self.tick_counters[name] == interval:
... | 0.004651 |
def update_progress(cls, progress, starttime):
""" Display an ascii progress bar while processing operation. """
width, _height = click.get_terminal_size()
if not width:
return
duration = datetime.utcnow() - starttime
hours, remainder = divmod(duration.seconds, 3600)... | 0.001754 |
def retry(self, index=None, params=None):
"""
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-retry-policy.html>`_
:arg index: The name of the indices (comma-separated) whose failed
lifecycle step is to be retry
"""
return self.transport.perform... | 0.00489 |
def fire_event(self, evt_name, *args, **kwargs):
"""触发事件
:params evt_name: 事件名称
:params args: 给事件接受者的参数
:params kwargs: 给事件接受者的参数
"""
listeners = self.__get_listeners(evt_name)
evt = self.generate_event(evt_name)
for listener in listeners:
lis... | 0.005764 |
def prepare_static_data(self, data):
"""
If user defined static fields, then process them with visiable value
"""
d = self.obj.to_dict()
d.update(data.copy())
for f in self.get_fields():
if f['static'] and f['name'] in d:
v = make_view_... | 0.006466 |
def complete_json_get(self, cmd_param_text, full_cmd, *rest):
""" TODO: prefetch & parse znodes & suggest keys """
complete_keys = partial(complete_values, ["key1", "key2", "#{key1.key2}"])
completers = [self._complete_path, complete_keys, complete_labeled_boolean("recursive")]
return co... | 0.010782 |
def size(self, width=None, height=None):
u'''Set/get window size.'''
sc = System.Console
if width is not None and height is not None:
sc.BufferWidth, sc.BufferHeight = width,height
else:
return sc.BufferWidth, sc.BufferHeight
if width is not None ... | 0.008368 |
async def handshake(
self,
origins: Optional[Sequence[Optional[Origin]]] = None,
available_extensions: Optional[Sequence[ServerExtensionFactory]] = None,
available_subprotocols: Optional[Sequence[Subprotocol]] = None,
extra_headers: Optional[HeadersLikeOrCallable] = None,
) -... | 0.00171 |
def colorify_logo(cls, home=False):
"""
Print the colored logo based on global results.
:param home: Tell us if we have to print the initial coloration.
:type home: bool
"""
if not PyFunceble.CONFIGURATION["quiet"]:
# The quiet mode is not activated.
... | 0.001518 |
def load_output_meta(self):
"""
Load descriptive output meta data from a JSON file in the input directory.
"""
options = self.options
file_path = os.path.join(options.inputdir, 'output.meta.json')
with open(file_path) as infile:
return json.load(infile) | 0.009585 |
def _attrs_to_tuple(obj, attrs):
"""
Create a tuple of all values of *obj*'s *attrs*.
"""
return tuple(getattr(obj, a.name) for a in attrs) | 0.006452 |
def get_proxy(self, proxystr=''):
"""
Get the proxy given the option passed on the command line.
If an empty string is passed it looks at the HTTP_PROXY
environment variable.
"""
if not proxystr:
proxystr = os.environ.get('HTTP_PROXY', '')
if proxystr:... | 0.002257 |
def event_key_pressed(self, event):
"""
So a "invert shift" for user inputs:
Convert all lowercase letters to uppercase and vice versa.
"""
char = event.char
if not char:
return
if char in string.ascii_letters:
char = invert_shift(char)
... | 0.00409 |
def inject(fun: Callable) -> Callable:
"""
A decorator for injection dependencies into functions/methods, based
on their type annotations.
.. code-block:: python
class SomeClass:
@inject
def __init__(self, my_dep: DepType) -> None:
self.my_dep = my_dep
... | 0.000858 |
def last_year(today: datetime=None, tz=None):
"""
Returns last year begin (inclusive) and end (exclusive).
:param today: Some date (defaults current datetime)
:param tz: Timezone (defaults pytz UTC)
:return: begin (inclusive), end (exclusive)
"""
if today is None:
today = datetime.ut... | 0.005725 |
def save(self, target=None, shp=None, shx=None, dbf=None):
"""Save the shapefile data to three files or
three file-like objects. SHP and DBF files can also
be written exclusively using saveShp, saveShx, and saveDbf respectively."""
# TODO: Create a unique filename for target if None.... | 0.004425 |
def install_sql_hook():
"""If installed this causes Django's queries to be captured."""
try:
from django.db.backends.utils import CursorWrapper
except ImportError:
from django.db.backends.util import CursorWrapper
try:
real_execute = CursorWrapper.execute
real_executeman... | 0.000513 |
def expire_data(self):
"""Expire data within the samples collection."""
# Do we need to start deleting stuff?
while self.sample_storage_size() > self.samples_cap:
# This should return the 'oldest' record in samples
record = self.database[self.sample_collection].find().s... | 0.009662 |
def checkmagic(self):
"""Verify that self is a valid CArchive.
Magic signature is at end of the archive."""
#magic is at EOF; if we're embedded, we need to figure where that is
if self.len:
self.lib.seek(self.start+self.len, 0)
else:
self.lib.seek(0, ... | 0.00653 |
def makeW(r1, r2, r3, r4=0):
"""
matrix involved in quaternion rotation
"""
W = np.asarray([
[r4, r3, -r2, r1],
[-r3, r4, r1, r2],
[r2, -r1, r4, r3],
[-r1, -r2, -r3, r4]])
return W | 0.00431 |
def _compute_dk_dtau(self, tau, n):
r"""Evaluate :math:`dk/d\tau` at the specified locations with the specified derivatives.
Parameters
----------
tau : :py:class:`Matrix`, (`M`, `D`)
`M` inputs with dimension `D`.
n : :py:class:`Array`, (`D`,)
De... | 0.004084 |
def decons_obs_group_ids(comp_ids, obs_ids, shape, labels, xnull):
"""
reconstruct labels from observed group ids
Parameters
----------
xnull: boolean,
if nulls are excluded; i.e. -1 labels are passed through
"""
if not xnull:
lift = np.fromiter(((a == -1).any() for a in la... | 0.002516 |
def name(self):
""" Returns name of the digest """
if not hasattr(self, 'digest_name'):
self.digest_name = Oid(libcrypto.EVP_MD_type(self.digest)
).longname()
return self.digest_name | 0.011905 |
def eventReminder(self, thread_id, time, title, location="", location_id=""):
"""
Deprecated. Use :func:`fbchat.Client.createPlan` instead
"""
plan = Plan(time=time, title=title, location=location, location_id=location_id)
self.createPlan(plan=plan, thread_id=thread_id) | 0.009677 |
def set_keepalive(self, interval):
"""
Set a keepalive to occur every ``interval`` on this connection.
"""
pinger = functools.partial(self.ping, 'keep-alive')
self.reactor.scheduler.execute_every(period=interval, func=pinger) | 0.007547 |
def touch(ctx, key, policy, admin_pin, force):
"""
Manage touch policy for OpenPGP keys.
\b
KEY Key slot to set (sig, enc or aut).
POLICY Touch policy to set (on, off or fixed).
"""
controller = ctx.obj['controller']
old_policy = controller.get_touch(key)
if old_policy == TOUC... | 0.002933 |
def save(self, other: merkle_tree.MerkleTree):
"""Save this tree into a dumb data object for serialisation.
The object must have attributes tree_size:int and hashes:list.
"""
other.__tree_size = self.__tree_size
other.__hashes = self.__hashes | 0.007067 |
def graph(args):
"""
%prog graph best.edges
Convert Celera Assembler's "best.edges" to a GEXF which can be used to
feed into Gephi to check the topology of the best overlapping graph. Mutual
best edges are represented as thicker edges.
Reference:
https://github.com/PacificBiosciences/Bioin... | 0.002458 |
def _read_elem_elements(self, fid):
"""Read all FE elements from the file stream. Elements are stored in
the self.element_data dict. The keys refer to the element types:
* 3: Triangular grid (three nodes)
* 8: Quadrangular grid (four nodes)
* 11: Mixed boundary element
... | 0.001412 |
def decode(s, checksum=True):
"""Convert base58 to binary using BASE58_ALPHABET."""
v, prefix = to_long(
BASE58_BASE, lambda c: BASE58_LOOKUP[c], s.encode("utf8"))
data = from_long(v, prefix, 256, lambda x: x)
if checksum:
data, the_hash = data[:-4], data[-4:]
if utils.hash256(... | 0.002227 |
def center_cell_text(cell):
"""
Horizontally center the text within a cell's grid
Like this::
+---------+ +---------+
| foo | --> | foo |
+---------+ +---------+
Parameters
----------
cell : dashtable.data2rst.Cell
Returns
-------
cell : da... | 0.000822 |
def error(self, message, code=1):
""" Prints the error, and exits with the given code. """
sys.stderr.write(message)
sys.exit(code) | 0.012903 |
def json_decode(value: Union[str, bytes]) -> Any:
"""Returns Python objects for the given JSON string.
Supports both `str` and `bytes` inputs.
"""
return json.loads(to_basestring(value)) | 0.004926 |
def unquote(cls, string):
""" Removes quotes from a quoted string.
Splunk search command quote rules are applied. The enclosing
double-quotes, if present, are removed. Escaped double-quotes ('\"' or
'""') are replaced by a single double-quote ('"').
**NOTE**
We are not... | 0.002144 |
def _fit(self, dataset):
"""Trains a TensorFlow model and returns a TFModel instance with the same args/params pointing to a checkpoint or saved_model on disk.
Args:
:dataset: A Spark DataFrame with columns that will be mapped to TensorFlow tensors.
Returns:
A TFModel representing the trained ... | 0.009782 |
def code_timer(reset=False):
'''Sets a global variable for tracking the timer accross multiple
files '''
global CODE_TIMER
if reset:
CODE_TIMER = CodeTimer()
else:
if CODE_TIMER is None:
return CodeTimer()
else:
return CODE_TIMER | 0.003356 |
def dist_sift4(src, tar, max_offset=5, max_distance=0):
"""Return the normalized "common" Sift4 distance between two terms.
This is a wrapper for :py:meth:`Sift4.dist`.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
max_o... | 0.001205 |
def _check_algorithm_values(item):
"""Check for misplaced inputs in the algorithms.
- Identify incorrect boolean values where a choice is required.
"""
problems = []
for k, v in item.get("algorithm", {}).items():
if v is True and k not in ALG_ALLOW_BOOLEANS:
problems.append("%s ... | 0.006605 |
def _as_rdf_xml(self, ns):
"""
Return identity details for the element as XML nodes
"""
self.rdf_identity = self._get_identity(ns)
elements = []
elements.append(ET.Element(NS('sbol', 'persistentIdentity'),
attrib={NS('rdf', 'resource'):
... | 0.002803 |
def get_deployments(self, prefix=""):
""" This endpoint lists all deployments.
https://www.nomadproject.io/docs/http/deployments.html
optional_arguments:
- prefix, (default "") Specifies a string to filter deployments on based on an index prefix.
Th... | 0.004615 |
def estimate_row_means(
self,
X,
observed,
column_means,
column_scales):
"""
row_center[i] =
sum{j in observed[i, :]}{
(1 / column_scale[j]) * (X[i, j] - column_center[j])
}
----------------------------------... | 0.001802 |
def _remove_vlan_from_all_service_profiles(self, handle, vlan_id, ucsm_ip):
"""Deletes VLAN Profile config from server's ethernet ports."""
service_profile_list = []
for key, value in six.iteritems(self.ucsm_sp_dict):
if (ucsm_ip in key) and value:
service_profile_lis... | 0.001968 |
def dirinfo(path, opts=None):
'''
Return information on a directory located on the Moose
CLI Example:
.. code-block:: bash
salt '*' moosefs.dirinfo /path/to/dir/ [-[n][h|H]]
'''
cmd = 'mfsdirinfo'
ret = {}
if opts:
cmd += ' -' + opts
cmd += ' ' + path
out = __s... | 0.001761 |
def regression(fname="regression.png"):
"""
Create figures for regression models
"""
_, axes = plt.subplots(ncols=2, figsize=(18, 6))
alphas = np.logspace(-10, 1, 300)
data = load_concrete(split=True)
# Plot prediction error in the middle
oz = PredictionError(LassoCV(alphas=alphas), ax=... | 0.001393 |
def add_private_note(self, private_notes, source=None):
"""Add private notes.
:param private_notes: hidden notes for the current document
:type private_notes: string
:param source: source for the given private notes
:type source: string
"""
self._append_to('_pri... | 0.004808 |
def set_current_context(self, name):
"""Set the current context in kubeconfig."""
if self.context_exists(name):
self.data['current-context'] = name
else:
raise KubeConfError("Context does not exist.") | 0.008065 |
def from_environment_or_defaults(cls, environment=None):
"""Create a Run object taking values from the local environment where possible.
The run ID comes from WANDB_RUN_ID or is randomly generated.
The run mode ("dryrun", or "run") comes from WANDB_MODE or defaults to "dryrun".
The run ... | 0.004692 |
def homepage(request):
'''
Context:
all_metadata
Templates:
- billy/web/public/homepage.html
'''
all_metadata = db.metadata.find()
return render(request, templatename('homepage'),
dict(all_metadata=all_metadata)) | 0.003676 |
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)
... | 0.010917 |
def hourly(place):
"""return data as list of dicts with all data filled in."""
# time in utc?
lat, lon = place
url = "https://api.forecast.io/forecast/%s/%s,%s?solar" % (APIKEY, lat,
lon)
w_data = json.loads(urllib2.urlopen(url).read())
... | 0.002183 |
def get_teams(self):
""" Return json current roster of team """
return self.make_request(host="erikberg.com", sport='nba',
method="teams", id=None,
format="json",
parameters={}) | 0.006849 |
def _make_plan(plan_dict):
""" Construct a Plan or ProfiledPlan from a dictionary of metadata values.
:param plan_dict:
:return:
"""
operator_type = plan_dict["operatorType"]
identifiers = plan_dict.get("identifiers", [])
arguments = plan_dict.get("args", [])
children = [_make_plan(chil... | 0.002963 |
def load(self, updates):
"""Load configuration data"""
# Go through in order and override the config (`.mbed_cloud_config.json` loader)
for path in self.paths():
if not path:
continue
abs_path = os.path.abspath(os.path.expanduser(path))
if not ... | 0.004704 |
def count_nonzero(data, mapper=None, blen=None, storage=None,
create='array', **kwargs):
"""Count the number of non-zero elements."""
return reduce_axis(data, reducer=np.count_nonzero,
block_reducer=np.add, mapper=mapper,
blen=blen, storage=storage... | 0.00289 |
def parse_spec(self, spec):
"""Parse the given spec into a `specs.Spec` object.
:param spec: a single spec string.
:return: a single specs.Specs object.
:raises: CmdLineSpecParser.BadSpecError if the address selector could not be parsed.
"""
if spec.endswith('::'):
spec_path = spec[:-len... | 0.015666 |
def create(self, email, verify=None, components=None):
"""Create a new subscriber
:param str email: Email address to subscribe
:param bool verify: Whether to send verification email
:param list components: Components ID list, defaults to all
:return: Created subscriber data (:cl... | 0.003328 |
def find_prop_overlap(rdf, prop1, prop2):
"""Generate (subject,object) pairs connected by two properties."""
for s, o in sorted(rdf.subject_objects(prop1)):
if (s, prop2, o) in rdf:
yield (s, o) | 0.004505 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.