text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def get_default_config_help(self):
"""
Returns the help text for the configuration options for this handler
"""
config = super(LibratoHandler, self).get_default_config_help()
config.update({
'user': 'Librato username',
'apikey': 'Librato API key',
... | 0.005272 |
def sequential_connect(self):
"""
Sequential connect is designed to return a connection to the
Rendezvous Server but it does so in a way that the local port
ranges (both for the server and used for subsequent hole
punching) are allocated sequentially and predictably. This is... | 0.001309 |
def form_field(self):
"Returns appropriate form field."
label = unicode(self)
defaults = dict(required=False, label=label, widget=self.widget)
defaults.update(self.extra)
return self.field_class(**defaults) | 0.00813 |
def get_subset_ids(path):
""" Return a list with ids of all available subsets (based on existing csv-files). """
all = []
for path in glob.glob(os.path.join(path, '*.tsv')):
file_name = os.path.split(path)[1]
basename = os.path.splitext(file_name)[0]
all.appe... | 0.008523 |
def init(self, address, hard_reset=False):
"""Open the serial connection to a dongle at the supplied address.
Args:
address (str): the serial port address of the BLED112 dongle, e.g. 'COM5'
hard_reset (bool): not currently used
Returns:
True if a connection ... | 0.006138 |
def get_projected_player_game_stats_by_player(self, season, week, player_id):
"""
Projected Player Game Stats by Player
"""
result = self._method_call("PlayerGameProjectionStatsByPlayerID/{season}/{week}/{player_id}", "projections", season=season, week=week, player_id=player_id)
... | 0.009009 |
def ansi_format( self, width=64, height=12 ):
"""Return a human readable ANSI-terminal printout of the stats.
width
Custom width for the graph (in characters).
height
Custom height for the graph (in characters).
"""
from mrcrowbar.ansi import format_bar_... | 0.032258 |
def validate_doc(schema_names, # type: Names
doc, # type: Union[Dict[Text, Any], List[Dict[Text, Any]], Text, None]
loader, # type: Loader
strict, # type: bool
strict_foreign_properties=False # type: bool
):
... | 0.001151 |
def _varFindLimitSpace(basedir, vars, space, part, lookup_fatal, depth):
''' limits the search space of space to part
basically does space.get(part, None), but with
templating for part and a few more things
'''
# Previous part couldn't be found, nothing to limit to
if space is None:
... | 0.001708 |
def get_stp_mst_detail_output_cist_port_internal_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
... | 0.003165 |
def _dispatch(self, stmt, stage, *args):
"""Construct and call an assembly function.
This function constructs the name of the assembly function based on
the type of statement, the corresponding policy and the stage
of assembly. It then calls that function to perform the assembly
... | 0.002402 |
def main(argv=None):
"""
Print accuracies
"""
try:
_name_of_script, filepath = argv
except ValueError:
raise ValueError(argv)
print_accuracies(filepath=filepath, test_start=FLAGS.test_start,
test_end=FLAGS.test_end, which_set=FLAGS.which_set,
nb_iter=FLAGS.nb_it... | 0.012315 |
def run_triggers(step, pre_post, args=(), **kwargs):
'''
step, pre_post-->str: Looked up in CONFIG_VAR
step must be key in CONFIG_VAR
pre_post must be key in CONFIG_VAR[step]
args-->tuple: Passed to run_in_order()
'''
if not isinstance(step, str) o... | 0.001668 |
def pop(self):
"""Pops the data stack, returning the value."""
try:
return self.data_stack.pop()
except errors.MachineError as e:
raise errors.MachineError("%s: At index %d in code: %s" %
(e, self.instruction_pointer, self.code_string)) | 0.009868 |
def gauge(key, gauge=None, default=float("nan"), **dims):
"""Adds gauge with dimensions to the global pyformance registry"""
return global_registry().gauge(key, gauge=gauge, default=default, **dims) | 0.004854 |
def get_results(self):
'''
:return: result from running the task
'''
self._event.wait()
if self._exception is not None:
#
# Well... rethrownig the exception caught in execute
# but on the caller thread
#
raise self._exce... | 0.005291 |
def is_executable(value,
**kwargs):
"""Indicate whether ``value`` is an executable file.
.. caution::
This validator does **NOT** work correctly on a Windows file system. This
is due to the vagaries of how Windows manages its file system and the
various ways in which it can... | 0.002458 |
def get_foreign_id(self, idspace='musicbrainz', cache=True):
"""Get the foreign id for this artist for a specific id space
Args:
Kwargs:
idspace (str): A string indicating the idspace to fetch a foreign id for.
Returns:
A foreign ID stri... | 0.010397 |
def type(self, sequence_coverage_collection,
min_gene_percent_covg_threshold=99):
"""Types a collection of genes returning the most likely gene version
in the collection with it's genotype"""
best_versions = self.get_best_version(
sequence_coverage_collection.values(... | 0.006342 |
def estimate(self, upgrades):
"""Estimate the time needed to apply upgrades.
If an upgrades does not specify and estimate it is assumed to be
in the order of 1 second.
:param upgrades: List of upgrades sorted in topological order.
"""
val = 0
for u in upgrades:
... | 0.005405 |
def serializable_value(self, obj):
''' Produce the value as it should be serialized.
Sometimes it is desirable for the serialized value to differ from
the ``__get__`` in order for the ``__get__`` value to appear simpler
for user or developer convenience.
Args:
obj (... | 0.003759 |
def stream(self):
"""Returns a stream object (:func:`file`, :class:`~io.BytesIO` or
:class:`~StringIO.StringIO`) on the data."""
if not hasattr(self, '_stream'):
if self.file is not None:
self._stream = self.file
elif self.filename is not None:
... | 0.003067 |
def dt_to_qdatetime(dt):
"""Convert a python datetime.datetime object to QDateTime
:param dt: the datetime object
:type dt: :class:`datetime.datetime`
:returns: the QDateTime conversion
:rtype: :class:`QtCore.QDateTime`
:raises: None
"""
return QtCore.QDateTime(QtCore.QDate(dt.year, dt.... | 0.002451 |
def get_current_user():
"""
Return a TOKEN_USER for the owner of this process.
"""
process = OpenProcessToken(
ctypes.windll.kernel32.GetCurrentProcess(), TokenAccess.TOKEN_QUERY
)
return GetTokenInformation(process, TOKEN_USER) | 0.003846 |
def drop(self,arg):
""" overload of pandas.DataFrame.drop()
Parameters
----------
arg : iterable
argument to pass to pandas.DataFrame.drop()
Returns
-------
Ensemble : Ensemble
"""
df = super(Ensemble,self).drop(arg)
... | 0.016713 |
def InteractiveShellCommand(cls, conn, cmd=None, strip_cmd=True, delim=None, strip_delim=True, clean_stdout=True):
"""Retrieves stdout of the current InteractiveShell and sends a shell command if provided
TODO: Should we turn this into a yield based function so we can stream all output?
Args:
... | 0.003715 |
def get_minions():
'''
Return a list of minions
'''
serv = _get_serv(ret=None)
sql = "select distinct(id) from returns"
data = serv.query(sql)
ret = []
if data:
for jid in data[0]['points']:
ret.append(jid[1])
return ret | 0.003597 |
def run_bash_jobs(
jobs: Iterator[Job], directory: PathLike = Path.cwd(), dry_run: bool = False
) -> None:
"""Submit commands to the bash shell.
This function runs the commands iteratively but handles errors in the
same way as with the pbs_commands function. A command will run for all
combinations ... | 0.001471 |
def to_dense_one_hot(labels, class_count):
"""Converts a vector that specified one-hot per batch into a dense version.
Args:
labels: The labels input.
class_count: The number of classes as an int.
Returns:
One dense vector for each item in the batch.
Raises:
ValueError: If labels is not rank 1.... | 0.011471 |
def execute_from_command_line(argv=None):
"""
A simple method that runs a ManagementUtility.
"""
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "colab.settings")
from django.conf import settings
if not hasattr(settings, 'SECRET_KEY') and 'initconfig' in sys.argv:
command = initconfig.C... | 0.00232 |
def _register_trade(self, order):
""" constructs trade info from order data """
if order['id'] in self.orders.recent:
orderId = order['id']
else:
orderId = order['parentId']
# entry / exit?
symbol = order["symbol"]
order_data = self.orders.recent[o... | 0.001515 |
def get_location(self, ip, detailed=False):
"""Returns a dictionary with location data or False on failure.
Amount of information about IP contained in the dictionary depends
upon `detailed` flag state.
"""
seek = self._get_pos(ip)
if seek > 0:
return self.... | 0.005236 |
def build_kal_scan_band_string(kal_bin, band, args):
"""Return string for CLI invocation of kal, for band scan."""
option_mapping = {"gain": "-g",
"device": "-d",
"error": "-e"}
if not sanity.scan_band_is_valid(band):
err_txt = "Unsupported band designatio... | 0.001984 |
def get_files(files, extnames=['.root']):
"""Extract a list of file paths from a list containing both paths
and file lists with one path per line."""
files_out = []
for f in files:
mime = mimetypes.guess_type(f)
if os.path.splitext(f)[1] in extnames:
files_out += [f]
... | 0.001946 |
def countdown(template, duration=datetime.timedelta(seconds=5)):
"""
Do a countdown for duration, printing the template (which may accept one
positional argument). Template should be something like
``countdown complete in {} seconds.``
"""
now = datetime.datetime.now()
deadline = now + duration
remaining = dead... | 0.029641 |
def filter_indices(self, options, verbosity, *args, **kwargs):
"""Filter indices and execute an action for each index."""
index_name_map = {
index.__class__.__name__: index
for index in index_builder.indexes
}
# Process includes.
if options['index']:
... | 0.002786 |
def get_readable_filesize(size):
"""get_readable_filesize(size) -> filesize -- return human readable
filesize from given size in bytes.
"""
if(size < 1024):
return str(size)+' bytes'
temp = size/1024.0
level = 1
while(temp >= 1024 and level< 3):
temp = temp/1024
level += 1
if(level == 1):
return str(ro... | 0.050926 |
def share(self, file_ids, pwd=None, **kwargs):
"""
创建一个文件的分享链接
:param file_ids: 要分享的文件fid列表
:type file_ids: list
:param pwd: 分享密码,没有则没有密码
:type pwd: str
:return: requests.Response 对象
.. note::
返回正确
{
... | 0.001689 |
def readonce(self, size = None):
"""
Read from current buffer. If current buffer is empty, returns an empty string. You can use `prepareRead`
to read the next chunk of data.
This is not a coroutine method.
"""
if self.eof:
raise EOFError
if se... | 0.008152 |
def dict_key(self):
"""
Find the next key in a dict. We skip any newlines and check for if the
dict has ended.
"""
while True:
token = self.next()
t_value = token["value"]
if t_value == "\n":
continue
if t_value == ... | 0.004073 |
def build_ascii_property_table(output):
"""Build and write out Unicode property table."""
if not os.path.exists(output):
os.mkdir(output)
gen_properties(output, ascii_props=True, append=True) | 0.004717 |
def prt_tsv(prt, data_nts, **kws):
"""Print tab-separated table headers and data"""
# User-controlled printing options
prt_tsv_hdr(prt, data_nts, **kws)
return prt_tsv_dat(prt, data_nts, **kws) | 0.004785 |
def getCellVertexes(self, i, j):
"""
Edge coordinates of an hexagon centered in (x,y) having a side of d:
[x-d/2, y+sqrt(3)*d/2] [x+d/2, y+sqrt(3)*d/2]
[x-d, y] [x+d, y]
[x-d/2,... | 0.019822 |
def matomo(parser, token):
"""
Matomo tracking template tag.
Renders Javascript code to track page visits. You must supply
your Matomo domain (plus optional URI path), and tracked site ID
in the ``MATOMO_DOMAIN_PATH`` and the ``MATOMO_SITE_ID`` setting.
Custom variables can be passed in the `... | 0.001344 |
def atleast_nd(n, u):
"""
If the input array has fewer than n dimensions, append singleton
dimensions so that it is n dimensional. Note that the interface
differs substantially from that of :func:`numpy.atleast_3d` etc.
Parameters
----------
n : int
Minimum number of required dimensio... | 0.001805 |
def ensure_session(engine_or_session):
"""
If it is an engine, then create a session from it. And indicate that
this session should be closed after the job done.
"""
if isinstance(engine_or_session, Engine):
ses = sessionmaker(bind=engine_or_session)()
auto_close = True
elif isin... | 0.002268 |
def hfd(X, Kmax):
""" Compute Hjorth Fractal Dimension of a time series X, kmax
is an HFD parameter
"""
L = []
x = []
N = len(X)
for k in range(1, Kmax):
Lk = []
for m in range(0, k):
Lmk = 0
for i in range(1, int(numpy.floor((N - m) / k))):
... | 0.00161 |
def add_host(host):
""" Put your host information in the prefix object. """
p = new_prefix()
p.prefix = str(host['ipaddr'])
p.type = "host"
p.description = host['description']
p.node = host['fqdn']
p.avps = {}
# Use remaining data from ipplan to populate comment field.
if 'additiona... | 0.001381 |
def remove_semantic_data(self, path_as_list):
""" Removes a entry from the semantic data vividict.
:param list path_as_list: The path of the vividict to delete.
:return: removed value or dict
"""
if len(path_as_list) == 0:
raise AttributeError("The argument path_as_l... | 0.004615 |
def limit_gen(limit, iterable):
'''A generator that applies a count `limit`.'''
limit = int(limit)
assert limit >= 0, 'negative limit'
for item in iterable:
if limit <= 0:
break
yield item
limit -= 1 | 0.026549 |
def export(self, path, epoch=0):
"""Export HybridBlock to json format that can be loaded by
`SymbolBlock.imports`, `mxnet.mod.Module` or the C++ interface.
.. note:: When there are only one input, it will have name `data`. When there
Are more than one inputs, they will be name... | 0.007273 |
def get_console_output(self, instance_id):
"""Get the console output for a single instance."""
InstanceIDParam = {"InstanceId": instance_id}
query = self.query_factory(
action="GetConsoleOutput", creds=self.creds,
endpoint=self.endpoint, other_params=InstanceIDParam)
... | 0.004963 |
def sel_entries(self):
"""Generator which returns all SEL entries."""
ENTIRE_RECORD = 0xff
rsp = self.send_message_with_name('GetSelInfo')
if rsp.entries == 0:
return
reservation_id = self.get_sel_reservation_id()
next_record_id = 0
while True:
... | 0.001312 |
def department(self):
"""
| Description: The ID of the department to which the chat is directed
"""
if self.api and self.department_id:
return self.api._get_department(self.department_id) | 0.008621 |
def validate(self, instance, value):
"""Check if value is a string, and strips it and changes case"""
value_type = type(value)
if not isinstance(value, string_types):
self.error(instance, value)
if self.regex is not None and self.regex.search(value) is None: #pylint: d... | 0.005464 |
def stats(self):
"""
Return storage statistics about the library
Returns
-------
dictionary of storage stats
"""
res = {}
db = self._collection.database
conn = db.connection
res['sharding'] = {}
try:
sharding = conn.co... | 0.003591 |
def returnDepositsWithdrawals(self, start=0, end=2**32-1):
"""Returns your deposit and withdrawal history within a range,
specified by the "start" and "end" POST parameters, both of which
should be given as UNIX timestamps."""
return self._private('returnDepositsWithdrawals', start=start... | 0.006061 |
def _prepare_init_params_from_job_description(cls, job_details):
"""Convert the transform job description to init params that can be handled by the class constructor
Args:
job_details (dict): the returned job details from a describe_transform_job API call.
Returns:
dict... | 0.008529 |
def plot(self, flip=False, ax_channels=None, ax=None, *args, **kwargs):
"""
{_gate_plot_doc}
"""
if ax == None:
ax = pl.gca()
if ax_channels is not None:
flip = self._find_orientation(ax_channels)
plot_func = ax.axes.axhline if flip else ax.axes.... | 0.005941 |
def _getPath():
""" Returns Chrome's cookie database path
Returns
str - Google Chrome's cookie database path
"""
if os.name == "posix":
path = os.getenv("HOME") + "/.config/google-chrome/Default/Cookies"
return path
... | 0.012579 |
def to_xdr_object(self):
"""Creates an XDR Operation object that represents this
:class:`AccountMerge`.
"""
destination = account_xdr_object(self.destination)
self.body.type = Xdr.const.ACCOUNT_MERGE
self.body.destination = destination
return super(AccountMerge,... | 0.005848 |
def _get_boot_time_aix():
'''
Return the number of seconds since boot time on AIX
t=$(LC_ALL=POSIX ps -o etime= -p 1)
d=0 h=0
case $t in *-*) d=${t%%-*}; t=${t#*-};; esac
case $t in *:*:*) h=${t%%:*}; t=${t#*:};; esac
s=$((d*86400 + h*3600 + ${t%%:*}*60 + ${t#*:}))
t is 7-20:46:46
... | 0.002805 |
def begin_auth(request):
"""The view function that initiates the entire handshake.
For the most part, this is 100% drag and drop.
"""
# Instantiate Twython with the first leg of our trip.
twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET)
# Request an authorization url to send th... | 0.005682 |
def callproc(self, procname, parameters = (), cursorClass = DictCursor, quiet = False):
"""Calls a MySQL stored procedure procname. This uses DictCursor by default."""
i = 0
errcode = 0
caughte = None
while i < self.numTries:
i += 1
try:
cursor = self.connection.cursor(cursorClass)
if type(para... | 0.045908 |
def all(self, domain=None):
"""
Gets the messages within a given domain.
If domain is None, it returns all messages.
@type id: The
@param id: message id
@rtype: dict
@return: A dict of messages
"""
if domain is None:
return {k: dict(... | 0.004819 |
def on_current_tab_changed(self):
"""
Update action states when the current tab changed.
"""
self.menuEdit.clear()
self.menuModes.clear()
self.menuPanels.clear()
editor = self.tabWidget.current_widget()
self.menuEdit.setEnabled(editor is not None)
... | 0.002245 |
def tophat_alignment_plot (self):
""" Make the HighCharts HTML to plot the alignment rates """
# Specify the order of the different possible categories
keys = OrderedDict()
keys['aligned_not_multimapped_discordant'] = { 'color': '#437bb1', 'name': 'Aligned' }
keys['aligned_multi... | 0.02659 |
def __create_admin_entry(self, handleowner, permissions, index, handle, ttl=None):
'''
Create an entry of type "HS_ADMIN".
:param username: The username, i.e. a handle with an index
(index:prefix/suffix). The value referenced by the index contains
authentcation informati... | 0.008309 |
def setup_prjs_signals(self, ):
"""Setup the signals for the projects page
:returns: None
:rtype: None
:raises: None
"""
log.debug("Setting up projects page signals.")
self.prjs_prj_view_pb.clicked.connect(self.prjs_view_prj)
self.prjs_prj_create_pb.click... | 0.005682 |
def eat_line(self):
"""Move current position forward until the next line."""
if self.eos:
return None
eat_length = self.eat_length
get_char = self.get_char
has_space = self.has_space
while has_space() and get_char() != '\n':
eat_length(1)
e... | 0.006024 |
def instagram_scrap_profile(username):
"""
Scrap an instagram profile page
:param username:
:return:
"""
try:
url = "https://www.instagram.com/{}/".format(username)
page = requests.get(url)
# Raise error for 404 cause by a bad profile name
page.raise_for_status()
... | 0.001773 |
def populate_class_members(self, element_cls, prop_name):
"""
Add the appropriate methods to *element_cls*.
"""
self._element_cls = element_cls
self._prop_name = prop_name
self._add_attr_property() | 0.00813 |
def from_shapely(geometry, label=None):
"""
Create a MultiPolygon from a Shapely MultiPolygon, a Shapely Polygon or a Shapely GeometryCollection.
This also creates all necessary Polygons contained by this MultiPolygon.
Parameters
----------
geometry : shapely.geometry.M... | 0.005984 |
def max_min_col_update(self):
"""
Determines the maximum and minimum number in each column.
The result is a list whose k-th entry is [vmax, vmin], where vmax and
vmin denote the maximum and minimum of the k-th column (ignoring NaN).
This list is stored in self.max_min_col... | 0.003647 |
def strptime(cls, data, format, scale=DEFAULT_SCALE): # pragma: no cover
"""Convert a string representation of a date to a Date object
"""
return cls(datetime.strptime(data, format), scale=scale) | 0.009091 |
def getLabels(self, start=None, end=None):
"""
Get the labels on classified points within range start to end. Not inclusive
of end.
:returns: (dict) with format:
::
{
'isProcessing': boolean,
'recordLabels': list of results
}
``isProcessing`` - current... | 0.010453 |
def _readFile(self, fname, sldir):
'''
private method that reads in and organizes the .DAT file
Loads the data of the .DAT File into the variables cattrs and cols.
In both these cases they are dictionaries, but in the case of cols,
it is a dictionary of numpy array exect for the ... | 0.015374 |
def eval(self, data, name='eval', iteration=0):
"""Evaluate the model on mat.
Parameters
----------
data : DMatrix
The dmatrix storing the input.
name : str, optional
The name of the dataset.
iteration : int, optional
The current ite... | 0.003766 |
def build_struct_type(s_sdt):
'''
Build an xsd complexType out of a S_SDT.
'''
s_dt = nav_one(s_sdt).S_DT[17]()
struct = ET.Element('xs:complexType', name=s_dt.name)
first_filter = lambda selected: not nav_one(selected).S_MBR[46, 'succeeds']()
s_mbr = nav_any(s_sdt).S_MBR[44](first... | 0.010292 |
def user_func(func, arg_types=None, return_type=None):
"""Create an EFILTER-callable version of function 'func'.
As a security precaution, EFILTER will not execute Python callables
unless they implement the IApplicative protocol. There is a perfectly good
implementation of this protocol in the standard... | 0.000631 |
def libvlc_media_player_get_agl(p_mi):
'''Get the agl handler previously set with L{libvlc_media_player_set_agl}().
@param p_mi: the Media Player.
@return: the agl handler or 0 if none where set.
'''
f = _Cfunctions.get('libvlc_media_player_get_agl', None) or \
_Cfunction('libvlc_media_playe... | 0.007229 |
def cancel_signature_request(self, signature_request_id):
''' Cancels a SignatureRequest
Cancels a SignatureRequest. After canceling, no one will be able to sign
or access the SignatureRequest or its documents. Only the requester can
cancel and only before everyone has signed.
... | 0.006768 |
def update(self):
"""
Updates the #rules_map dictionary and #skippable_rules list based on the
#rules list. Must be called after #rules or any of its items have been
modified. The same rule name may appear multiple times.
# Raises
TypeError: if an item in the `rules` list is not a rule.
"""... | 0.006369 |
def control_change(self, channel, control, value):
"""Send a control change message.
See the MIDI specification for more information.
"""
if control < 0 or control > 128:
return False
if value < 0 or value > 128:
return False
self.cc_event(channel... | 0.006186 |
def _parse(self, context=0, push=True):
"""Parse the wikicode string, using *context* for when to stop."""
if push:
self._push(context)
while True:
this = self._read()
if self._context & contexts.UNSAFE:
if not self._verify_safe(this):
... | 0.001405 |
def _tarjan_head(ctx, v):
""" Used by @tarjan and @tarjan_iter. This is the head of the
main iteration """
ctx.index[v] = len(ctx.index)
ctx.lowlink[v] = ctx.index[v]
ctx.S.append(v)
ctx.S_set.add(v)
it = iter(ctx.g.get(v, ()))
ctx.T.append((it,False,... | 0.015244 |
def _str(value, depth):
"""
FOR DEBUGGING POSSIBLY RECURSIVE STRUCTURES
"""
output = []
if depth >0 and _get(value, CLASS) in data_types:
for k, v in value.items():
output.append(str(k) + "=" + _str(v, depth - 1))
return "{" + ",\n".join(output) + "}"
elif depth >0 an... | 0.006085 |
def do_gate_matrix(self, matrix: np.ndarray,
qubits: Sequence[int]) -> 'AbstractQuantumSimulator':
"""
Apply an arbitrary unitary; not necessarily a named gate.
:param matrix: The unitary matrix to apply. No checks are done
:param qubits: A list of qubits to apply... | 0.006787 |
def directory_to_pif(directory, **kwargs):
"""
Convert a directory to a pif
:param directory: Directory to convert to a pif
:param kwargs: any additional keyword arguments. (See `files_to_pif`)
:return: the created pif
"""
# Get the files
files = [os.path.join(directory, f) for f in os.... | 0.002183 |
def get_key_signature(key='C'):
"""Return the key signature.
0 for C or a, negative numbers for flat key signatures, positive numbers
for sharp key signatures.
"""
if not is_valid_key(key):
raise NoteFormatError("unrecognized format for key '%s'" % key)
for couple in keys:
if k... | 0.002421 |
def call_runtime(self):
'''
Execute the runtime
'''
cache = self.gather_cache()
chunks = self.get_chunks()
interval = self.opts['thorium_interval']
recompile = self.opts.get('thorium_recompile', 300)
r_start = time.time()
while True:
ev... | 0.001919 |
def main():
''' Execute the "bokeh" command line program.
'''
import sys
from bokeh.command.bootstrap import main as _main
# Main entry point (see setup.py)
_main(sys.argv) | 0.010152 |
def nvmlDeviceGetMemoryErrorCounter(handle, errorType, counterType, locationType):
r"""
/**
* Retrieves the requested memory error counter for the device.
*
* For Fermi &tm; or newer fully supported devices.
* Requires \a NVML_INFOROM_ECC version 2.0 or higher to report aggregate location-ba... | 0.006964 |
def actor_url(parser, token):
"""
Renders the URL for a particular actor instance
::
<a href="{% actor_url request.user %}">View your actions</a>
<a href="{% actor_url another_user %}">{{ another_user }}'s actions</a>
"""
bits = token.split_contents()
if len(bits) != 2:
... | 0.002016 |
def command(self, rule, **options):
"""\
direct=False, override=True, inject=False, flags=0
"""
options.setdefault("direct", False)
options.setdefault("override", True)
options.setdefault("inject", False)
options.setdefault("flags", 0)
if not options["dire... | 0.003632 |
def get_cli_string(path=None, action=None, key=None, value=None, quote=None):
"""Returns a string suitable for running as a shell script.
Useful for converting a arguments passed to a fabric task
to be passed to a `local` or `run` command.
"""
command = ['dotenv']
if quote:
command.appe... | 0.001443 |
def delete_host(zone, name, keyname, keyfile, nameserver, timeout, port=53,
keyalgorithm='hmac-md5'):
'''
Delete both forward (A) and reverse (PTR) records for a host only if the
forward (A) record exists.
CLI Example:
.. code-block:: bash
salt-run ddns.delete_host domain.... | 0.001198 |
def _dict_mapping_to_pb(mapping, proto_type):
"""
Convert a dict to protobuf.
Args:
mapping (dict): A dict that needs to be converted to protobuf.
proto_type (str): The type of the Protobuf.
Returns:
An instance of the specified protobuf.
"""
converted_pb = getattr(trac... | 0.002494 |
def edit(self, tag_name=None, target_commitish=None, name=None, body=None,
draft=None, prerelease=None):
"""Users with push access to the repository can edit a release.
If the edit is successful, this object will update itself.
:param str tag_name: (optional), Name of the tag to u... | 0.002049 |
def connect(self, addr):
"""Initiate a connection request to the peer router."""
if _debug: RouterToRouterService._debug("connect %r", addr)
# make a connection
conn = ConnectionState(addr)
self.multiplexer.connections[addr] = conn
# associate with this service, but it ... | 0.005384 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.