text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def gauss_fit(X, Y):
"""
Fit the function to a gaussian.
Parameters
----------
X: 1d array
X values
Y: 1d array
Y values
Returns
-------
(The return from scipy.optimize.curve_fit)
popt : array
Optimal values for the parameters
pcov : 2d array
... | 0.0022 |
def process_spawn_qty(self, name):
"""Return the number of processes to spawn for the given consumer name.
:param str name: The consumer name
:rtype: int
"""
return self.consumers[name].qty - self.process_count(name) | 0.007752 |
def track_end(self):
"""
Ends tracking of attributes changes.
Returns the changes that occurred to the attributes.
Only the final state of each attribute is obtained
"""
self.__tracking = False
changes = self.__changes
self.__changes = {}
return ... | 0.006116 |
def modify_endpoint(EndpointArn=None, EndpointIdentifier=None, EndpointType=None, EngineName=None, Username=None, Password=None, ServerName=None, Port=None, DatabaseName=None, ExtraConnectionAttributes=None, CertificateArn=None, SslMode=None, DynamoDbSettings=None, S3Settings=None, MongoDbSettings=None):
"""
Mo... | 0.004688 |
def list_user_access(self, user):
"""
Returns a list of all database names for which the specified user
has access rights.
"""
user = utils.get_name(user)
uri = "/%s/%s/databases" % (self.uri_base, user)
try:
resp, resp_body = self.api.method_get(uri)
... | 0.003717 |
def tarbell_configure(command, args):
"""
Tarbell configuration routine.
"""
puts("Configuring Tarbell. Press ctrl-c to bail out!")
# Check if there's settings configured
settings = Settings()
path = settings.path
prompt = True
if len(args):
prompt = False
config = _ge... | 0.002566 |
def filter_inactive_ports(query):
"""Filter ports that aren't in active status """
port_model = models_v2.Port
query = (query
.filter(port_model.status == n_const.PORT_STATUS_ACTIVE))
return query | 0.004444 |
def get_history_tags(self, exp, rep=0):
""" returns all available tags (logging keys) of the given experiment
repetition.
Note: Technically, each repetition could have different
tags, therefore the rep number can be passed in as parameter,
even tho... | 0.013035 |
def to_yaml_file(obj, f):
"""
Convert Python objects (including rpcq messages) to yaml and write it to `f`.
"""
yaml.dump(rapidjson.loads(to_json(obj)), f) | 0.011696 |
def load_machine(self, descriptor):
"""
Load a complete register machine.
The descriptor is a map, unspecified values are loaded from the default values.
"""
def get_cfg(name):
if(name in descriptor):
return descriptor[name]
else:
return defaults[name]
self.processor = Processor(width = get_... | 0.032724 |
def rerank(args: argparse.Namespace):
"""
Reranks a list of hypotheses according to a sentence-level metric.
Writes all output to STDOUT.
:param args: Namespace object holding CLI arguments.
"""
reranker = Reranker(args.metric, args.return_score)
with utils.smart_open(args.reference) as re... | 0.003955 |
def numericalize(self, t:Collection[str]) -> List[int]:
"Convert a list of tokens `t` to their ids."
return [self.stoi[w] for w in t] | 0.020134 |
def matches_address(self, address):
"""returns whether this account knows about an email address
:param str address: address to look up
:rtype: bool
"""
if self.address == address:
return True
for alias in self.aliases:
if alias == address:
... | 0.004396 |
def finish(self):
"""Finishes transconding and returns the video.
Returns:
bytes
Raises:
IOError: in case of transcoding error.
"""
if self.proc is None:
return None
self.proc.stdin.close()
for thread in (self._out_thread, self._err_thread):
thread.join()
(out, ... | 0.007813 |
def _bcbio_variation_ensemble(vrn_files, out_file, ref_file, config_file, base_dir, data):
"""Run a variant comparison using the bcbio.variation toolkit, given an input configuration.
"""
vrn_files = [_handle_somatic_ensemble(v, data) for v in vrn_files]
tmp_dir = utils.safe_makedir(os.path.join(base_di... | 0.004739 |
def compute(self, tdb, tdb2, derivative=True):
"""Generate angles and derivatives for time `tdb` plus `tdb2`.
If ``derivative`` is true, return a tuple containing both the
angle and its derivative; otherwise simply return the angles.
"""
scalar = not getattr(tdb, 'shape', 0) an... | 0.002818 |
def _call(self, x, out=None):
"""Apply resampling operator.
The element ``x`` is resampled using the sampling and interpolation
operators of the underlying spaces.
"""
if out is None:
return x.interpolation
else:
out.sampling(x.interpolation) | 0.006349 |
def type_from_ast(schema, type_node): # noqa: F811
"""Get the GraphQL type definition from an AST node.
Given a Schema and an AST node describing a type, return a GraphQLType definition
which applies to that type. For example, if provided the parsed AST node for
`[User]`, a GraphQLList instance will b... | 0.004587 |
def vcenter_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
vcenter = ET.SubElement(config, "vcenter", xmlns="urn:brocade.com:mgmt:brocade-vswitch")
id = ET.SubElement(vcenter, "id")
id.text = kwargs.pop('id')
callback = kwargs.pop('c... | 0.007958 |
def process_data(data, models):
""" Convert ``data`` to processed data using ``models``.
Data from dictionary ``data`` is processed by each model
in list ``models``, and the results collected into a new
dictionary ``pdata`` for use in :meth:`MultiFitter.lsqfit`
and :meth:`MultiF... | 0.003145 |
def _iter_from_annotations_dict(graph: BELGraph,
annotations_dict: AnnotationsDict,
) -> Iterable[Tuple[str, Set[str]]]:
"""Iterate over the key/value pairs in this edge data dictionary normalized to their source URLs."""
for key, n... | 0.008168 |
def _generate_docker_image_version(layers, runtime):
"""
Generate the Docker TAG that will be used to create the image
Parameters
----------
layers list(samcli.commands.local.lib.provider.Layer)
List of the layers
runtime str
Runtime of the image... | 0.007136 |
def unpack_rawr_zip_payload(table_sources, payload):
"""unpack a zipfile and turn it into a callable "tables" object."""
# the io we get from S3 is streaming, so we can't seek on it, but zipfile
# seems to require that. so we buffer it all in memory. RAWR tiles are
# generally up to around 100MB in size... | 0.001148 |
def create_was_invalidated_by_relation(self, activity_id, entity_kind, entity_id):
"""
Create a was invalidated by relationship between an activity and a entity(file).
:param activity_id: str: uuid of the activity
:param entity_kind: str: kind of entity('dds-file')
:param entity_... | 0.009058 |
def _validate_options(self):
'''
Make sure there are no conflicting or invalid options
'''
if self.obfuscate_hostname and not self.obfuscate:
raise ValueError(
'Option `obfuscate_hostname` requires `obfuscate`')
if self.analyze_image_id is not None and... | 0.002173 |
def scatter_plot(self, ax, topic_dims, t=None, ms_limits=True, **kwargs_plot):
""" 2D or 3D scatter plot.
:param axes ax: matplotlib axes (use Axes3D if 3D data)
:param tuple topic_dims: list of (topic, dims) tuples, where topic is a string and dims is a list of dimensions to be plotte... | 0.006908 |
def _finish_fragment(self):
""" Creates fragment
"""
if self.fragment:
self.fragment.finish()
if self.fragment.headers:
# Regardless of what's been seen to this point, if we encounter a headers fragment,
# all the previous fragments should... | 0.00426 |
def listPrimaryDsTypes(self, primary_ds_type="", dataset=""):
"""
API to list primary dataset types
:param primary_ds_type: List that primary dataset type (Optional)
:type primary_ds_type: str
:param dataset: List the primary dataset type for that dataset (Optional)
:typ... | 0.006838 |
def RandomGraph(nodes=range(10), min_links=2, width=400, height=300,
curvature=lambda: random.uniform(1.1, 1.5)):
"""Construct a random graph, with the specified nodes, and random links.
The nodes are laid out randomly on a (width x height) rectangle.
Then each node is connec... | 0.005263 |
def server_update(s_name, s_ip, **connection_args):
'''
Update a server's attributes
CLI Example:
.. code-block:: bash
salt '*' netscaler.server_update 'serverName' 'serverIP'
'''
altered = False
cur_server = _server_get(s_name, **connection_args)
if cur_server is None:
... | 0.002119 |
def add_to_buffer(self, content, read_position):
"""Add additional bytes content as read from the read_position.
Args:
content (bytes): data to be added to buffer working BufferWorkSpac.
read_position (int): where in the file pointer the data was read from.
"""
s... | 0.005988 |
def show_linkinfo_output_show_link_info_linkinfo_version(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_linkinfo = ET.Element("show_linkinfo")
config = show_linkinfo
output = ET.SubElement(show_linkinfo, "output")
show_link_info = E... | 0.004027 |
def get_storer(self, key):
""" return the storer object for a key, raise if not in the file """
group = self.get_node(key)
if group is None:
raise KeyError('No object named {key} in the file'.format(key=key))
s = self._create_storer(group)
s.infer_axes()
retu... | 0.006173 |
def redraw_now(self, whence=0):
"""Redraw the displayed image.
Parameters
----------
whence
See :meth:`get_rgb_object`.
"""
try:
time_start = time.time()
self.redraw_data(whence=whence)
# finally update the window drawabl... | 0.002457 |
def splitclass(classofdevice):
"""
Splits the given class of device to return a 3-item tuple with the
major service class, major device class and minor device class values.
These values indicate the device's major services and the type of the
device (e.g. mobile phone, laptop, etc.). If you google ... | 0.003033 |
def clear_routing_table_entries(self, x, y, app_id):
"""Clear the routing table entries associated with a given application.
"""
# Construct the arguments
arg1 = (app_id << 8) | consts.AllocOperations.free_rtr_by_app
self._send_scp(x, y, 0, SCPCommands.alloc_free, arg1, 0x1) | 0.006349 |
def insert_import_path_to_sys_modules(import_path):
"""
When importing a module, Python references the directories in sys.path.
The default value of sys.path varies depending on the system, But:
When you start Python with a script, the directory of the script is inserted into sys.path[0].
So we hav... | 0.003565 |
def get_private(self):
""" Derive private key from the brain key and the current sequence
number
"""
encoded = "%s %d" % (self.brainkey, self.sequence)
a = _bytes(encoded)
s = hashlib.sha256(hashlib.sha512(a).digest()).digest()
return PrivateKey(hexlify(s).dec... | 0.005666 |
def read_inquiry_mode(sock):
"""returns the current mode, or -1 on failure"""
# save current filter
old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)
# Setup socket filter to receive only events related to the
# read_inquiry_mode command
flt = bluez.hci_filter_new()
opcode ... | 0.0143 |
def parseBranches(self, descendants):
"""
Parse top level of markdown
:param list elements: list of source objects
:return: list of filtered TreeOfContents objects
"""
parsed, parent, cond = [], False, lambda b: (b.string or '').strip()
for branch in filter(cond,... | 0.007937 |
def showhtml():
"""Open your web browser and display the generated html documentation.
"""
import webbrowser
# copy from paver
opts = options
docroot = path(opts.get('docroot', 'docs'))
if not docroot.exists():
raise BuildFailure("Sphinx documentation root (%s) does not exist."
... | 0.003091 |
def repack(self):
"""Removes any blank ranks in the order."""
items = self.grouped_filter().order_by('rank').select_for_update()
for count, item in enumerate(items):
item.rank = count + 1
item.save(rerank=False) | 0.007722 |
def grouper(self, n, iterable, fillvalue=None):
"""This generator yields a set of tuples, where the
iterable is broken into n sized chunks. If the
iterable is not evenly sized then fillvalue will
be appended to the last tuple to make up the difference.
This function is copied fr... | 0.003384 |
def defconfig_filename(self):
"""
See the class documentation.
"""
if self.defconfig_list:
for filename, cond in self.defconfig_list.defaults:
if expr_value(cond):
try:
with self._open_config(filename.str_value) as f... | 0.004415 |
def _init_metadata(self):
"""stub"""
self._choices_metadata = {
'element_id': Id(self.my_osid_object_form._authority,
self.my_osid_object_form._namespace,
'choices'),
'element_label': 'Choices',
'instructions':... | 0.001107 |
def gen(mimetype):
"""``gen`` is a decorator factory function, you just need to set
a mimetype before using::
@app.route('/')
@gen('')
def index():
pass
A full demo for creating a image stream is available on
`GitHub <https://github.com/kxxoling/flask-video-streamin... | 0.001815 |
def URLField(default=NOTHING, required=True, repr=True, cmp=True, key=None):
"""
Create new UUID field on a model.
:param default: any value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bo... | 0.001302 |
def set_initial_status(self, configuration=None):
"""
Override behaviour of methods in class DiffusionModel.
Overwrites initial status using random real values.
Generates random node profiles.
"""
super(CognitiveOpDynModel, self).set_initial_status(configuration)
... | 0.005717 |
def from_index_amount(cls, idx, amount):
"""
Like Deformation.from_index_amount, except generates
a strain from the zero 3x3 tensor or voigt vector with
the amount specified in the index location. Ensures
symmetric strain.
Args:
idx (tuple or integer): index... | 0.002148 |
def get_exception_error():
''' Get the exception info
Sample usage:
try:
raise Exception("asdfsdfsdf")
except:
print common.get_exception_error()
Return:
return the exception infomation.
'''
error_messa... | 0.009667 |
def raw_conf_process_pyramid(raw_conf):
"""
Loads the process pyramid of a raw configuration.
Parameters
----------
raw_conf : dict
Raw mapchete configuration as dictionary.
Returns
-------
BufferedTilePyramid
"""
return BufferedTilePyramid(
raw_conf["pyramid"][... | 0.002188 |
def value(self) -> Union[bool, None]:
"""Returns the concrete value of this bool if concrete, otherwise None.
:return: Concrete value or None
"""
self.simplify()
if self.is_true:
return True
elif self.is_false:
return False
else:
... | 0.005988 |
def check_boto_reqs(boto_ver=None,
boto3_ver=None,
botocore_ver=None,
check_boto=True,
check_boto3=True):
'''
Checks for the version of various required boto libs in one central location. Most
boto states and modules rely on a s... | 0.005867 |
def LogBinomialCoef(n, k):
"""Computes the log of the binomial coefficient.
http://math.stackexchange.com/questions/64716/
approximating-the-logarithm-of-the-binomial-coefficient
n: number of trials
k: number of successes
Returns: float
"""
return n * log(n) - k * log(k) - (n - k) * l... | 0.00304 |
def FillDeviceAttributes(device, descriptor):
"""Fill out the attributes of the device.
Fills the devices HidAttributes and product string
into the descriptor.
Args:
device: A handle to the open device
descriptor: The DeviceDescriptor to populate with the
attributes.
Returns:
None
Rais... | 0.013111 |
def from_payload(self, payload):
"""Init frame from binary data."""
self.major_version = payload[0] * 256 + payload[1]
self.minor_version = payload[2] * 256 + payload[3] | 0.010363 |
def get_comment_admin_session(self, proxy):
"""Gets the ``OsidSession`` associated with the comment administration service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.commenting.CommentAdminSession) - a
``CommentAdminSession``
raise: NullArgument - ``proxy`... | 0.003663 |
def _notify_media_transport_available(self, path, transport):
"""
Called by the endpoint when a new media transport is
available
"""
self.source = BTAudioSource(dev_path=path)
self.state = self.source.State
self.source.add_signal_receiver(self._property_change_eve... | 0.004264 |
def dump_privatekey(type, pkey, cipher=None, passphrase=None):
"""
Dump the private key *pkey* into a buffer string encoded with the type
*type*. Optionally (if *type* is :const:`FILETYPE_PEM`) encrypting it
using *cipher* and *passphrase*.
:param type: The file type (one of :const:`FILETYPE_PEM`,... | 0.000472 |
def find_table_links(self):
"""
When given a url, this function will find all the available table names
for that EPA dataset.
"""
html = urlopen(self.model_url).read()
doc = lh.fromstring(html)
href_list = [area.attrib['href'] for area in doc.cssselect('map area')... | 0.005013 |
def primes(n):
"""
Simple test function
Taken from http://www.huyng.com/posts/python-performance-analysis/
"""
if n==2:
return [2]
elif n<2:
return []
s=list(range(3,n+1,2))
mroot = n ** 0.5
half=(n+1)//2-1
i=0
m=3
while m <= mroot:
... | 0.031068 |
def Entry(self, name, directory=None, create=1):
""" Create `SCons.Node.FS.Entry` """
return self._create_node(name, self.env.fs.Entry, directory, create) | 0.011765 |
def calculate_prorated_values():
"""
A utility function to prompt for a rate (a string in units per
unit time), and return that same rate for various time periods.
"""
rate = six.moves.input("Enter the rate (3/hour, 50/month)> ")
res = re.match(r'(?P<value>[\d.]+)/(?P<period>\w+)$', rate).groupdict()
value = flo... | 0.020725 |
def perform_create(self, serializer):
""" determine user when node is added """
if serializer.instance is None:
serializer.save(user=self.request.user) | 0.011173 |
def leave_group(self, group_jid):
"""
Leaves a specific group
:param group_jid: The JID of the group to leave
"""
log.info("[+] Leaving group {}".format(group_jid))
return self._send_xmpp_element(group_adminship.LeaveGroupRequest(group_jid)) | 0.010345 |
def one_storage_per_feeder(edisgo, storage_timeseries,
storage_nominal_power=None, **kwargs):
"""
Allocates the given storage capacity to multiple smaller storages.
For each feeder with load or voltage issues it is checked if integrating a
storage will reduce peaks in the fee... | 0.000549 |
def set_model_domain(model, domain):
"""
Sets the domain on the ONNX model.
:param model: instance of an ONNX model
:param domain: string containing the domain name of the model
Example:
::
from onnxmltools.utils import set_model_domain
onnx_model = load_model("SqueezeNet.onnx... | 0.001555 |
def format_for_baseline_output(self):
"""
:rtype: dict
"""
results = self.json()
for key in results:
results[key] = sorted(results[key], key=lambda x: x['line_number'])
plugins_used = list(map(
lambda x: x.__dict__,
self.plugins,
... | 0.002729 |
def is_suspended(order_book_id, count=1):
"""
判断某只股票是否全天停牌。
:param str order_book_id: 某只股票的代码或股票代码,可传入单只股票的order_book_id, symbol
:param int count: 回溯获取的数据个数。默认为当前能够获取到的最近的数据
:return: count为1时 `bool`; count>1时 `pandas.DataFrame`
"""
dt = Environment.get_instance().calendar_dt.date()
or... | 0.00432 |
def ids(cls, values, itype=None):
'''
http://www.elasticsearch.org/guide/reference/query-dsl/ids-filter.html
Filters documents that only have the provided ids. Note, this filter does not require the _id field to be indexed since it works using the _uid field.
'''
instance = cls(ids={'va... | 0.006912 |
def start(self):
""" Start the sensor """
# open device
openni2.initialize(PrimesenseSensor.OPENNI2_PATH)
self._device = openni2.Device.open_any()
# open depth stream
self._depth_stream = self._device.create_depth_stream()
self._depth_stream.configure_mode(Primes... | 0.005682 |
def fixMissingPythonLib(self, binaries):
"""Add the Python library if missing from the binaries.
Some linux distributions (e.g. debian-based) statically build the
Python executable to the libpython, so bindepend doesn't include
it in its output.
Darwin custom builds could possi... | 0.003132 |
def get_node_list(self) -> list:
"""Get a list of nodes.
Only the manager nodes can retrieve all the nodes
Returns:
list, all the ids of the nodes in swarm
"""
# Initialising empty list
nodes = []
# Raise an exception if we are not a manager
... | 0.003311 |
def process_field(elt, ascii=False):
"""Process a 'field' tag.
"""
# NOTE: if there is a variable defined in this field and it is different
# from the default, we could change the value and restart.
scale = np.uint8(1)
if elt.get("type") == "bitfield" and not ascii:
current_type = ">u"... | 0.001026 |
def check_misc(text):
"""Avoid mixing metaphors.
source: Garner's Modern American Usage
source_url: http://bit.ly/1T4alrY
"""
err = "mixed_metaphors.misc.misc"
msg = u"Mixed metaphor. Try '{}'."
preferences = [
["cream rises to the top", ["cream rises to the crop"]],
... | 0.001527 |
def get_transition(self, # suppress(too-many-arguments)
line,
line_index,
column,
is_escaped,
comment_system_transitions,
eof=False):
"""Return a parser state, a move-ahead ... | 0.012638 |
def wait(self, timeout=None):
"""
Block until the container stops, then return its exit code. Similar to
the ``podman wait`` command.
:param timeout: int, microseconds to wait before polling for completion
:return: int, exit code
"""
timeout = ["--interval=%s" % ... | 0.004202 |
def ratio_beyond_r_sigma(x, r):
"""
Ratio of values that are more than r*std(x) (so r sigma) away from the mean of x.
:param x: the time series to calculate the feature of
:type x: iterable
:return: the value of this feature
:return type: float
"""
if not isinstance(x, (np.ndarray, pd.S... | 0.004773 |
def from_indra_statements(stmts,
name: Optional[str] = None,
version: Optional[str] = None,
description: Optional[str] = None,
authors: Optional[str] = None,
contact: Optional[str] = None,
... | 0.001309 |
def _handle(self, nick, target, message, **kwargs):
""" client callback entrance """
for regex, (func, pattern) in self.routes.items():
match = regex.match(message)
if match:
self.client.loop.create_task(
func(nick, target, message, match, **kw... | 0.006135 |
def _maybe_classify(self, y, k, cutoffs):
'''Helper method for classifying continuous data.
'''
rows, cols = y.shape
if cutoffs is None:
if self.fixed:
mcyb = mc.Quantiles(y.flatten(), k=k)
yb = mcyb.yb.reshape(y.shape)
cutoff... | 0.002315 |
def add_role(self, role, term, start_date=None, end_date=None,
**kwargs):
"""
Examples:
leg.add_role('member', term='2009', chamber='upper',
party='Republican', district='10th')
"""
self['roles'].append(dict(role=role, term=term,
... | 0.006993 |
def list_rooms(self, message):
"""what are the rooms?: List all the rooms I know about."""
context = {"rooms": self.available_rooms.values(), }
self.say(rendered_template("rooms.html", context), message=message, html=True) | 0.012195 |
def GetMemBalloonedMB(self):
'''Retrieves the amount of memory that has been reclaimed from this virtual
machine by the vSphere memory balloon driver (also referred to as the
"vmmemctl" driver).'''
counter = c_uint()
ret = vmGuestLib.VMGuestLib_GetMemBalloonedMB(self.handle... | 0.013423 |
def _send(self, messages):
"""A helper method that does the actual sending."""
if len(messages) == 1:
to_send = self._build_message(messages[0])
if to_send is False:
# The message was missing recipients.
# Bail.
return False
... | 0.003546 |
def get_requirements(filename=None):
"""
Read requirements from 'requirements txt'
:return: requirements
:rtype: list
"""
if filename is None:
filename = 'requirements.txt'
file = WORK_DIR / filename
install_reqs = parse_requirements(str(file), session='hack')
return [str(... | 0.002849 |
def setObjectName( self, objectName ):
"""
Updates the style sheet for this line edit when the name changes.
:param objectName | <str>
"""
super(XLineEdit, self).setObjectName(objectName)
self.adjustStyleSheet() | 0.017857 |
def crop(self, doy, depth, lat, lon, var):
""" Crop a subset of the dataset for each var
Given doy, depth, lat and lon, it returns the smallest subset
that still contains the requested coordinates inside it.
It handels special cases like a region around greenwich and
... | 0.002112 |
def read(self, file_or_filename):
""" Loads a pickled case.
"""
if isinstance(file_or_filename, basestring):
fname = os.path.basename(file_or_filename)
logger.info("Unpickling case file [%s]." % fname)
file = None
try:
file = open(... | 0.004329 |
def random_peak_magnitudes(
log,
peakMagnitudeDistributions,
snTypesArray,
plot=True):
"""
*Generate a numpy array of random (distribution weighted) peak magnitudes for the given sn types.*
**Key Arguments:**
- ``log`` -- logger
- ``peakMagnitudeDistributions... | 0.006192 |
def save(self, config=None):
"""Saves config to config files.
Args:
config (configobj.ConfigObj): optional config object to save.
Raises:
dvc.config.ConfigError: thrown if failed to write config file.
"""
if config is not None:
clist = [confi... | 0.001771 |
def save(self, request, connect=False):
"""
Saves a new account. Note that while the account is new,
the user may be an existing one (when connecting accounts)
"""
assert not self.is_existing
user = self.user
user.save()
self.account.user = user
se... | 0.003096 |
def build_uri(orig_uriparts, kwargs):
"""
Build the URI from the original uriparts and kwargs. Modifies kwargs.
"""
uriparts = []
for uripart in orig_uriparts:
# If this part matches a keyword argument (starting with _), use
# the supplied value. Otherwise, just use the part.
... | 0.001399 |
def render(self, name, value, attrs=None, renderer=None):
"""Include a hidden input to store the serialized upload value."""
location = getattr(value, '_seralized_location', '')
if location and not hasattr(value, 'url'):
value.url = '#'
if hasattr(self, 'get_template_subs... | 0.003018 |
def _get_reference_classnames(self, classname, namespace,
resultclass_name, role):
"""
Get list of classnames that are references for which this classname
is a target filtered by the result_class and role parameters if they
are none.
This is a co... | 0.002433 |
def long_path_formatter(line, max_width=pd.get_option('max_colwidth')):
"""
If a path is longer than max_width, it substitute it with the first and last element,
joined by "...". For example 'this.is.a.long.path.which.we.want.to.shorten' becomes
'this...shorten'
:param line:
:param max_width:
... | 0.006359 |
def ap_state(value, failure_string=None):
"""
Converts a state's name, postal abbreviation or FIPS to A.P. style.
Example usage:
>> ap_state("California")
'Calif.'
"""
try:
return statestyle.get(value).ap
except:
if failure_string:
retur... | 0.013333 |
def logged_in():
"""
Method called by Strava (redirect) that includes parameters.
- state
- code
- error
"""
error = request.args.get('error')
state = request.args.get('state')
if error:
return render_template('login_error.html', error=error)
else:
code = request.... | 0.005814 |
def _insert(self, dom_group, idx=None, prepend=False, name=None):
"""Inserts a DOMGroup inside this element.
If provided at the given index, if prepend at the start of the childs list, by default at the end.
If the child is a DOMElement, correctly links the child.
If the DOMGroup have a ... | 0.003263 |
def primitive_datatype_nostring(self, t: URIRef, v: Optional[str] = None) -> Optional[URIRef]:
"""
Return the data type for primitive type t, if any, defaulting string to no type
:param t: type
:param v: value - for munging dates if we're doing FHIR official output
:return: corre... | 0.007273 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.