text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def get_method_name(method):
"""
Returns given method name.
:param method: Method to retrieve the name.
:type method: object
:return: Method name.
:rtype: unicode
"""
name = get_object_name(method)
if name.startswith("__") and not name.endswith("__"):
name = "_{0}{1}".forma... | 0.002653 |
def drawLine(self, x1, y1, x2, y2, silent=False):
"""
Draws a line on the current :py:class:`Layer` with the current :py:class:`Brush`.
Coordinates are relative to the original layer size WITHOUT downsampling applied.
:param x1: Starting X coordinate.
:param y1: Starting Y coordinate.
:param x2: End X coor... | 0.036082 |
def _create_safe_task(self, coroutine):
""" Calls self._loop.create_task with a safe (== with logged exception) coroutine. When run() ends, these tasks
are automatically cancelled"""
task = self._loop.create_task(coroutine)
self.__asyncio_tasks_running.add(task)
task.add_done... | 0.008475 |
def validate_config(cls, config):
"""
Validates a config dictionary parsed from a cluster config file.
Checks that a discovery method is defined and that at least one of
the balancers in the config are installed and available.
"""
if "discovery" not in config:
... | 0.003384 |
def write_to_fullarr(data, sample, sidx):
""" writes arrays to h5 disk """
## enter ref data?
#isref = 'reference' in data.paramsdict["assembly_method"]
LOGGER.info("writing fullarr %s %s", sample.name, sidx)
## save big arrays to disk temporarily
with h5py.File(data.clust_database, 'r+') as i... | 0.010554 |
def set_client_format(self, desc):
"""Get the client format description. This describes the
encoding of the data that the program will read from this
object.
"""
assert desc.mFormatID == AUDIO_ID_PCM
check(_coreaudio.ExtAudioFileSetProperty(
self._obj, PROP_CL... | 0.00463 |
def _get_bandfile(self, **options):
"""Get the VIIRS rsr filename"""
# Need to understand why there are A&B files for band M16. FIXME!
# Anyway, the absolute response differences are small, below 0.05
# LOG.debug("paths = %s", str(self.bandfilenames))
path = self.bandfilenames... | 0.005329 |
def ROL(self, a):
"""
Rotates all bits of the register one place left through the C (carry)
bit. This is a 9-bit rotation.
source code forms: ROL Q; ROLA; ROLB
CC bits "HNZVC": -aaas
"""
r = (a << 1) | self.C
self.clear_NZVC()
self.update_NZVC_8(... | 0.005797 |
def PushItem(self, item, block=True):
"""Push an item on to the queue.
If no ZeroMQ socket has been created, one will be created the first time
this method is called.
Args:
item (object): item to push on the queue.
block (Optional[bool]): whether the push should be performed in blocking
... | 0.00567 |
def QA_fetch_stock_block_adv(code=None, blockname=None, collections=DATABASE.stock_block):
'''
返回板块 ❌
:param code:
:param blockname:
:param collections: 默认数据库 stock_block
:return: QA_DataStruct_Stock_block
'''
if code is not None and blockname is None:
# 返回这个股票代码所属的板块
dat... | 0.002835 |
def has_vtable(decl_type):
"""True, if class has virtual table, False otherwise"""
assert isinstance(decl_type, class_declaration.class_t)
return bool(
decl_type.calldefs(
lambda f: isinstance(f, calldef_members.member_function_t) and
f.virtuality != calldef_types.VIRTUALITY_... | 0.002513 |
def manage_action_return(self, action):
"""Manage action return from Workers
We just put them into the corresponding sched
and we clean unused properties like my_scheduler
:param action: the action to manage
:type action: alignak.action.Action
:return: None
"""
... | 0.002662 |
def DatabaseDirectorySize(root_path, extension):
"""Compute size (in bytes) and number of files of a file-based data store."""
directories = collections.deque([root_path])
total_size = 0
total_files = 0
while directories:
directory = directories.popleft()
try:
items = os.listdir(directory)
e... | 0.018116 |
def do_run_one(self, args):
'''run a single job'''
work_spec_names = args.from_work_spec or None
worker = SingleWorker(self.config, task_master=self.task_master, work_spec_names=work_spec_names, max_jobs=args.max_jobs)
worker.register()
rc = False
starttime = time.time()
... | 0.005165 |
def _summarize_result(self, root_action, leaf_eot):
"""Return a dict with useful information that summarizes this action."""
root_board = root_action.parent.board
action_detail = root_action.position_pair
score = self._relative_score(root_action, leaf_eot,
... | 0.003764 |
def dbRestore(self, db_value, context=None):
"""
Converts a stored database value to Python.
:param py_value: <variant>
:param context: <orb.Context>
:return: <variant>
"""
if db_value is not None:
try:
return pickle.loads(str(db_valu... | 0.003774 |
def tohexstring(self):
"""
Returns a hexadecimal string
"""
val = self.tostring()
st = "{0:0x}".format(int(val, 2))
return st.zfill(len(self.bitmap)*2) | 0.01005 |
def Not(x, simplify=True):
"""Expression negation operator
If *simplify* is ``True``, return a simplified expression.
"""
x = Expression.box(x).node
y = exprnode.not_(x)
if simplify:
y = y.simplify()
return _expr(y) | 0.003968 |
def uniform_grid_fromintv(intv_prod, shape, nodes_on_bdry=True):
"""Return a grid from sampling an interval product uniformly.
The resulting grid will by default include ``intv_prod.min_pt`` and
``intv_prod.max_pt`` as grid points. If you want a subdivision into
equally sized cells with grid points in ... | 0.000204 |
def _bucket_time(self, event_time):
"""
The seconds since epoch that represent a computed bucket.
An event bucket is the time of the earliest possible event for
that `bucket_width`. Example: if `bucket_width =
timedelta(minutes=10)`, bucket times will be the number of seconds
since epoch at 12... | 0.002128 |
def get_nonce(
sk: Ed25519PrivateKey, data: bytes, ctr: int = 0
) -> Tuple[int, Ed25519PublicPoint]:
"""Calculate CoSi nonces for given data.
These differ from Ed25519 deterministic nonces in that there is a counter appended at end.
Returns both the private point `r` and the partial signature `R`.
... | 0.004362 |
def enforce_timezone(cls, value):
"""
When `self.default_timezone` is `None`, always return naive datetimes.
When `self.default_timezone` is not `None`, always return aware datetimes.
"""
field_timezone = cls.default_timezone()
if (field_timezone is not None) and not is_... | 0.005906 |
def nmf_ensemble(data, k, n_runs=10, W_list=[], **nmf_params):
"""
Runs an ensemble method on the list of NMF W matrices...
Args:
data: genes x cells array (should be log + cell-normalized)
k: number of classes
n_runs (optional): number of random initializations of state estimation
... | 0.003788 |
def handle_failed_login(self, login_result):
"""If Two Factor Authentication (2FA/2SV) is enabled, the initial
login will fail with a predictable error. Catching this error allows us
to begin the authentication process.
Other types of errors can be treated in a similar way.
"""
... | 0.00303 |
def get_field_type(cls, name):
"""
Takes a field name and gets an appropriate BaseField instance
for that column. It inspects the Model that is set on the manager
to determine what the BaseField subclass should be.
:param unicode name:
:return: A BaseField subclass that... | 0.002821 |
def _user_raw_from_login_content(login_content):
"""Returns a User instance with appropriate raw data parsed from login response content"""
matching_keys = [
'displayName',
'lastLogin',
'active',
'name',
'isMe',
'lastPasswordChangedDate',
'passwordResetReq... | 0.002703 |
def format_commands(self, ctx, formatter):
"""Extra format methods for multi methods that adds all the commands
after the options.
"""
self.format_command_subsection(
ctx, formatter, self.list_misc_commands(), 'Commands'
)
self.format_command_subsection(
... | 0.005063 |
def enumerate_all(vars, e, bn):
"""Return the sum of those entries in P(vars | e{others})
consistent with e, where P is the joint distribution represented
by bn, and e{others} means e restricted to bn's other variables
(the ones other than vars). Parents must precede children in vars."""
if not vars... | 0.001621 |
def add_arguments(self, parser):
"""Command line arguments for Django 1.8+"""
# Add the underlying test command arguments first
test_command = TestCommand()
test_command.add_arguments(parser)
for option in OPTIONS:
parser.add_argument(*option[0], **option[1]) | 0.00641 |
def characters(self, chars):
"""
Put character data in the currently open element. Special characters
(such as ``<``, ``>`` and ``&``) are escaped.
If `chars` contains any ASCII control character, :class:`ValueError` is
raised.
"""
self._finish_pending_start_elem... | 0.003257 |
def update(self, password=values.unset):
"""
Update the CredentialInstance
:param unicode password: The password will not be returned in the response
:returns: Updated CredentialInstance
:rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialInstance
... | 0.010444 |
def get_certifi_file():
"""Get the SSL certifications installed by the certifi package.
@return: the filename to the cert file
@rtype: string
@raises: ImportError when certifi is not installed or ValueError when
the file is not found
"""
import certifi
filename = certifi.where()... | 0.002119 |
def clean_csvs(dialogpath=None):
""" Translate non-ASCII characters to spaces or equivalent ASCII characters """
dialogdir = os.dirname(dialogpath) if os.path.isfile(dialogpath) else dialogpath
filenames = [dialogpath.split(os.path.sep)[-1]] if os.path.isfile(dialogpath) else os.listdir(dialogpath)
for ... | 0.00818 |
def get_mysql_args(db_config):
"""
Returns an array of argument values that will be passed to a `mysql` or
`mysqldump` process when it is started based on the given database
configuration.
"""
db = db_config['NAME']
mapping = [('--user={0}', db_config.get('USER')),
('--passwo... | 0.001859 |
def serialize_distribution(network_agents, known_modules=[]):
'''
When serializing an agent distribution, remove the thresholds, in order
to avoid cluttering the YAML definition file.
'''
d = deepcopy(list(network_agents))
for v in d:
if 'threshold' in v:
del v['threshold']
... | 0.002179 |
def location_based_search(self, lng, lat, distance, unit="miles", attribute_map=None, page=0, limit=50):
"""Search based on location and other attribute filters
:param long lng: Longitude parameter
:param long lat: Latitude parameter
:param int distance: The radius of the query
... | 0.007599 |
def flat_model(tree):
"""Flatten the tree into a list of properties adding parents as prefixes."""
names = []
for columns in viewvalues(tree):
for col in columns:
if isinstance(col, dict):
col_name = list(col)[0]
names += [col_name + '__' + c for c in flat... | 0.004975 |
def strip_text_after_string(txt, junk):
""" used to strip any poorly documented comments at the end of function defs """
if junk in txt:
return txt[:txt.find(junk)]
else:
return txt | 0.009569 |
def can_update(self, user, **kwargs):
"""Org admins may not update organisation_id or service_type"""
if user.is_admin():
raise Return((True, set([])))
is_creator = self.created_by == user.id
if not (user.is_org_admin(self.organisation_id) or is_creator):
raise R... | 0.003724 |
def can_cut(self):
""" Returns whether text can be cut to the clipboard.
"""
cursor = self._control.textCursor()
return (cursor.hasSelection() and
self._in_buffer(cursor.anchor()) and
self._in_buffer(cursor.position())) | 0.007067 |
def eigen_table(self):
"""Eigenvalues, expl. variance, and cumulative expl. variance."""
idx = ["Eigenvalue", "Variability (%)", "Cumulative (%)"]
table = pd.DataFrame(
np.array(
[self.eigenvalues, self.inertia, self.cumulative_inertia]
),
... | 0.004598 |
def ensure_time_as_index(ds):
"""Ensures that time is an indexed coordinate on relevant quantites.
Sometimes when the data we load from disk has only one timestep, the
indexing of time-defined quantities in the resulting xarray.Dataset gets
messed up, in that the time bounds array and data variables do... | 0.000773 |
def _set_user(self, v, load=False):
"""
Setter method for user, mapped from YANG variable /snmp_server/user (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_user is considered as a private
method. Backends looking to populate this variable should
do so via ... | 0.002846 |
def cmd_c(self, ch=None):
"""c ch=chname
Center the image for the given viewer/channel.
"""
viewer = self.get_viewer(ch)
if viewer is None:
self.log("No current viewer/channel.")
return
viewer.center_image() | 0.007117 |
def calc_point_dist_vary(mus1, fUpper1, mus2, fUpper2, fMap, norm_map, MMdistA):
"""
Function to determine if two points, with differing upper frequency cutoffs
have a mismatch < MMdistA for *both* upper frequency cutoffs.
Parameters
----------
mus1 : List of numpy arrays
mus1[i] will g... | 0.002697 |
def multi_polygons_data(element):
"""
Expands polygon data which contains holes to a bokeh multi_polygons
representation. Multi-polygons split by nans are expanded and the
correct list of holes is assigned to each sub-polygon.
"""
paths = element.split(datatype='array', dimensions=element.kdims)... | 0.00175 |
def spectrogram(self, ref=None, segmentLengthMultiplier=1, window='hann'):
"""
analyses the source to generate a spectrogram
:param ref: the reference value for dB purposes.
:param segmentLengthMultiplier: allow for increased resolution.
:return:
t : ndarray
... | 0.003058 |
def each(coro, iterable, limit=0, loop=None,
collect=False, timeout=None, return_exceptions=False, *args, **kw):
"""
Concurrently iterates values yielded from an iterable, passing them to
an asynchronous coroutine.
You can optionally collect yielded values passing collect=True param,
which... | 0.000329 |
def clonevm(name=None,
uuid=None,
new_name=None,
snapshot_uuid=None,
snapshot_name=None,
mode='machine',
options=None,
basefolder=None,
new_uuid=None,
register=False,
groups=None,
**kwargs... | 0.001996 |
def optimal_AR_spectrum(dx, Y, ndegrees=None,return_min=True):
'''
Get the optimal order AR spectrum by minimizing the BIC.
'''
if ndegrees is None : ndegrees=len(Y)-ndegrees
aicc=np.arange(ndegrees)
aic=aicc.copy()
bic=aicc.copy()
tmpStr=[]
for i in np.arange(1,... | 0.039039 |
def flow_meter_discharge(D, Do, P1, P2, rho, C, expansibility=1.0):
r'''Calculates the flow rate of an orifice plate based on the geometry
of the plate, measured pressures of the orifice, and the density of the
fluid.
.. math::
m = \left(\frac{\pi D_o^2}{4}\right) C \frac{\sqrt{2\Delta P \r... | 0.003163 |
def respond(self, request, view, newsitems, extra_context={}):
"""A helper that takes some news items and returns an HttpResponse"""
context = self.get_context(request, view=view)
context.update(self.paginate_newsitems(request, newsitems))
context.update(extra_context)
template =... | 0.004785 |
def generate_modname_nunja(
entry_point, base_module, fext, text_prefix=REQUIREJS_TEXT_PREFIX):
"""
Generate a 3-tuple for the two modname_* and one modpath_* functions
required.
"""
def modname_nunja_template(fragments):
# Nunja explicitly requires requirejs-text for the dynamic
... | 0.000401 |
def shebang(self, new_shebang):
"""Write a new shebang to the file.
Raises:
ValueError: If the file has no shebang to modify.
ValueError: If the new shebang is invalid.
"""
if not self.shebang:
raise ValueError('Cannot modify a shebang if it does not... | 0.004301 |
def iter_delimiter(self, byte_size=8192):
""" Generalization of the default iter file delimited by '\n'.
Note:
The newline string can be arbitrarily long; it need not be restricted to a
single character. You can also set the read size and control whether or not
the newline string is left on th... | 0.013636 |
def interpret(self):
"""Return value of text. Return False if text is invalid, raise exception if text is intermediate"""
strn = self.lineEdit().text()
suf = self.opts['suffix']
if len(suf) > 0:
if strn[-len(suf):] != suf:
return False
#raise Excep... | 0.013746 |
def Auth(email=None, password=None):
"""Get a reusable google data client."""
gd_client = SpreadsheetsService()
gd_client.source = "texastribune-ttspreadimporter-1"
if email is None:
email = os.environ.get('GOOGLE_ACCOUNT_EMAIL')
if password is None:
password = os.environ.get('GOOGLE... | 0.002304 |
def extract_response(self, extractors):
""" extract value from requests.Response and store in OrderedDict.
Args:
extractors (list):
[
{"resp_status_code": "status_code"},
{"resp_headers_content_type": "headers.content-type"},
... | 0.00309 |
def slice_to_numerical_args(slice_, num_examples):
"""Translate a slice's attributes into numerical attributes.
Parameters
----------
slice_ : :class:`slice`
Slice for which numerical attributes are wanted.
num_examples : int
Number of examples in the ind... | 0.002837 |
def edit(self,
name,
description=None,
homepage=None,
private=None,
has_issues=None,
has_wiki=None,
has_downloads=None,
default_branch=None):
"""Edit this repository.
:param str name: (required), nam... | 0.004425 |
def __catalina_home():
'''
Tomcat paths differ depending on packaging
'''
locations = ['/usr/share/tomcat*', '/opt/tomcat']
for location in locations:
folders = glob.glob(location)
if folders:
for catalina_home in folders:
if os.path.isdir(catalina_home + ... | 0.002591 |
def display_warning_message_bar(
title=None,
message=None,
more_details=None,
button_text=tr('Show details ...'),
duration=8,
iface_object=iface):
"""
Display a warning message bar.
:param title: The title of the message bar.
:type title: basestring
... | 0.000723 |
def cli(env, identifier):
"""Reset connections on a certain service group."""
mgr = SoftLayer.LoadBalancerManager(env.client)
loadbal_id, group_id = loadbal.parse_id(identifier)
mgr.reset_service_group(loadbal_id, group_id)
env.fout('Load balancer service group connections are being reset!') | 0.003185 |
def post(self, request, bot_id, format=None):
"""
Add a new chat state
---
serializer: TelegramChatStateSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request
"""
... | 0.005076 |
def upload_file_to_container(block_blob_client, container_name, file_path):
"""Uploads a local file to an Azure Blob storage container.
:param block_blob_client: A blob service client.
:type block_blob_client: `azure.storage.blob.BlockBlobService`
:param str container_name: The name of the Azure Blob s... | 0.001489 |
def validate_arguments(func, args, kwargs, drop_extra=True):
"""Checks if the function accepts the arguments and keyword arguments.
Returns a new ``(args, kwargs)`` tuple that can safely be passed to
the function without causing a `TypeError` because the function signature
is incompatible. If `drop_ext... | 0.000467 |
def set_constraint_bound(self, name, value):
"""Set the upper bound of a constraint."""
index = self._get_constraint_index(name)
self.upper_bounds[index] = value
self._reset_solution() | 0.009259 |
def genealogic_ids(self):
""" Get all genealogic ids
Returns:
A list of all parent ids
"""
ids = []
parent = self
while parent:
ids.append(parent.id)
parent = parent.parent_object
return ids | 0.00678 |
def get_bg_color(image, bits_per_channel=None):
'''Obtains the background color from an image or array of RGB colors
by grouping similar colors into bins and finding the most frequent
one.
'''
assert image.shape[-1] == 3
quantized = quantize(image, bits_per_channel).astype(int)
packed = pack_rgb... | 0.002128 |
def create_invalidation_request(self, distribution_id, paths,
caller_reference=None):
"""Creates a new invalidation request
:see: http://goo.gl/8vECq
"""
# We allow you to pass in either an array or
# an InvalidationBatch object
if ... | 0.00391 |
def subdivide(name, rgstr_stamps=None, save_itrs=SET['SI']):
"""
Induce a new subdivision--a lower level in the timing hierarchy.
Subsequent calls to methods like stamp() operate on this new level.
Notes:
If rgstr_stamps is used, the collection is passed through set() for
uniqueness, an... | 0.003106 |
def get_subgraph(self, subvertices, normalize=False):
"""Creates a subgraph of the current graph
See :meth:`molmod.graphs.Graph.get_subgraph` for more information.
"""
graph = Graph.get_subgraph(self, subvertices, normalize)
if normalize:
new_numbers = self.number... | 0.007121 |
def is_cep(numero, estrito=False):
"""Uma versão conveniente para usar em testes condicionais. Apenas retorna
verdadeiro ou falso, conforme o argumento é validado.
:param bool estrito: Padrão ``False``, indica se apenas os dígitos do
número deverão ser considerados. Se verdadeiro, potenciais caract... | 0.001805 |
def read_adjacency_matrix(file_path, separator, numbering="matlab"):
"""
Reads an edge list in csv format and returns the adjacency matrix in SciPy Sparse COOrdinate format.
Inputs: - file_path: The path where the adjacency matrix is stored.
- separator: The delimiter among values (e.g. ",", ... | 0.001812 |
def get_query(self, query):
"""Run a generic issue/PR query"""
url = self._api_url(
"/search/issues?q={query}&per_page=100", query=query)
return self._getter(url, subkey='items') | 0.009346 |
def submission(self):
"""Return the Submission object this comment belongs to."""
if not self._submission: # Comment not from submission
self._submission = self.reddit_session.get_submission(
url=self._fast_permalink)
return self._submission | 0.006803 |
def create_execve(original_name):
"""
os.execve(path, args, env)
os.execvpe(file, args, env)
"""
def new_execve(path, args, env):
import os
send_process_created_message()
return getattr(os, original_name)(path, patch_args(args), env)
return new_execve | 0.003322 |
def ClearPathHistory(self, client_id, path_infos):
"""Clears path history for specified paths of given client."""
for path_info in path_infos:
path_record = self._GetPathRecord(client_id, path_info)
path_record.ClearHistory() | 0.012245 |
def forwards(self, orm):
"Write your forwards methods here."
rows = db.execute("select distinct feature_type from content_content")
for row in rows:
feature_type = row[0]
try:
ft = orm.FeatureType.objects.get(slug=slugify(feature_type))
except... | 0.004777 |
def _init_img_params(param):
"""
Initialize 2D image-type parameters that can accept either a
single or two values.
"""
if param is not None:
param = np.atleast_1d(param)
if len(param) == 1:
param = np.repeat(param, 2)
return para... | 0.006231 |
def icartesian_to_index(ranges, maxima=None):
"""
Inverts tuples from a cartesian product to a numeric index ie. the index this
tuple would have in a cartesian product.
Each column gets multiplied with a place value according to the preceding columns maxmimum.
This function in the... | 0.013301 |
def infer_shape(self, node, input_shapes):
"""Return a list of output shapes based on ``input_shapes``.
This method is optional. It allows to compute the shape of the
output without having to evaluate.
Parameters
----------
node : `theano.gof.graph.Apply`
Th... | 0.002257 |
def current(instance: bool = True) -> Optional["IOLoop"]:
"""Returns the current thread's `IOLoop`.
If an `IOLoop` is currently running or has been marked as
current by `make_current`, returns that instance. If there is
no current `IOLoop` and ``instance`` is true, creates one.
... | 0.001938 |
def retrieve_breadcrumbs(path, model_instance, root_name=''):
"""
Build a semi-hardcoded breadcrumbs
based of the model's url handled by Zinnia.
"""
breadcrumbs = []
zinnia_root_path = reverse('zinnia:entry_archive_index')
if root_name:
breadcrumbs.append(Crumb(root_name, zinnia_roo... | 0.000541 |
def _create_emulated_mapping(self, uc, address):
"""
Create a mapping in Unicorn and note that we'll need it if we retry.
:param uc: The Unicorn instance.
:param address: The address which is contained by the mapping.
:rtype Map
"""
m = self._cpu.memory.map_conta... | 0.002837 |
def get_correction(self, entry):
"""
Gets the Freysoldt correction for a defect entry
Args:
entry (DefectEntry): defect entry to compute Freysoldt correction on.
Requires following parameters in the DefectEntry to exist:
axis_grid (3 x NGX where N... | 0.005373 |
def pan_pan_cb(self, fitsimage, event):
"""Pan event in the pan window. Just pan the channel viewer.
"""
chviewer = self.fv.getfocus_viewer()
bd = chviewer.get_bindings()
if hasattr(bd, 'pa_pan'):
return bd.pa_pan(chviewer, event)
return False | 0.006536 |
def initializeColumns(self):
"""
Initializes the columns that will be used for this tree widget based \
on the table type linked to it.
"""
tableType = self.tableType()
if not tableType:
return
elif self._columnsInitialized or self.columnOf(0) ... | 0.007062 |
def _compute_secondary(self):
"""Compute secondary axis min max and label positions"""
# secondary y axis support
if self.secondary_series and self._y_labels:
y_pos = list(zip(*self._y_labels))[1]
if self.include_x_axis:
ymin = min(self._secondary_min, 0)
... | 0.002155 |
def url(self, service):
'''return URL for a tile'''
if service not in TILE_SERVICES:
raise TileException('unknown tile service %s' % service)
url = string.Template(TILE_SERVICES[service])
(x,y) = self.tile
tile_info = TileServiceInfo(x, y, self.zoom)
return url.substitute(tile_info) | 0.033557 |
def launch(prompt_prefix=None):
'''Launch a subshell'''
if prompt_prefix:
os.environ['PROMPT'] = prompt(prompt_prefix)
subprocess.call(cmd(), env=os.environ.data) | 0.005435 |
def insert_instance(instance, table, **kwargs):
"""Inserts an object's values into a given table, will not populate Nonetype values
@param instance: Instance of an object to insert
@param table: Table in which to insert instance values
@return: ID of the last inserted row
"""
... | 0.004525 |
def is_fp_arg(self, arg):
"""
This should take a SimFunctionArgument instance and return whether or not that argument is a floating-point
argument.
Returns True for MUST be a floating point arg,
False for MUST NOT be a floating point arg,
None for when it... | 0.005882 |
def convert_attrs_to_uppercase(obj: Any, attrs: Iterable[str]) -> None:
"""
Converts the specified attributes of an object to upper case, modifying
the object in place.
"""
for a in attrs:
value = getattr(obj, a)
if value is None:
continue
setattr(obj, a, value.up... | 0.003067 |
def _setPWMFrequency(self, pwm, device, message):
"""
Set the PWM frequency.
:Parameters:
pwm : `int`
The PWN frequency to set in hertz.
device : `int`
The device is the integer number of the hardware devices ID and
is only used with the P... | 0.00213 |
def getStmgrsRegSummary(self, tmaster, callback=None):
"""
Get summary of stream managers registration summary
"""
if not tmaster or not tmaster.host or not tmaster.stats_port:
return
reg_request = tmaster_pb2.StmgrsRegistrationSummaryRequest()
request_str = reg_request.SerializeToString()... | 0.007874 |
def _separate_buffers(substate, path, buffer_paths, buffers):
"""For internal, see _remove_buffers"""
# remove binary types from dicts and lists, but keep track of their paths
# any part of the dict/list that needs modification will be cloned, so the original stays untouched
# e.g. {'x': {'ar': ar}, 'y'... | 0.005256 |
def vector_poly_data(orig, vec):
""" Creates a vtkPolyData object composed of vectors """
# shape, dimention checking
if not isinstance(orig, np.ndarray):
orig = np.asarray(orig)
if not isinstance(vec, np.ndarray):
vec = np.asarray(vec)
if orig.ndim != 2:
orig = orig.resha... | 0.000569 |
def unflatten_dct(obj):
"""
Undoes the work of flatten_dict
@param {Object} obj 1-D object in the form returned by flattenObj
@returns {Object} The original
:param obj:
:return:
"""
def reduce_func(accum, key_string_and_value):
key_string = key_string_and_value[0]
val... | 0.004788 |
def set(self, start, stop, length=None, units='bytes'):
"""Simple method to update the ranges."""
assert is_byte_range_valid(start, stop, length), \
'Bad range provided'
self._units = units
self._start = start
self._stop = stop
self._length = length
if... | 0.005249 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.