text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def setup_formats(self):
"""
Inspects its methods to see what it can convert from and to
"""
methods = self.get_methods()
for m in methods:
#Methods named "from_X" will be assumed to convert from format X to the common format
if m.startswith("from_"):
... | 0.017513 |
def _hide_column(self, column):
'''Hides a column by prefixing the name with \'__\''''
column = _ensure_string_from_expression(column)
new_name = self._find_valid_name('__' + column)
self._rename(column, new_name) | 0.008163 |
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return ... | 0.005065 |
def set_printoptions(**kwargs):
"""Set printing options.
These options determine the way JPEG 2000 boxes are displayed.
Parameters
----------
short : bool, optional
When True, only the box ID, offset, and length are displayed. Useful
for displaying only the basic structure or skel... | 0.000823 |
def lstm(name, input, state_c, state_h, kernel_i, kernel_j, kernel_f, kernel_o, bias_i, bias_j, bias_f, bias_o, new_state_c, new_state_h):
''' Full:
- it = f(Xt*Wi + Ht_1*Ri + Pi . Ct_1 + Wbi + Rbi)
- ft = f(Xt*Wf + Ht_1*Rf + Pf . Ct_1 + Wbf + Rbf)
- ct = g(Xt*Wc + Ht_1*Rc + Wbc + Rbc)
- Ct = ft . ... | 0.004248 |
def post_collect(self, obj):
"""
We want to manage the side-effect of not collecting other items of the same type as root model.
If for example, you run the collect on a specific user that is linked to a model "A" linked (ForeignKey)
to ANOTHER user.
Then the collect won't collec... | 0.005479 |
def p_function_body(p):
""" function_body : program_co END FUNCTION
| program_co END SUB
| statements_co END FUNCTION
| statements_co END SUB
| co_statements_co END FUNCTION
| co_statements_co END SUB
... | 0.00404 |
def render_error_page(code, exc, mimetype='text/html', traceback=''):
"""
Render the error page
"""
from giotto.views import get_jinja_template
if 'json' in mimetype:
return json.dumps({
'code': code,
'exception': exc.__class__.__name__,
'message': str(ex... | 0.001582 |
def main():
mesh = parse_gmsh('../commands.msh', '../boundary_lines.dat')
# now create the CRTomo grid
"""
1. Header
2. Nodes
3. Elements: Triangles, Boundary elements
4. Element ids for adjoining boundary elements
"""
str_header = get_header(mesh)
str_nodes = get_nodes(mesh)
... | 0.001486 |
def get_context_data(self, **kwargs):
"""
Add filter form to the context.
TODO: Currently we construct the filter form object twice - in
get_queryset and here, in get_context_data. Will need to figure out a
good way to eliminate extra initialization.
"""
context ... | 0.004292 |
def decode_pdf_date(s: str) -> datetime:
"""Decode a pdfmark date to a Python datetime object
A pdfmark date is a string in a paritcular format. See the pdfmark
Reference for the specification.
"""
if isinstance(s, String):
s = str(s)
if s.startswith('D:'):
s = s[2:]
# Lite... | 0.001323 |
def dataframe( self, only_successful = True ):
"""Return the results as a pandas DataFrame. Note that there is a danger
of duplicate labels here, for example if the results contain a value
with the same name as one of the parameters. To resolve this, parameter names
take precedence over ... | 0.010962 |
def convert_pre(self, markup):
""" Substitutes <pre> to Wikipedia markup by adding a space at the start of a line.
"""
for m in re.findall(self.re["preformatted"], markup):
markup = markup.replace(m, m.replace("\n", "\n "))
markup = re.sub("<pre.*?>\n{0,... | 0.016588 |
def add_filter(self, key, filter_value):
"""
add and validate a filter with value
returns True on success otherwise exception
"""
seek = u"filter[%s]" % key
if self.validate_filter(key, filter_value):
self.filters[key] = filter_value
return True
... | 0.008032 |
def _export_work_errors(self, work, output_file):
"""Saves errors for given work pieces into file.
Args:
work: instance of either AttackWorkPieces or DefenseWorkPieces
output_file: name of the output file
"""
errors = set()
for v in itervalues(work.work):
if v['is_completed'] and ... | 0.006198 |
def distance(latitude_1, longitude_1, elevation_1, latitude_2, longitude_2, elevation_2,
haversine=None):
""" Distance between two points """
# If points too distant -- compute haversine distance:
if haversine or (abs(latitude_1 - latitude_2) > .2 or abs(longitude_1 - longitude_2) > .2):
... | 0.007519 |
def toVector(value):
"""
Convert a value to a MLlib Vector, if possible.
"""
if isinstance(value, Vector):
return value
elif TypeConverters._can_convert_to_list(value):
value = TypeConverters.toList(value)
if all(map(lambda v: TypeConverters._i... | 0.004444 |
def echo_via_pager(*args, **kwargs):
"""Display pager only if it does not fit in one terminal screen.
NOTE: The feature is available only on ``less``-based pager.
"""
try:
restore = 'LESS' not in os.environ
os.environ.setdefault('LESS', '-iXFR')
click.echo_via_pager(*args, **kwa... | 0.002513 |
def get_assessment_data(self, queryset, total_count, user_id):
"""
Calculates and sets the following data for the supplied queryset:
data = {
'count': <the number of items in the queryset>
'percentage': <percentage of total_count queryset represents>
... | 0.00166 |
def update_context(app, pagename, templatename, context, doctree): # pylint: disable=unused-argument
"""
Update the page rendering context to include ``feedback_form_url``.
"""
context['feedback_form_url'] = feedback_form_url(app.config.project, pagename) | 0.011029 |
def sre_to_string(sre_obj, paren=True):
"""sre_parse object to string
:param sre_obj: Output of sre_parse.parse()
:type sre_obj: list
:rtype: str
"""
ret = u''
for i in sre_obj:
if i[0] == sre_parse.IN:
prefix = ''
if len(i[1]) and i[1][0][0] == sre_parse.NEG... | 0.000558 |
def closest_hendecasyllable_patterns(self, scansion: str) -> List[str]:
"""
Find the closest group of matching valid hendecasyllable patterns.
:return: list of the closest valid hendecasyllable patterns; only candidates with a matching
length/number of syllables are considered.
... | 0.00759 |
def y_max(self):
"""Get max y value for the variable."""
end_y = max(y for y, *_ in self.iterator())
if self.combined:
end_y += self.group_offset
return end_y + 2 * self.group_offset | 0.008772 |
def _set_xfpe(self, v, load=False):
"""
Setter method for xfpe, mapped from YANG variable /brocade_interface_ext_rpc/get_media_detail/output/interface/xfpe (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_xfpe is considered as a private
method. Backends lo... | 0.006317 |
def _set_dpod(self, v, load=False):
"""
Setter method for dpod, mapped from YANG variable /dpod (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_dpod is considered as a private
method. Backends looking to populate this variable should
do so via calling... | 0.005031 |
def autoComplete(self,
polygons=[],
polylines=[],
sr=None
):
"""
The autoComplete operation simplifies the process of
constructing new polygons that are adjacent to other polygons.
It constructs ... | 0.009099 |
def _coerce_dtype(self, other_dtype):
"""Possibly change the bin content type to allow correct operations with other operand.
Parameters
----------
other_dtype : np.dtype or type
"""
if self._dtype is None:
new_dtype = np.dtype(other_dtype)
else:
... | 0.008421 |
def from_dict(cls, context_options_dict):
"""Return a context job from a dict output by Context.to_dict."""
import copy
context_options = copy.deepcopy(context_options_dict)
tasks_inserted = context_options.pop('_tasks_inserted', False)
insert_tasks = context_options.pop('inse... | 0.001905 |
def launch_plugin(self):
'''
launch nagios_plugin command
'''
# nagios_plugins probes
for plugin in self.plugins:
# Construct the nagios_plugin command
command = ('%s%s' % (self.plugins[plugin]['path'], self.plugins[plugin]['command']))
try:
... | 0.003034 |
def ReadingBloomFilter(filename, want_lock=False):
"""
Create a read-only bloom filter with an upperbound of
(num_elements, max_fp_prob) as a specification and using filename
as the backing datastore.
"""
with open('{}.desc'.format(filename), 'r') as descriptor:
num_elements = int(descri... | 0.001639 |
def disable(self):
"""
Disable the Cloud.
:returns: A list of mist.clients' updated clouds.
"""
payload = {
"new_state": "0"
}
data = json.dumps(payload)
req = self.request(self.mist_client.uri+'/clouds/'+self.id, data=data)
req.post(... | 0.005115 |
def chdir(directory):
"""Change the current working directory to a different directory for a code
block and return the previous directory after the block exits. Useful to
run commands from a specificed directory.
:param str directory: The directory path to change to for this context.
"""
cur = ... | 0.002445 |
def run(self):
"""Run analysis.
The basic idea is to recursively find all script files in specific
programming language, and analyze each file then sum it up.
"""
n_target_file, n_other_file = 0, 0
code, comment, docstr, purecode = 0, 0, 0, 0
fc = FileCollecti... | 0.001995 |
def _parse_multifile(self, desired_type: Type[T], obj: PersistedObject,
parsing_plan_for_children: Dict[str, AnyParser._RecursiveParsingPlan],
logger: Logger, options: Dict[str, Dict[str, Any]]) -> T:
"""
Implementation of AnyParser API
"""
... | 0.016908 |
def from_notebook_node(self, nb, resources=None, **kw):
"""Takes output of OneCodexHTMLExporter and runs Weasyprint to get a PDF."""
from weasyprint import HTML, CSS
nb = copy.deepcopy(nb)
output, resources = super(OneCodexPDFExporter, self).from_notebook_node(
nb, resource... | 0.008961 |
def _wrap_command(cmds, cls, strict=True):
"""Wrap a setup command
Parameters
----------
cmds: list(str)
The names of the other commands to run prior to the command.
strict: boolean, optional
Whether to raise errors when a pre-command fails.
"""
class WrappedCommand(cls):
... | 0.001253 |
def _read_ready(self):
"""Called by the event loop whenever the fd is ready for reading."""
try:
data = os.read(self._fileno, self.max_size)
except InterruptedError:
# No worries ;)
pass
except OSError as exc:
# Some OS-level problem, cras... | 0.002296 |
def setzscale(self, z1="auto", z2="auto", nsig=3, samplesizelimit = 10000, border=300):
"""
We set z1 and z2, according to different algorithms or arguments.
For both z1 and z2, give either :
- "auto" (default automatic, different between z1 and z2)
- "e... | 0.015176 |
def disconnect(self):
"""
Ends a client authentication session, performs a logout and a clean up.
"""
if self.r_session:
self.session_logout()
self.r_session = None
self.clear() | 0.008403 |
def parse(self, file):
'''
Method the programmer should call when ready to parse a file.
:param file: exact file path of the file to be processed
:return: PieceTree object representing the file in memory
'''
parser = make_parser()
self.clear()
class Extra... | 0.00183 |
def wget(ftp, f = False, exclude = False, name = False, md5 = False, tries = 10):
"""
download files with wget
"""
# file name
if f is False:
f = ftp.rsplit('/', 1)[-1]
# downloaded file if it does not already exist
# check md5s on server (optional)
t = 0
while md5check(f, ft... | 0.017588 |
def handle_request(self, req, validate=True):
'''
handle a jsonrpc request
req - request as jsonrpc-dict
validate - validate the request? (default: True)
returns jsonrpc-dict with result or error
'''
#result that will be filled and returned
res = {'json... | 0.003812 |
def SendToExecSocket(self, code, tid=None):
"""Inject python code into exec socket."""
response = self._SendToExecSocketRaw(json.dumps(code), tid)
return json.loads(response) | 0.005376 |
def with_histogram(name, reservoir_type="uniform", *reservoir_args, **reservoir_kwargs):
"""
Time-measuring decorator: the time spent in the wrapped function is measured
and added to the named metric.
metric_args and metric_kwargs are passed to new_histogram()
"""
hmetric = get_or_create_histog... | 0.00607 |
def major(self):
""" Major inbox feed, contains major activities such as notes and images. """
url = self._subfeed("major")
if "major" in self.url or "minor" in self.url:
return self
if self._major is None:
self._major = self.__class__(url, pypump=self._pump)
... | 0.008772 |
def get(self, key, default=None, type=None):
"""Return the default value if the requested data doesn't exist.
If `type` is provided and is a callable it should convert the value,
return it or raise a :exc:`ValueError` if that is not possible. In
this case the function will return the de... | 0.001642 |
def get_configparser(filename=''):
"""
Read main configuration file and all files from *conf.d* subdirectory
and return parsed configuration as a **configparser.RawConfigParser**
instance.
"""
filename = filename or os.environ.get('SHELTER_CONFIG_FILENAME', '')
if not filename:
raise... | 0.001198 |
def pairwise_align_sequences_to_representative_parallelize(self, sc, gapopen=10, gapextend=0.5, outdir=None,
engine='needle', parse=True, force_rerun=False):
"""Pairwise all sequences in the sequences attribute to the representative sequence. Stores the alig... | 0.007607 |
def _load_profile_imports(self, symbol_table):
"""
profile_imports is a list of module names or tuples
of (module_name, names to import)
in the form of ('.', names) it behaces like:
from . import name1, name2, name3
or similarly
import .name1, .name2, .name3
i.e. "name" in names becomes... | 0.010703 |
def _char_to_string_binary(c, align=ALIGN.LEFT, padding='-'):
"""
>>> _char_to_string_binary('O', align=ALIGN.LEFT)
'O----------'
>>> _char_to_string_binary('O', align=ALIGN.RIGHT)
'----------O'
>>> _char_to_string_binary('O', align=ALIGN.CENTER)
'-----O-----'
"""
s_bin = mtalk.enc... | 0.001445 |
def initmobile_view(request):
"""
Create lazy user with a password. Used from the Android app.
Also returns csrf token.
GET parameters:
username:
user's name
password:
user's password
"""
if 'username' in request.GET and 'password' in request.GET:
... | 0.001065 |
def prompt_4_value(question, choices = None, default = None, display_choices = True, display_indices = False, authorize_list = False, is_question = False, no_confirm = False, required = True, regex = None, regex_format = '', max_laps = 5, input = None, return_index = False):
"""
Prompt for a value
... | 0.009772 |
def bulkCmd(snmpDispatcher, authData, transportTarget,
nonRepeaters, maxRepetitions, *varBinds, **options):
"""Creates a generator to perform one or more SNMP GETBULK queries.
On each iteration, new SNMP GETBULK request is send
(:RFC:`1905#section-4.2.3`). The iterator blocks waiting for respon... | 0.002264 |
async def read(response, loads=loads, encoding=None):
"""
read the data of the response
Parameters
----------
response : aiohttp.ClientResponse
response
loads : callable
json loads function
encoding : :obj:`str`, optional
character encoding of the response, if se... | 0.000841 |
def possible_params(self):
""" Used when assuming params is a list. """
return self.params if isinstance(self.params, list) else [self.params] | 0.012658 |
def airline_delay(data_set='airline_delay', num_train=700000, num_test=100000, seed=default_seed):
"""Airline delay data used in Gaussian Processes for Big Data by Hensman, Fusi and Lawrence"""
if not data_available(data_set):
download_data(data_set)
dir_path = os.path.join(data_path, data_set)
... | 0.005755 |
def interactive(self):
"""Run in interactive mode."""
while True:
line = sys.stdin.readline().strip()
if line == 'quit':
sys.exit()
elif line == 'validate':
self.check_syntax()
self.check_imports()
self.c... | 0.003937 |
def __git_commit(git_tag):
"""
Commit files to branch.
The function call will return 0 if the command success.
"""
Shell.msg('Commit changes.')
if APISettings.DEBUG:
Shell.debug('Execute "git commit" in dry mode.')
if not call(['git', 'commit', '-m... | 0.005769 |
def set_log_type_name(self, logType, name):
"""
Set a logtype name.
:Parameters:
#. logType (string): A defined logging type.
#. name (string): The logtype new name.
"""
assert logType in self.__logTypeStdoutFlags.keys(), "logType '%s' not defined" %logType... | 0.008734 |
def copy(self, other, ignore=None, parameters=None, parameter_names=None,
read_args=None, write_args=None):
"""Copies metadata, info, and samples in this file to another file.
Parameters
----------
other : str or InferenceFile
The file to write to. May be either... | 0.001118 |
def _add_outcome_provenance(self, association, outcome):
"""
:param association: str association curie
:param outcome: dict (json)
:return: None
"""
provenance = Provenance(self.graph)
base = self.curie_map.get_base()
provenance.add_agent_to_graph(base, '... | 0.004785 |
def refresh(self):
"""Re-pulls the data from redis"""
redis_key = EXPERIMENT_REDIS_KEY_TEMPLATE % self.experiment.name
self.plays = int(self.experiment.redis.hget(redis_key, "%s:plays" % self.name) or 0)
self.rewards = int(self.experiment.redis.hget(redis_key, "%s:rewards" % self.name) ... | 0.010178 |
def _EnsureFileExists(self):
"""Touches a file; returns False on error, True on success."""
if not os.path.exists(self._filename):
old_umask = os.umask(0o177)
try:
open(self._filename, 'a+b').close()
except OSError:
return False
... | 0.005141 |
def _dismantle_callsign(self, callsign, timestamp=timestamp_now):
""" try to identify the callsign's identity by analyzing it in the following order:
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Raises:
... | 0.007511 |
def push_scope(self, callback=None): # noqa
"""Pushes a new layer on the scope stack. Returns a context manager
that should be used to pop the scope again. Alternatively a callback
can be provided that is executed in the context of the scope.
"""
if callback is not None:
... | 0.003466 |
def equation(self):
"""Mix-in class that returns matrix rows for leaky wall condition.
Qnormal = resfac * (headin - headout)
Returns matrix part (nunknowns,neq)
Returns rhs part nunknowns
"""
mat = np.empty((self.nunknowns, self.model.neq))
rhs = np.zeros(self.nun... | 0.007645 |
def data_context(fn, mode="r"):
"""
Return content fo the `fn` from the `template_data` directory.
"""
with open(data_context_name(fn), mode) as f:
return f.read() | 0.005348 |
def nexttime(self, lastts):
'''
Returns next timestamp that meets requirements, incrementing by (self.incunit * incval) if not increasing, or
0.0 if there are no future matches
'''
lastdt = datetime.datetime.fromtimestamp(lastts, tz.utc)
newvals = {} # all the new fields... | 0.003093 |
def is_logged_in(self, name_id):
""" Check if user is in the cache
:param name_id: The identifier of the subject
"""
identity = self.users.get_identity(name_id)[0]
return bool(identity) | 0.00885 |
def is_group_or_super_group(cls, obj) -> bool:
"""
Check chat is group or super-group
:param obj:
:return:
"""
return cls._check(obj, [cls.GROUP, cls.SUPER_GROUP]) | 0.009434 |
def requeue(self):
"""Loop endlessly and requeue expired jobs."""
job_requeue_interval = float(
self.config.get('sharq', 'job_requeue_interval'))
while True:
self.sq.requeue()
gevent.sleep(job_requeue_interval / 1000.00) | 0.007143 |
def hashes(self, trust_internet=True):
# type: (bool) -> Hashes
"""Return a hash-comparer that considers my option- and URL-based
hashes to be known-good.
Hashes in URLs--ones embedded in the requirements file, not ones
downloaded from an index server--are almost peers with ones... | 0.00291 |
def generateIndex(self, refresh=0, refresh_index=0):
"""Writes the index file"""
open(self.index_file, "wt").write(self.renderIndex(refresh=refresh, refresh_index=refresh_index)) | 0.015464 |
def experimentVaryingSynapseSampling(expParams,
sampleSizeDistalList,
sampleSizeProximalList):
"""
Test multi-column convergence with varying amount of proximal/distal sampling
:return:
"""
numRpts = 20
df = None
args = []
for sa... | 0.011897 |
def get_header_url(response, header_name):
"""Get a URL from a header requests.
:param requests.Response response: REST call response.
:param str header_name: Header name.
:returns: URL if not None AND valid, None otherwise
"""
url = response.headers.get(header_name)
try:
_validate(... | 0.002525 |
def insert_optimization_option_group(parser):
"""
Adds the options used to specify optimization-specific options.
Parameters
----------
parser : object
OptionParser instance
"""
optimization_group = parser.add_argument_group("Options for selecting "
... | 0.003699 |
def _load_view(self, template_engine_name, template_dir):
"""
Load view by name and return an instance.
"""
file_name = template_engine_name.lower()
class_name = "{}View".format(template_engine_name.title())
try:
view_module = import_module("rails.views.{}".fo... | 0.005405 |
def expo(base=2, factor=1, max_value=None):
"""Generator for exponential decay.
Args:
base: The mathematical base of the exponentiation operation
factor: Factor to multiply the exponentation by.
max_value: The maximum value to yield. Once the value in the
true exponential s... | 0.001664 |
def close_streaming_interface(self):
"""Called when someone closes the streaming interface to the device.
This method will automatically notify sensor_graph that there is a no
longer a streaming interface opened.
"""
super(ReferenceDevice, self).close_streaming_interface()
... | 0.005181 |
def get(self, **kwargs):
"""
Queries database for results of view
:return:
"""
db_url = ':'.join([options.url_registry_db, str(options.db_port)])
db = couch.AsyncCouch(db_name=self.db_name, couch_url=db_url)
result = yield db.view(
design_doc_name=sel... | 0.004854 |
def create(name, url, tournament_type="single elimination", **params):
"""Create a new tournament."""
params.update({
"name": name,
"url": url,
"tournament_type": tournament_type,
})
return api.fetch_and_parse("POST", "tournaments", "tournament", **params) | 0.003367 |
def enhex(d, separator=''):
"""
Convert bytes to their hexadecimal representation, optionally joined by a
given separator.
Args:
d(bytes): The data to convert to hexadecimal representation.
separator(str): The separator to insert between hexadecimal tuples.
Returns:
str: Th... | 0.001346 |
def listItem(node):
"""
An item in a list
"""
o = nodes.list_item()
for n in MarkDown(node):
o += n
return o | 0.007143 |
def add_subparser(subparsers):
"""Add command line arguments as server subparser.
"""
parser = subparsers.add_parser("server", help="Run a bcbio-nextgen server allowing remote job execution.")
parser.add_argument("-c", "--config", help=("Global YAML configuration file specifying system details."
... | 0.008168 |
def add_output_file(self, filename):
"""
Add filename as a output file for this DAG node.
@param filename: output filename to add
"""
if filename not in self.__output_files:
self.__output_files.append(filename)
if not isinstance(self.job(), CondorDAGManJob):
if self.job().get_un... | 0.010499 |
def removeComponent(self, row,col):
"""Removes the component at the given location
:param row: track location of existing component to remove
:type row: int
:param col: location in track of existing component to remove
:type col: int
"""
self._segments[row].pop(c... | 0.005291 |
def estimate_clock_model(params):
"""
implementing treetime clock
"""
if assure_tree(params, tmp_dir='clock_model_tmp'):
return 1
dates = utils.parse_dates(params.dates)
if len(dates)==0:
return 1
outdir = get_outdir(params, '_clock')
##################################... | 0.006222 |
def QA_fetch_get_hkindex_list(ip=None, port=None):
"""[summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
# 港股 HKMARKET
27 5 香港指数 FH
31 2 香港主板 KH
48 2... | 0.001541 |
def invert(m):
"""
Generate the inverse of a 3x3 matrix.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/invert_c.html
:param m: Matrix to be inverted.
:type m: 3x3-Element Array of floats
:return: Inverted matrix (m1)^-1
:rtype: 3x3-Element Array of floats
"""
m = stypes.t... | 0.002252 |
def chi2_adaptive_binning(features_0,features_1,number_of_splits_list,systematics_fraction=0.0,title = "title", name="name", PLOT = True, DEBUG = False, transform='StandardScalar'):
"""This function takes in two 2D arrays with all features being columns"""
max_number_of_splits = np.max(number_of_splits_list)
#deter... | 0.044957 |
def splits(cls, text_field, root='.data', train='wiki.train.tokens',
validation='wiki.valid.tokens', test='wiki.test.tokens',
**kwargs):
"""Create dataset objects for splits of the WikiText-2 dataset.
This is the most flexible way to use the dataset.
Arguments:
... | 0.004452 |
def CreatePrecisionHelper(cls, precision):
"""Creates a precision helper.
Args:
precision (str): precision of the date and time value, which should
be one of the PRECISION_VALUES in definitions.
Returns:
class: date time precision helper class.
Raises:
ValueError: if the p... | 0.003484 |
def get_trace_entity(self):
"""
Return the current trace entity(segment/subsegment). If there is none,
it behaves based on pre-defined ``context_missing`` strategy.
"""
if not getattr(self._local, 'entities', None):
return self.handle_context_missing()
return... | 0.005797 |
def get_db_prep_save(self, value, connection=None):
"""
Returns field's value prepared for saving into a database.
"""
## convert to settings.TIME_ZONE
if value is not None:
if value.tzinfo is None:
value = default_tz.localize(value)
else:
... | 0.008511 |
def update_credit_note_item(self, credit_note_item_id, credit_note_item_dict):
"""
Updates a credit note item
:param credit_note_item_id: the credit note item id
:param credit_note_item_dict: dict
:return: dict
"""
return self._create_put_request(
res... | 0.004515 |
def disk_free(path):
"""Return free bytes on partition holding `path`."""
stats = os.statvfs(path)
return stats.f_bavail * stats.f_frsize | 0.006711 |
def ballot_id(self):
"""
str: Ballot ID
"""
self._validate()
self._validate_division(self.division)
self._validate_for_ballot_id()
parts = []
parts.append(self.election_type)
if self.subtype:
parts.append(self.subtype)
if self.... | 0.003448 |
def _load(self):
"""
Load editable settings from the database and return them as a dict.
Delete any settings from the database that are no longer registered,
and emit a warning if there are settings that are defined in both
settings.py and the database.
"""
from y... | 0.001053 |
def get_one(self, criteria):
''' return one item
'''
try:
items = [item for item in self._get_with_criteria(criteria, limit=1)]
return items[0]
except:
return None | 0.017316 |
def get_log_by_name(log_group_name, log_stream_name, out_file=None,
verbose=True):
"""Download a log given the log's group and stream name.
Parameters
----------
log_group_name : str
The name of the log group, e.g. /aws/batch/job.
log_stream_name : str
The name ... | 0.000708 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.