text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def rebase(self, key, start=None, decimals=5):
"""Rebase a channel (key) on start.
The step (between elements) need to be constant all through,
else ValueError is raised. The exception to this is the border
step between data loaded from two different files.
key: int or str
... | 0.000933 |
def create_local_copy(self, effects=None, store=None):
"""Creates a Local File Copy on Uploadcare Storage.
Args:
- effects:
Adds CDN image effects. If ``self.default_effects`` property
is set effects will be combined with default effects.
- store:... | 0.0025 |
def import_demo_experience(self, states, internals, actions, terminal, reward):
"""
Stores demonstrations in the demo memory.
"""
fetches = self.import_demo_experience_output
feed_dict = self.get_feed_dict(
states=states,
internals=internals,
... | 0.004193 |
def LT(classical_reg1, classical_reg2, classical_reg3):
"""
Produce an LT instruction.
:param classical_reg1: Memory address to which to store the comparison result.
:param classical_reg2: Left comparison operand.
:param classical_reg3: Right comparison operand.
:return: A ClassicalLessThan ins... | 0.007215 |
def train(train_dir=None, train_csv=None, epochs=30, batch_size=32):
"""Function responsible for running the training the model."""
if not train_dir or not os.path.exists(train_dir) or not train_csv:
warnings.warn("No train directory could be found ")
return
# Make a dataset from the local ... | 0.003686 |
def _vis_calibrate(self, data):
"""Calibrate visible channels to reflectance."""
solar_irradiance = self['esun']
esd = self["earth_sun_distance_anomaly_in_AU"].astype(float)
factor = np.pi * esd * esd / solar_irradiance
res = data * factor
res.attrs = data.attrs
... | 0.004619 |
def integrate(self, outevent, inevent):
"""Propagate function time ratio along the function calls.
Must be called after finding the cycles.
See also:
- http://citeseer.ist.psu.edu/graham82gprof.html
"""
# Sanity checking
assert outevent not in self
for ... | 0.002457 |
def endSubscription(self, subscriber):
"""
Unregister a live subscription.
"""
self._reqId2Contract.pop(subscriber.reqId, None)
self.reqId2Subscriber.pop(subscriber.reqId, None) | 0.009217 |
async def open(self) -> 'Issuer':
"""
Explicit entry. Perform ancestor opening operations,
then synchronize revocation registry to tails tree content.
:return: current object
"""
LOGGER.debug('Issuer.open >>>')
await super().open()
for path_rr_id in Tai... | 0.004141 |
def call(fun, **kwargs):
'''
Directly call a function inside a loader directory
'''
args = kwargs.get('args', [])
dirs = kwargs.get('dirs', [])
funcs = LazyLoader(
[os.path.join(SALT_BASE_PATH, 'modules')] + dirs,
None,
tag='modules',
virtual_enable=False,
)
... | 0.002874 |
def create_machine(self, name=None, package=None, dataset=None,
metadata=None, tags=None, boot_script=None, credentials=False,
image=None, networks=None):
"""
::
POST /:login/machines
Provision a machine in the current
:py:class:`sma... | 0.007654 |
def Pack(cls, obj, version):
"""Pack the given object using AdWords-specific logic.
Args:
obj: an object to be packed for SOAP using AdWords-specific logic, if
applicable.
version: the version of the current API, e.g. 'v201809'
Returns:
The given object packed with AdWords-spec... | 0.004065 |
def enver(*args):
"""
%prog [<name>=[value]]
To show all environment variables, call with no parameters:
%prog
To Add/Modify/Delete environment variable:
%prog <name>=[value]
If <name> is PATH or PATHEXT, %prog will by default append the value using
a semicolon as a separator. Use -r to disable this behavio... | 0.028158 |
def report(zap_helper, output, output_format):
"""Generate XML, MD or HTML report."""
if output_format == 'html':
zap_helper.html_report(output)
elif output_format == 'md':
zap_helper.md_report(output)
else:
zap_helper.xml_report(output)
console.info('Report saved to "{0}"'.... | 0.002985 |
def ErrorMessage(text, **kwargs):
"""Show an error message dialog to the user.
This will raise a Zenity Error Dialog with a description of the error.
text - A description of the error.
kwargs - Optional command line parameters for Zenity such as height,
width, etc."""
args = ... | 0.006329 |
def _auto_adjust_panel_spans(dashboard):
'''Adjust panel spans to take up the available width.
For each group of panels that would be laid out on the same level, scale up
the unspecified panel spans to fill up the level.
'''
for row in dashboard.get('rows', []):
levels = []
current_... | 0.000711 |
def verifyChainFromCAPath(self, capath, untrusted_file=None):
"""
Does the same job as .verifyChainFromCAFile() but using the list
of anchors in capath directory. The directory should (only) contain
certificates files in PEM format. As for .verifyChainFromCAFile(),
a list of untr... | 0.001779 |
def get_file_list():
"""Return a list of strings corresponding to file names supplied by drag and drop or standard input."""
if len(sys.argv) > 1:
file_list = list(sys.argv[1:]) # make copy
else:
files_str = input('Select the files you want to process and drag and drop them onto this windo... | 0.009106 |
def campaign_name(self, campaign_name):
"""
Sets the campaign_name of this ServicePackageQuotaHistoryReservation.
Textual campaign name for this reservation.
:param campaign_name: The campaign_name of this ServicePackageQuotaHistoryReservation.
:type: str
"""
if ... | 0.007264 |
def _setDriftList(self, drift_length):
""" set drift length list of three elements
:param drift_length: input drift_length in [m], single float, or list/tuple of float numbers
"""
if isinstance(drift_length, tuple) or isinstance(drift_length, list):
if len(drift_length) == 1... | 0.003033 |
def CreateConstMuskingumXFile(x_value,
in_connectivity_file,
out_x_file):
"""
Create muskingum X file from value that is constant all the way through
for each river segment.
Parameters
----------
x_value: float
Value for the mu... | 0.000933 |
def get_importer(path_item):
"""Retrieve a PEP 302 "importer" for the given path item
If there is no importer, this returns a wrapper around the builtin import
machinery. The returned importer is only cached if it was created by a
path hook.
"""
try:
importer = sys.path_importer_cache[... | 0.002532 |
def _getInputImage (input,group=None):
""" Factory function to return appropriate imageObject class instance"""
# extract primary header and SCI,1 header from input image
sci_ext = 'SCI'
if group in [None,'']:
exten = '[sci,1]'
phdu = fits.getheader(input, memmap=False)
else:
... | 0.011729 |
def deephash(obj):
"""
Given an object, return a hash using HashableJSON. This hash is not
architecture, Python version or platform independent.
"""
try:
return hash(json.dumps(obj, cls=HashableJSON, sort_keys=True))
except:
return None | 0.007246 |
def get_memory_map_xml(self):
"""! @brief Generate GDB memory map XML.
"""
root = ElementTree.Element('memory-map')
for r in self._context.core.memory_map:
# Look up the region type name. Regions default to ram if gdb doesn't
# have a concept of the region type.
... | 0.008739 |
def volume(self):
"""
Volume of the simplex.
"""
return abs(np.linalg.det(self.T)) / math.factorial(self.space_dim) | 0.013605 |
def _token_to_subwords(self, token):
"""Greedily split token into subwords."""
subwords = []
start = 0
while start < len(token):
subword = None
for end in range(
min(len(token), start + self._max_subword_len), start, -1):
candidate = token[start:end]
if (candidate ... | 0.016345 |
def one(self):
"""Return exactly one record or raise an exception.
:return:
- Dictionary containing the only item in the response content
:raise:
- MultipleResults: If more than one records are present in the content
- NoResults: If the result is empty
... | 0.006849 |
def update_assessment_taken(self, assessment_taken_form):
"""Updates an existing assessment taken.
arg: assessment_taken_form
(osid.assessment.AssessmentTakenForm): the form
containing the elements to be updated
raise: IllegalState - ``assessment_taken_form``... | 0.003838 |
def process(name):
'''
Return whether the specified signature is found in the process tree. This
differs slightly from the services states, in that it may refer to a
process that is not managed via the init system.
'''
# Monitoring state, no changes will be made so no test interface needed
r... | 0.001203 |
def annotate_video(
self,
input_uri=None,
input_content=None,
features=None,
video_context=None,
output_uri=None,
location_id=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=Non... | 0.004461 |
def score_function(self, x, W):
# need refector
'''
Score function to calculate score
'''
score = self.sign * np.sign(x[self.feature_index] - self.theta)
return score | 0.013825 |
def configure(self, config):
"""
Configures component by passing configuration parameters.
:param config: configuration parameters to be set.
"""
self._timeout = config.get_as_long_with_default("options.timeout", self._default_timeout)
self._max_size = config.get_as_long... | 0.01061 |
def update(self, **kwargs):
"""Change the configuration of the resource on the device.
This method uses Http PUT alter the service state on the device.
The attributes of the instance will be packaged as a dictionary. That
dictionary will be updated with kwargs. It is then submitted a... | 0.002361 |
def records(account_id):
"""Fetch locks data
"""
s = boto3.Session()
table = s.resource('dynamodb').Table('Sphere11.Dev.ResourceLocks')
results = table.scan()
for r in results['Items']:
if 'LockDate' in r:
r['LockDate'] = datetime.fromtimestamp(r['LockDate'])
if 'Rev... | 0.001916 |
def color_palette(name=None, n_colors=6, desat=None):
"""Return a list of colors defining a color palette.
Availible seaborn palette names:
deep, muted, bright, pastel, dark, colorblind
Other options:
hls, husl, any matplotlib palette
Matplotlib paletes can be specified as reversed pa... | 0.000304 |
def forward_message(self, chat_id, from_chat_id, message_id, disable_notification=None):
"""
Use this method to forward messages of any kind.
:param disable_notification:
:param chat_id: which chat to forward
:param from_chat_id: which chat message from
:param message_id:... | 0.007737 |
def _rgb_triangle(ax, r_label, g_label, b_label, loc):
"""
Draw an RGB triangle legend on the desired axis
"""
if not loc in range(1, 11):
loc = 2
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
inset_ax = inset_axes(ax, width=1, height=1, loc=lo... | 0.00145 |
def update_translations(request):
"""
Update translations: delete orphan translations and creates empty translations for new objects in database.
"""
FieldTranslation.delete_orphan_translations()
num_translations = FieldTranslation.update_translations()
return render_to_response('modeltranslation/admin/update_tra... | 0.027363 |
def namedb_get_name_preorder( db, preorder_hash, current_block ):
"""
Get a (singular) name preorder record outstanding at the given block, given the preorder hash.
NOTE: returns expired preorders.
Return the preorder record on success.
Return None if not found.
"""
select_query = "SEL... | 0.015636 |
def set_bucket_props(self, bucket, props):
"""
Set the properties on the bucket object given
"""
bucket_type = self._get_bucket_type(bucket.bucket_type)
url = self.bucket_properties_path(bucket.name,
bucket_type=bucket_type)
heade... | 0.002766 |
def _accumulateFrequencyCounts(values, freqCounts=None):
"""
Accumulate a list of values 'values' into the frequency counts 'freqCounts',
and return the updated frequency counts
For example, if values contained the following: [1,1,3,5,1,3,5], and the initial
freqCounts was None, then the return value would b... | 0.012535 |
def convert(args):
"""
Download VM disks, and OVF from vCenter
:param args:
:return: created vmdk
"""
exporter = OvfExporter(user=args.vcenter_user,password=args.vcenter_pass, host=args.vcenter_host, port=args.vcenter_port,
vm_name=args.vm_name, dir=args.directory)
... | 0.008596 |
def minutes_for_session(self, session_label):
"""
Given a session label, return the minutes for that session.
Parameters
----------
session_label: pd.Timestamp (midnight UTC)
A session label whose session's minutes are desired.
Returns
-------
... | 0.003367 |
def exists(self, vars_list: List[str]) -> 'TensorFluent':
'''Returns the TensorFluent for the exists aggregation function.
Args:
vars_list: The list of variables to be aggregated over.
Returns:
A TensorFluent wrapping the exists aggregation function.
'''
... | 0.005263 |
def populate(self, priority, address, rtr, data):
"""
data bytes (high + low)
1 + 2 = current temp
3 + 4 = min temp
5 + 6 = max temp
:return: None
"""
assert isinstance(data, bytes)
self.needs_no_rtr(rtr)
self.needs_data(d... | 0.010582 |
def __gen_token_anno_file(self, top_level_layer):
"""
creates an etree representation of a <multiFeat> file that describes
all the annotations that only span one token (e.g. POS, lemma etc.).
Note: discoursegraphs will create one token annotation file for each
top level layer (e... | 0.00242 |
def get_updates(self, *args, **kwargs):
"""See :func:`get_updates`"""
return get_updates(*args, **self._merge_overrides(**kwargs)).run() | 0.013158 |
def modules(self):
"""
:return: dictionary {index: object} of all modules.
"""
if not self.get_objects_by_type('module'):
self.inventory()
return {int(c.index): c for c in self.get_objects_by_type('module')} | 0.007692 |
def cooccurrences(self, domain):
'''Get the cooccurrences of the given domain.
For details, see https://investigate.umbrella.com/docs/api#co-occurrences
'''
uri = self._uris["cooccurrences"].format(domain)
return self.get_parse(uri) | 0.010989 |
def fulfill(self, method, *args, **kwargs):
""" Fulfill an HTTP request to Keen's API. """
return getattr(self.session, method)(*args, **kwargs) | 0.012346 |
def log(self, _from=None, to=None):
"""Run git-log."""
command = ["git", "log"]
if _from:
to = "HEAD" if not to else to
revision_range = f"{_from}..{to}"
command.append(revision_range)
git_log_text = _run_command(command)
commit_text_lst = _... | 0.004684 |
def toposort_flatten(data, sort=True):
"""Returns a single list of dependencies. For any set returned by
toposort(), those items are sorted and appended to the result (just to
make the results deterministic)."""
result = []
for d in toposort(data):
try:
result.extend((sorted if sort els... | 0.00241 |
def get_instance(self, payload):
"""
Build an instance of DefaultsInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.autopilot.v1.assistant.defaults.DefaultsInstance
:rtype: twilio.rest.autopilot.v1.assistant.defaults.DefaultsInstance
"""
... | 0.007075 |
def genericCameraMatrix(shape, angularField=60):
'''
Return a generic camera matrix
[[fx, 0, cx],
[ 0, fy, cy],
[ 0, 0, 1]]
for a given image shape
'''
# http://nghiaho.com/?page_id=576
# assume that the optical centre is in the middle:
cy = int(shape[0] / 2)
cx ... | 0.001339 |
def set_hosts_file_entry_for_role(self, role_name, network_name='user-net', fqdn=None, domain_name=None):
"""Adds an entry to the hosts file for a scenario host given
the role name and network name
:param role_name: (str) role name of the host to add
:param network_name: (str) Name of t... | 0.005906 |
def user_cache_dir(self):
"""Return ``user_cache_dir``."""
directory = appdirs.user_cache_dir(self.appname, self.appauthor,
version=self.version)
if self.create:
self._ensure_directory_exists(directory)
return directory | 0.010239 |
def ln(label):
"""Draw a 70-char-wide divider, with label in the middle.
>>> ln('hello there')
'---------------------------- hello there -----------------------------'
"""
label_len = len(label) + 2
chunk = (70 - label_len) // 2
out = '%s %s %s' % ('-' * chunk, label, '-' * chunk)
pad =... | 0.002519 |
def parse_request(cls, request_string):
"""JSONRPC allows for **batch** requests to be communicated
as array of dicts. This method parses out each individual
element in the batch and returns a list of tuples, each
tuple a result of parsing of each item in the batch.
:Returns: ... | 0.003621 |
def pluralize(word, pos=NOUN, custom=None, classical=True):
""" Returns the plural of a given word, e.g., child => children.
Handles nouns and adjectives, using classical inflection by default
(i.e., where "matrix" pluralizes to "matrices" and not "matrixes").
The custom dictionary is for us... | 0.001785 |
def _make_agent(self, entrez_id, text_id):
"""Make an Agent object, appropriately grounded.
Parameters
----------
entrez_id : str
Entrez id number
text_id : str
A plain text systematic name, or None if not listed.
Returns
-------
... | 0.002782 |
def movMF(
X,
n_clusters,
posterior_type="soft",
force_weights=None,
n_init=10,
n_jobs=1,
max_iter=300,
verbose=False,
init="random-class",
random_state=None,
tol=1e-6,
copy_x=True,
):
"""Wrapper for parallelization of _movMF and running n_init times.
"""
if n... | 0.001115 |
def mousePressEvent( self, event ):
"""
Changes the current date to the clicked on date.
:param event | <QMousePressEvent>
"""
XPopupWidget.hideToolTip()
# update the current date
self.setCurrentDate(self.dateAt(event.scenePos()))
... | 0.018041 |
def analyze_string_content(self, string, line_num, filename):
"""Searches string for custom pattern, and captures all high entropy strings that
match self.regex, with a limit defined as self.entropy_limit.
"""
output = {}
for result in self.secret_generator(string):
... | 0.007619 |
def check_error(self, response, status, err_cd):
" Check an error in the response."
if 'status' not in response:
return False
if response['status'] != status:
return False
if 'msgs' not in response:
return False
if not isinstance(response['... | 0.003396 |
def convert_type(self, type):
"""Convert type to BigQuery
"""
# Mapping
mapping = {
'any': 'STRING',
'array': None,
'boolean': 'BOOLEAN',
'date': 'DATE',
'datetime': 'DATETIME',
'duration': None,
'geojso... | 0.002516 |
def decode_message(cls, protocol_version, user_type_map, stream_id, flags, opcode, body,
decompressor, result_metadata):
"""
Decodes a native protocol message body
:param protocol_version: version to use decoding contents
:param user_type_map: map[keyspace name] =... | 0.005053 |
def supprime(cls,table, **kwargs):
""" Remove entries matchin given condition
kwargs is a dict of column name : value , with length ONE.
"""
assert len(kwargs) == 1
field, value = kwargs.popitem()
req = f"""DELETE FROM {table} WHERE {field} = """ + cls.mark_style
... | 0.007937 |
def ensure_yx_order(func):
"""Wrap a function to ensure all array arguments are y, x ordered, based on kwarg."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
# Check what order we're given
dim_order = kwargs.pop('dim_order', None)
x_first = _is_x_first_dim(dim_order)
... | 0.005161 |
def load(self, fileobj):
'''Load the dict from the file object'''
# try formats from most restrictive to least restrictive
for loader in (pickle.load, json.load, csv.reader):
fileobj.seek(0)
try:
return self.initial_update(loader(fileobj))
exce... | 0.004785 |
def check(text):
"""Suggest the preferred forms.
source: Garner's Modern American Usage
source_url: http://bit.ly/1T4alrY
"""
err = "terms.denizen_labels.garner"
msg = "'{}' is the preferred denizen label."
preferences = [
["Afrikaner", ["Afrikaaner"]],
["Afrik... | 0.000471 |
def write_numeric_array(fd, header, array):
"""Write the numeric array"""
# make a memory file for writing array data
bd = BytesIO()
# write matrix header to memory file
write_var_header(bd, header)
if not isinstance(array, basestring) and header['dims'][0] > 1:
# list array data in co... | 0.001709 |
def VFSMultiOpen(pathspecs, progress_callback=None):
"""Opens multiple files specified by given path-specs.
See documentation for `VFSOpen` for more information.
Args:
pathspecs: A list of pathspec instances of files to open.
progress_callback: A callback function to call to notify about progress
Ret... | 0.008621 |
def scored_to_phenotype(self,phenotypes):
"""
Convert binary pehnotypes to mutually exclusive phenotypes.
If none of the phenotypes are set, then phenotype_label becomes nan
If any of the phenotypes are multiply set then it throws a fatal error.
Args:
phenotypes (li... | 0.015209 |
def _add_dependency(self, key, dependlist, i, isSubroutine, anexec):
"""Determines whether the item in the dependency list is a valid function
call by excluding local variables and members."""
#First determine if the reference is to a derived type variable
lkey = key.lower()
if "... | 0.0115 |
def on_remove_row(self, event, row_num=-1):
"""
Remove specified grid row.
If no row number is given, remove the last row.
"""
if row_num == -1:
default = (255, 255, 255, 255)
# unhighlight any selected rows:
for row in self.selected_rows:
... | 0.001231 |
async def get_historic_data(self, n_data):
"""Get historic data."""
query = gql(
"""
{
viewer {
home(id: "%s") {
consumption(resolution: HOURLY, last: %s) {
nodes {
f... | 0.002255 |
def build_url(api_key, spot_id, fields=None, unit=None,
start=None, end=None):
"""
This function builds the request url
API details https://magicseaweed.com/developer/forecast-api
key: Magic Seaweed API key
spot_id: The ID of a location, available from th... | 0.004614 |
def _joint_sample_n(self, n, seed=None):
"""Draw a joint sample from the prior over latents and observations."""
with tf.name_scope("sample_n_joint"):
stream = seed_stream.SeedStream(
seed, salt="LinearGaussianStateSpaceModel_sample_n_joint")
sample_and_batch_shape = distribution_util.pr... | 0.008092 |
def probabilities(items, params):
"""Compute the comparison outcome probabilities given a subset of items.
This function computes, for each item in ``items``, the probability that it
would win (i.e., be chosen) in a comparison involving the items, given
model parameters.
Parameters
----------
... | 0.001658 |
def _check_delete_fw(self, tenant_id, drvr_name):
"""Deletes the Firewall, if all conditioms are met.
This function after modifying the DB with delete operation status,
calls the routine to remove the fabric cfg from DB and unconfigure
the device.
"""
fw_dict = self.fwid... | 0.002621 |
def add_record(self, record):
"""Add a record to the OAISet.
:param record: Record to be added.
:type record: `invenio_records.api.Record` or derivative.
"""
record.setdefault('_oai', {}).setdefault('sets', [])
assert not self.has_record(record)
record['_oai'][... | 0.005797 |
def _get_port_range(range_str):
""" Given a string with a port or port range: '80', '80-120'
Returns tuple with range start and end ports: (80, 80), (80, 120)
"""
if range_str == '*':
return PortsRangeHelper.PortsRange(start=0, end=65535)
s = range_str.split('-')... | 0.004008 |
def write_chapter(self):
"""
Create a chapter
that contains a random number
of paragraphs
"""
self.paragraphs = []
self.paragraphs.append('\n')
for x in range(randint(0, 50)):
p = Paragraph(self.model)
self.paragraphs.append(p.get_p... | 0.004963 |
def run_algorithm(start,
end,
initialize,
capital_base,
handle_data=None,
before_trading_start=None,
analyze=None,
data_frequency='daily',
bundle='quantopian-quandl',
... | 0.000217 |
def _get_targets_by_declared_platform_with_placeholders(self, targets_by_platform):
"""
Aggregates a dict that maps a platform string to a list of targets that specify the platform.
If no targets have platforms arguments, return a dict containing platforms inherited from
the PythonSetup object.
:pa... | 0.011858 |
def Get(self, name, default=utils.NotAValue, context=None):
"""Get the value contained by the named parameter.
This method applies interpolation/escaping of the named parameter and
retrieves the interpolated value.
Args:
name: The name of the parameter to retrieve. This should be in the format
... | 0.007256 |
def chebyshev(point1, point2):
"""Computes distance between 2D points using chebyshev metric
:param point1: 1st point
:type point1: list
:param point2: 2nd point
:type point2: list
:returns: Distance between point1 and point2
:rtype: float
"""
return max(abs(point1[0] - point2[0]),... | 0.002874 |
def BC_Rigidity(self):
"""
Utility function to help implement boundary conditions by specifying
them for and applying them to the elastic thickness grid
"""
#########################################
# FLEXURAL RIGIDITY BOUNDARY CONDITIONS #
#########################################
# W... | 0.0235 |
def MatrixDiagPart(a):
"""
Batched diag op that returns only the diagonal elements.
"""
r = np.zeros(a.shape[:-2] + (min(a.shape[-2:]),))
for coord in np.ndindex(a.shape[:-2]):
pos = coord + (Ellipsis,)
r[pos] = np.diagonal(a[pos])
return r, | 0.003559 |
def remove_nesting(dom, tag_name):
"""
Unwrap items in the node list that have ancestors with the same tag.
"""
for node in dom.getElementsByTagName(tag_name):
for ancestor in ancestors(node):
if ancestor is node:
continue
if ancestor is dom.documentElemen... | 0.002273 |
def power_cycle_vm(virtual_machine, action='on'):
'''
Powers on/off a virtual machine specified by it's name.
virtual_machine
vim.VirtualMachine object to power on/off virtual machine
action
Operation option to power on/off the machine
'''
if action == 'on':
try:
... | 0.001529 |
def manual_update_license(self, fd, filename='cdrouter.lic'):
"""Update the license on your CDRouter system manually by uploading a
.lic license from the CDRouter Support Lounge.
:param fd: File-like object to upload.
:param filename: (optional) Filename to use for license as string.
... | 0.00319 |
def Bahadori_gas(T, MW):
r'''Estimates the thermal conductivity of hydrocarbons gases at low P.
Fits their data well, and is useful as only MW is required.
Y is the Molecular weight, and X the temperature.
.. math::
K = a + bY + CY^2 + dY^3
a = A_1 + B_1 X + C_1 X^2 + D_1 X^3
... | 0.003049 |
def add_dict_to_hash(a_hash, a_dict):
"""Adds `a_dict` to `a_hash`
Args:
a_hash (`Hash`): the secure hash, e.g created by hashlib.md5
a_dict (dict[string, [string]]): the dictionary to add to the hash
"""
if a_dict is None:
return
for k, v in a_dict.items():
a_hash.up... | 0.005222 |
def _set_mirror(self, v, load=False):
"""
Setter method for mirror, mapped from YANG variable /openflow_global/openflow/mirror (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_mirror is considered as a private
method. Backends looking to populate this vari... | 0.006046 |
def _pack(cls, tensors):
"""Pack a list of `Tensor`s into a single, flattened, rank-1 `Tensor`."""
if not tensors:
return None
elif len(tensors) == 1:
return array_ops.reshape(tensors[0], [-1])
else:
flattened = [array_ops.reshape(tensor, [-1]) for tensor in tensors]
return array... | 0.014493 |
def build_time(start_time):
"""
Calculate build time per package
"""
diff_time = round(time.time() - start_time, 2)
if diff_time <= 59.99:
sum_time = str(diff_time) + " Sec"
elif diff_time > 59.99 and diff_time <= 3599.99:
sum_time = round(diff_time / 60, 2)
sum_time_list... | 0.001302 |
def replace_in_file(workspace, src_file_path, from_str, to_str):
"""Replace from_str with to_str in the name and content of the given file.
If any edits were necessary, returns the new filename (which may be the same as the old filename).
"""
from_bytes = from_str.encode('ascii')
to_bytes = to_str.encode('as... | 0.013889 |
def checkout(repo, ref):
"""Checkout a repoself."""
# Delete local branch if it exists, remote branch will be tracked
# automatically. This prevents stale local branches from causing problems.
# It also avoids problems with appending origin/ to refs as that doesn't
# work with tags, SHAs, and upstre... | 0.000826 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.