text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def create_keyspace_simple(name, replication_factor, durable_writes=True, connections=None):
"""
Creates a keyspace with SimpleStrategy for replica placement
If the keyspace already exists, it will not be modified.
**This function should be used with caution, especially in production environments.
... | 0.007307 |
def serialCmdPwdAuth(self, password_str):
""" Password step of set commands
This method is normally called within another serial command, so it
does not issue a termination string. Any default password is set
in the caller parameter list, never here.
Args:
password... | 0.005068 |
def get_cas_client(self, request, provider, renew=False):
"""
return a CAS client object matching provider
:param django.http.HttpRequest request: The current request object
:param cas_server.models.FederatedIendityProvider provider: the user identity provider
:r... | 0.003947 |
def plot_lens_subtracted_image(
fit, mask=None, extract_array_from_mask=False, zoom_around_mask=False, positions=None, as_subplot=False,
units='arcsec', kpc_per_arcsec=None, figsize=(7, 7), aspect='square',
cmap='jet', norm='linear', norm_min=None, norm_max=None, linthresh=0.05, linscale=0.01,
... | 0.007164 |
def _compute(self, funcTilde, R, z, phi):
"""
NAME:
_compute
PURPOSE:
evaluate the NxLxM density or potential
INPUT:
funcTidle - must be _rhoTilde or _phiTilde
R - Cylindrical Galactocentric radius
z - vertical height
phi ... | 0.02965 |
def parse(theme_file):
"""Parse the theme file."""
data = util.read_file_json(theme_file)
if "wallpaper" not in data:
data["wallpaper"] = "None"
if "alpha" not in data:
data["alpha"] = util.Color.alpha_num
# Terminal.sexy format.
if "color" in data:
data = terminal_sex... | 0.002849 |
def export():
r'''
Restores the trained variables into a simpler graph that will be exported for serving.
'''
log_info('Exporting the model...')
from tensorflow.python.framework.ops import Tensor, Operation
inputs, outputs, _ = create_inference_graph(batch_size=FLAGS.export_batch_size, n_steps=... | 0.003824 |
def reboot(self, devices):
"""Reboot one or more devices.
"""
for device in devices:
self.logger.info('Rebooting: %s', device.id)
try:
device.reboot()
except packet.baseapi.Error:
raise PacketManagerException('Unable to reboot i... | 0.008523 |
def installProductOn(self, userstore):
"""
Creates an Installation in this user store for our collection
of powerups, and then install those powerups on the user's
store.
"""
def install():
i = Installation(store=userstore)
i.types = self.types
... | 0.005305 |
def auth_required(*auth_methods):
"""
Decorator that protects enpoints through multiple mechanisms
Example::
@app.route('/dashboard')
@auth_required('token', 'session')
def dashboard():
return 'Dashboard'
:param auth_methods: Specified mechanisms.
"""
login_... | 0.000801 |
def velocity_genes(data, vkey='velocity', min_r2=0.01, highly_variable=None, copy=False):
"""Estimates velocities in a gene-specific manner
Arguments
---------
data: :class:`~anndata.AnnData`
Annotated data matrix.
vkey: `str` (default: `'velocity'`)
Name under which to refer to the... | 0.005232 |
def get_html(grafs):
"""
Renders the grafs provided in HTML by wrapping them in <p> tags.
Linebreaks are replaced with <br> tags.
"""
html = [format_html('<p>{}</p>', p) for p in grafs]
html = [p.replace("\n", "<br>") for p in html]
return format_html(six.text_type('\n\n'.join(html))) | 0.003185 |
def print_config(self, cfg, hide_password=True, history=False, module_id=None):
"""Returns a string representing the config of this ShutIt run.
"""
shutit_global.shutit_global_object.yield_to_draw()
cp = self.config_parser
s = ''
keys1 = list(cfg.keys())
if keys1:
keys1.sort()
for k in keys1:
if m... | 0.032404 |
def print_result(self, f=sys.stdout, verbose=False):
"""Print result to f
:param f: stream to print output
:param verbose: print all data or only the most important parts?
"""
var_count = len(self.betas)/2
if verbose:
results = [str(x) for x in [
... | 0.00108 |
def _run_includemes(configurator, includemes):
"""
Automatically include packages defined in **include** configuration key.
:param pyramid.config.Configurator configurator: pyramid's app configurator
:param dict includemes: include, a list of includes or dictionary
"""
for include in includemes... | 0.001931 |
def initOptions(self, options):
"""
Initializes the edit with the inputed options data set.
:param options | <XScintillaEditOptions>
"""
self.setAutoIndent( options.value('autoIndent'))
self.setIndentationsUseTabs( options.value('indentationsU... | 0.009556 |
def get_project(project_id, include_deleted_networks=False, **kwargs):
"""
get a project complexmodel
"""
user_id = kwargs.get('user_id')
proj_i = _get_project(project_id)
#lazy load owners
proj_i.owners
proj_i.check_read_permission(user_id)
proj_j = JSONObject(proj_i)
pr... | 0.006468 |
def use_http_form_post(message, destination, relay_state,
typ="SAMLRequest"):
"""
Return a form that will automagically execute and POST the message
to the recipient.
:param message:
:param destination:
:param relay_state:
:param typ: W... | 0.005254 |
def check_payment_v1(state_engine, state_op_type, nameop, fee_block_id, token_address, burn_address, name_fee, block_id):
"""
Verify that for a version-1 namespace, the nameop paid the right amount of BTC or STACKs.
nameop is either a name registration or name renewal
Return {'status': True, 'tokens_pai... | 0.006014 |
def set_attribute(self, selector, attribute, value, by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT):
""" This method uses JavaScript to set/update an attribute. """
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(ti... | 0.002833 |
def search_dict(data, key):
"""
Search for a key in a nested dict, or list of nested dicts, and return the values.
:param data: dict/list to search
:param key: key to find
:return: matches for key
"""
if isinstance(data, dict):
for dkey, value in data.items():
if dkey ==... | 0.00349 |
def refresh(self)->None:
"Apply any logit, flow, or affine transfers that have been sent to the `Image`."
if self._logit_px is not None:
self._px = self._logit_px.sigmoid_()
self._logit_px = None
if self._affine_mat is not None or self._flow is not None:
self.... | 0.008565 |
def _build_package_finder(
self,
options, # type: Values
session, # type: PipSession
platform=None, # type: Optional[str]
python_versions=None, # type: Optional[List[str]]
abi=None, # type: Optional[str]
implementa... | 0.00318 |
def list_course_nicknames(self):
"""
List course nicknames.
Returns all course nicknames you have set.
"""
path = {}
data = {}
params = {}
self.logger.debug("GET /api/v1/users/self/course_nicknames with query params: {params} and form data: {da... | 0.007905 |
def _handle_end_area(self):
"""
Handle closing area element
"""
self._result.append(Area(result=self._result, **self._curr))
self._curr = {} | 0.011111 |
def is_cleanly_mergable(*dicts: Dict[Any, Any]) -> bool:
"""Check that nothing will be overwritten when dictionaries are merged using `deep_merge`.
Examples:
>>> is_cleanly_mergable({"a": 1}, {"b": 2}, {"c": 3})
True
>>> is_cleanly_mergable({"a": 1}, {"b": 2}, {"a": 0, c": 3})
... | 0.004907 |
def bind(cls, param=None, **kwargs):
"""Bind middleware's method as endpoint.
"""
def stick(function, **binding):
if not asyncio.iscoroutine(function):
function = asyncio.coroutine(function)
bindings = getattr(function, STICKER, [])
bindings.ap... | 0.003697 |
def du(self, paths, include_toplevel=False, include_children=True):
'''Returns size information for paths
:param paths: Paths to du
:type paths: list
:param include_toplevel: Include the given path in the result. If the path is a file, include_toplevel is always True.
:type incl... | 0.005714 |
def call(self, func, *args, **kwargs):
"""
Call a function, resolving any type-hinted arguments.
"""
guessed_kwargs = self._guess_kwargs(func)
for key, val in guessed_kwargs.items():
kwargs.setdefault(key, val)
try:
return func(*args, **kwargs)
... | 0.003503 |
def pay(self, input=None, action=None, status_callback=None,
status_callback_method=None, timeout=None, max_attempts=None,
security_code=None, postal_code=None, payment_connector=None,
token_type=None, charge_amount=None, currency=None, description=None,
valid_card_types=... | 0.004815 |
def _is_valid_inherit_element(self, element):
"""
Check that the children of element can be manipulated to apply the CSS
properties.
:param element: The element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
:return: True if the children of element can ... | 0.002597 |
def _compute_memory_address(self, mem_operand):
"""Return operand memory access translation.
"""
base = ReilRegisterOperand(mem_operand.base_reg.name, mem_operand.size)
if mem_operand.displacement:
address = self.temporal(mem_operand.size)
if isinstance(mem_oper... | 0.003316 |
def compute_displays_sweep(
self,
program: Union[circuits.Circuit, schedules.Schedule],
params: Optional[study.Sweepable] = None,
qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
initial_state: Union[int, np.ndarray] = 0,
) -> List[study.ComputeDisplaysResult]:
... | 0.001565 |
def lhs(node):
'''
Return a set of symbols in `node` that are assigned.
:param node: ast node
:returns: set of strings.
'''
gen = ConditionalSymbolVisitor()
if isinstance(node, (list, tuple)):
gen.visit_list(node)
else:
gen.visit(node)
return gen.lhs | 0.012739 |
def write_temp_bird_conf(dummy_ip_prefix,
config_file,
variable_name,
prefixes):
"""Write in a temporary file the list of IP-Prefixes.
A failure to create and write the temporary file will exit main program.
Arguments:
dumm... | 0.000473 |
def push_token(self, tok):
"Push a token onto the stack popped by the get_token method"
if self.debug >= 1:
print("shlex: pushing token " + repr(tok))
self.pushback.appendleft(tok) | 0.009259 |
def get_twitter(app_key=None, app_secret=None, search='python', location='', **kwargs):
"""Location may be specified with a string name or latitude, longitude, radius"""
if not app_key:
from settings_secret import TWITTER_API_KEY as app_key
if not app_secret:
from settings_secret import TWIT... | 0.00625 |
def delete_note(self, note_id,
url='https://api.shanbay.com/bdc/note/{note_id}/'):
"""删除笔记"""
url = url.format(note_id=note_id)
return self._request(url, method='delete').json() | 0.013575 |
def _format_target(self, net, f, idx):
"""Apply formatting to the target filename template."""
if f is None:
return None
if isinstance(f, str):
f = self.fn_prefix + f.format(
net=net,
last_epoch=net.history[idx],
last_batch=... | 0.00463 |
def parse_set(self):
"""Parse an assign statement."""
lineno = next(self.stream).lineno
target = self.parse_assign_target()
self.stream.expect('assign')
expr = self.parse_tuple()
return nodes.Assign(target, expr, lineno=lineno) | 0.007273 |
def get_packet_and_syns(self, b, compute, times=[], **kwargs):
"""
get_packet is called by the master and must get all information necessary
to send to all workers. The returned packet will be passed on as
_run_chunk(**packet) with the following exceptions:
* b: the bundle will... | 0.007527 |
def _run1(self):
"""workhorse for do_run_1"""
if self.check_update_J():
self.update_J()
else:
if self.check_Broyden_J():
self.update_Broyden_J()
if self.check_update_eig_J():
self.update_eig_J()
#1. Assuming that J star... | 0.003836 |
def _write(self, f):
"""Serialize an NDEF record to a file-like object."""
log.debug("writing ndef record at offset {0}".format(f.tell()))
record_type = self.type
record_name = self.name
record_data = self.data
if record_type == '':
header_flags = 0;... | 0.00742 |
def commitVersion(self):
''' return a GithubComponentVersion object for a specific commit if valid
'''
import re
commit_match = re.match('^[a-f0-9]{7,40}$', self.tagOrBranchSpec(), re.I)
if commit_match:
return GithubComponentVersion(
'', '', _getComm... | 0.011655 |
def normalize_audio_buffer(buf, volume_percentage, sample_width=2):
"""Adjusts the loudness of the audio data in the given buffer.
Volume normalization is done by scaling the amplitude of the audio
in the buffer by a scale factor of 2^(volume_percentage/100)-1.
For example, 50% volume scales the amplit... | 0.000952 |
def strip_punctuation(text, exclude='', include=''):
"""Strip leading and trailing punctuation from an input string."""
chars_to_strip = ''.join(
set(list(punctuation)).union(set(list(include))) - set(list(exclude))
)
return text.strip(chars_to_strip) | 0.010169 |
def do_list(self, resource):
"""
Enumerate resources
Possible values: plugins, volumes
"""
if resource == 'plugins':
self.__list_plugins()
elif resource == 'volumes':
self.__list_volumes()
else:
self.logger.error("Unknown resou... | 0.004728 |
def highpass(frequency, sample_rate, fstop=None, gpass=2, gstop=30, type='iir',
**kwargs):
"""Design a high-pass filter for the given cutoff frequency
Parameters
----------
frequency : `float`
corner frequency of high-pass filter
sample_rate : `float`
sampling rate of ... | 0.000528 |
def _write_version1(self,new_filename,update_regul=False):
"""write a version 1 pest control file
Parameters
----------
new_filename : str
name of the new pest control file
update_regul : (boolean)
flag to update zero-order Tikhonov prior information
... | 0.006578 |
def suggest(self, query):
""" Gather suggestions based on the provided title or None if no
suggestions found
Args:
query (str): Page title
Returns:
String or None: Suggested page title or **None** if no \
sugges... | 0.003636 |
def _check_stage_complete(self):
"""
Purpose: Check if all tasks of the current stage have completed, i.e., are in either DONE or FAILED state.
"""
try:
for task in self._tasks:
if task.state not in [states.DONE, states.FAILED]:
return Fa... | 0.007299 |
def channels_list(self, exclude_archived=True, **params):
"""channels.list
This method returns a list of all channels in the team. This includes
channels the caller is in, channels they are not currently in, and
archived channels. The number of (non-deactivated) members in each
... | 0.003534 |
def compile(marker):
"""Return compiled marker as a function accepting an environment dict."""
try:
return _cache[marker]
except KeyError:
pass
if not marker.strip():
def marker_fn(environment=None, override=None):
""""""
return True
else:
comp... | 0.002478 |
def saveProfileAs( self ):
"""
Saves the current profile as a new profile to the manager.
"""
name, ok = QInputDialog.getText(self, 'Create Profile', 'Name:')
if ( not name ):
return
manager = self.parent()
prof = manager.viewWidget().saveP... | 0.019608 |
def convert_identifiers(self, identifiers: Union[Identifier, List[Identifier]]):
"""
Convert an individual :class:`Identifier` to a model instance,
or a list of Identifiers to a list of model instances.
"""
if not identifiers:
return identifiers
def _create_o... | 0.007229 |
def add_hybrid_interface(ifindex, pvid, taggedvlans, untaggedvlans, auth, url, devip=None,
devid=None):
"""
Function takes ifindex, pvid, tagged vlans untagged vlans as input values to add a hybrid
port to a HPE Comware based switch. These functions only apply to HPE Comware based d... | 0.004883 |
def plot_posterior(
data,
var_names=None,
coords=None,
figsize=None,
textsize=None,
credible_interval=0.94,
round_to=1,
point_estimate="mean",
rope=None,
ref_val=None,
kind="kde",
bw=4.5,
bins=None,
ax=None,
**kwargs
):
"""Plot Posterior densities in the s... | 0.002971 |
def kill(self, dwExitCode = 0):
"""
Terminates the thread execution.
@note: If the C{lpInjectedMemory} member contains a valid pointer,
the memory is freed.
@type dwExitCode: int
@param dwExitCode: (Optional) Thread exit code.
"""
hThread = self.get_han... | 0.007576 |
def items(self):
"""Returns a depth-first flat list of all items in the document"""
l = []
for e in self.data:
l += e.items()
return l | 0.022472 |
def intersect_arc(self, arc):
'''
Given an arc, finds the intersection point(s) of this arc with that.
Returns a list of 2x1 numpy arrays. The list has length 0, 1 or 2, depending on how many intesection points there are.
Points are ordered along the arc.
Intersection with the ar... | 0.005609 |
def _process_block(self, node, **kwargs):
"""
Processes a block e.g. `{% block my_block %}{% endblock %}`
"""
# check if this node already has a 'super_block' attribute
if not hasattr(node, 'super_block'):
# since it doesn't it must be the last block in the inherita... | 0.002928 |
def _do_export(self, remote_function):
"""Pickle a remote function and export it to redis.
Args:
remote_function: the RemoteFunction object.
"""
if self._worker.load_code_from_local:
return
# Work around limitations of Python pickling.
function = ... | 0.001063 |
def limtype(msmt):
"""Return -1 if this value is some kind of upper limit, 1 if this value
is some kind of lower limit, 0 otherwise."""
if np.isscalar(msmt):
return 0
if isinstance(msmt, Uval):
return 0
if isinstance(msmt, Lval):
if msmt.kind == 'undef':
raise Va... | 0.001053 |
def optimize(self, commit=True, waitFlush=None, waitSearcher=None, maxSegments=None, handler='update'):
"""
Tells Solr to streamline the number of segments used, essentially a
defragmentation operation.
Optionally accepts ``maxSegments``. Default is ``None``.
Optionally accepts... | 0.005472 |
def label_sequential_regions(inlist):
"""Input a list of labeled tuples and return a dictionary of sequentially labeled regions.
Args:
inlist (list): A list of tuples with the first number representing the index and the second the index label.
Returns:
dict: Dictionary of labeled regions.
... | 0.005423 |
def fetch_live(self, formatter=TableFormat):
"""
Fetch a live stream query. This is the equivalent of selecting
the "Play" option for monitoring fields within the SMC UI. Data will
be streamed back in real time.
:param formatter: Formatter type for data representation. A... | 0.004484 |
def get_listener_count(self):
"""Returns the number of listeners on the network"""
return _number(
_extract(
self._request(self.ws_prefix + ".getInfo", cacheable=True), "listeners"
)
) | 0.012048 |
def score(self, X, y, **kwargs):
"""
Simply returns the score of the underlying CV model
"""
return self.estimator.score(X, y, **kwargs) | 0.011905 |
def elevated_permissions(self, permissions, redirect_uri=None):
"""Requests elevated permissions for a set of calendars.
:param tuple permissions - calendar permission dicts set each dict
must contain values for both `calendar_id` and `permission_level`
:param string redirect_uri - A u... | 0.00444 |
def hub_scores(msm, waypoints=None):
"""
Calculate the hub score for one or more waypoints
The "hub score" is a measure of how well traveled a certain state or
set of states is in a network. Specifically, it is the fraction of
times that a walker visits a state en route from some state A to another... | 0.000599 |
def parse(xmlfile, element_names, element_attrs={}, attr_conversions={},
heterogeneous=False, warn=False):
"""
Parses the given element_names from xmlfile and yield compound objects for
their xml subtrees (no extra objects are returned if element_names appear in
the subtree) The compound objec... | 0.002979 |
def overlay_url_for(endpoint, filename=None, **values):
"""
Replace flasks url_for() function to allow usage without template changes
If the requested endpoint is static or ending in .static, it tries to serve a bower asset, otherwise it will pass
the arguments to flask.url_for()
See http://flask.... | 0.002121 |
def _request_post_helper(self, url, params=None):
'''API POST helper'''
if self.api_key:
query = {'api_key': self.api_key}
return requests.post(url, params=query, data=params, timeout=60) | 0.008969 |
def forwards(self, orm):
"Write your forwards methods here."
from django.contrib.auth.models import Group
projects = orm['samples.Project'].objects.all()
# Create group for each project
for project in projects:
name = PROJECT_GROUP_TEMPLATE.format(project.name)
... | 0.005464 |
def file_transfer_protocol_send(self, target_network, target_system, target_component, payload, force_mavlink1=False):
'''
File transfer message
target_network : Network ID (0 for broadcast) (uint8_t)
target_system : System ID (0 fo... | 0.007913 |
def guess_infer_extent(gtf_file):
"""
guess if we need to use the gene extent option when making a gffutils
database by making a tiny database of 1000 lines from the original
GTF and looking for all of the features
"""
_, ext = os.path.splitext(gtf_file)
tmp_out = tempfile.NamedTemporaryFile... | 0.001129 |
def get_subnet_flow_logs_list(current_config, subnet):
"""
Return the flow logs that cover a given subnet
:param current_config:
:param subnet: the subnet that the flow logs should cover
:return:
"""
flow_logs_list = []
for flow_log in current_config.flow_logs:
if current_config... | 0.005597 |
def filter_multi_output(stream_spec, filter_name, *args, **kwargs):
"""Apply custom filter with one or more outputs.
This is the same as ``filter_`` except that the filter can produce more than one output.
To reference an output stream, use either the ``.stream`` operator or bracket shorthand:
Exampl... | 0.006299 |
def decodeMessage(self, data):
"""Decode a protobuf message into a list of Tensor events"""
message = proto_pb2.Msg()
message.ParseFromString(data)
return message | 0.010256 |
def getComplexFileData(self, fileInfo, data):
"""Function to initialize the slightly more complicated data for file info"""
result = fileInfo[fileInfo.find(data + "</td>") + len(data + "</td>"):]
result = result[:result.find("</td>")]
result = result[result.rfind(">") + 1:]
return result | 0.02349 |
def chunked(sentence):
""" Returns a list of Chunk and Chink objects from the given sentence.
Chink is a subclass of Chunk used for words that have Word.chunk == None
(e.g., punctuation marks, conjunctions).
"""
# For example, to construct a training vector with the head of previous chunks a... | 0.006127 |
def back_slash_to_front_converter(string):
"""
Replacing all \ in the str to /
:param string: single string to modify
:type string: str
"""
try:
if not string or not isinstance(string, str):
return string
return string.replace('\\', '/')
except Exception:
... | 0.006006 |
def _handle_status(self, key, value):
"""Parse a status code from the attached GnuPG process.
:raises: :exc:`~exceptions.ValueError` if the status message is unknown.
"""
if key in ("USERID_HINT", "NEED_PASSPHRASE",
"GET_HIDDEN", "SIGEXPIRED", "KEYEXPIRED",
... | 0.004847 |
def empty_directory(self):
"""Remove all contents of a directory
Including any sub-directories and their contents"""
for child in self.walkfiles():
child.remove()
for child in reversed([d for d in self.walkdirs()]):
if child == self or not child.isdir():
... | 0.005525 |
def _get_geometric_attenuation_term(self, C, mag, rrup):
"""
Returns the geometric attenuation term defined in equation 3
"""
return (C["c5"] + C["c6"] * mag) * np.log(np.sqrt((rrup ** 2.) +
(C["c7"] ** 2.))) | 0.006711 |
def _BuildPluginRequest(self, app_id, challenge_data, origin):
"""Builds a JSON request in the form that the plugin expects."""
client_data_map = {}
encoded_challenges = []
app_id_hash_encoded = self._Base64Encode(self._SHA256(app_id))
for challenge_item in challenge_data:
key = challenge_item... | 0.008178 |
def step_type(self):
"""Whether it's a IFCW step or Keyword Wizard Step."""
if 'stepfc' in self.__class__.__name__.lower():
return STEP_FC
if 'stepkw' in self.__class__.__name__.lower():
return STEP_KW | 0.008032 |
def from_yw(self, acms):
"""Determine VAR model from autocorrelation matrices by solving the
Yule-Walker equations.
Parameters
----------
acms : array, shape (n_lags, n_channels, n_channels)
acms[l] contains the autocorrelation matrix at lag l. The highest
... | 0.00269 |
def log_stream(client, log_group, stream_name, start_time=0, skip=0):
"""A generator for log items in a single stream. This will yield all the
items that are available at the current moment.
Args:
client (boto3.CloudWatchLogs.Client): The Boto client for CloudWatch logs.
log_group (str): Th... | 0.003047 |
def get_collection(source, name, collection_format, default):
"""get collection named `name` from the given `source` that
formatted accordingly to `collection_format`.
"""
if collection_format in COLLECTION_SEP:
separator = COLLECTION_SEP[collection_format]
value = source.get(name, None)... | 0.001684 |
def make_hashcode(uuid, filepath, file_event):
"""Generate a SHA1 based on the given arguments.
:param uuid: perceval uuid of the item
:param filepath: path of the corresponding file
:param file_event: commit file event
:returns: a SHA1 hash code
"""
content = ':... | 0.004454 |
def freeze_tag(name):
"""
This is not using decorator.py because we need to access original function
not the wrapper.
"""
def decorator(func):
setattr(func, FREEZING_TAG_ATTRIBUTE, name)
return func
return decorator | 0.003891 |
def _map(expr, func, rtype=None, resources=None, args=(), **kwargs):
"""
Call func on each element of this sequence.
:param func: lambda, function, :class:`odps.models.Function`,
or str which is the name of :class:`odps.models.Funtion`
:param rtype: if not provided, will be the dtype o... | 0.002159 |
def load_covarfile(self, file, indices=[], names=[], sample_file=False):
"""Load covariate data from file.
Unlike phenofiles, if we already have data, we keep it (that would be the sex covariate)"""
# Clean up input in case we are given some empty values
var_indices = []
for x ... | 0.005193 |
def discover_extensions(self):
"""Discover available extensions."""
if self._discovery_done:
return
try:
previous_state = self._extensions.copy()
for app_config in apps.get_app_configs():
indexes_path = '{}.extensions'.format(app_config.name)... | 0.004505 |
def l1_l2_regularizer(weight_l1=1.0, weight_l2=1.0, scope=None):
"""Define a L1L2 regularizer.
Args:
weight_l1: scale the L1 loss by this factor.
weight_l2: scale the L2 loss by this factor.
scope: Optional scope for name_scope.
Returns:
a regularizer function.
"""
def regularizer(tensor):
... | 0.010711 |
def sample(self, multiplicity):
r"""
Randomly sample azimuthal angles `\phi`.
:param int multiplicity: Number to sample.
:returns: Array of sampled angles.
"""
if self._n is None:
return self._uniform_phi(multiplicity)
# Since the flow PDF does not... | 0.001318 |
def update(table_name, **fields):
""" Build a update query.
>>> update('foo_table', a=5, b=2)
"UPDATE `foo_table` SET `a`=%(_QB_a)s, `b`=%(_QB_b)s", { '_QB_a': 5, '_QB_b': 2 }
"""
prefix = "UPDATE `%s` SET " % table_name
sets, params = simple_expression(', ', **fields)
return prefix + sets,... | 0.006116 |
def common_type(a, b):
""" Returns a type which is common for both a and b types.
Returns None if no common types allowed.
"""
from symbols.type_ import SymbolBASICTYPE as BASICTYPE
from symbols.type_ import Type as TYPE
from symbols.type_ import SymbolTYPE
if a is None or b is None:
... | 0.000845 |
def main(N=32, n=32, ndiag=1, main_diag_factor=1.0, off_diag_factor=1.0,
base_seed=0, seed_range=1, fact_pow2_min=4, fact_pow2_max=18,
plot=False, npows=0, scan_ndiag=False, savefig='None'):
"""
Ax = b
"""
npows = npows or fact_pow2_max - fact_pow2_min
factors = np.linspace(fact_p... | 0.001743 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.