text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def get_gicon(self, icon_id: str) -> "Gio.Icon":
"""Lookup Gio.Icon from udiskie-internal id."""
return Gio.ThemedIcon.new_from_names(self._icon_names[icon_id]) | [
"def",
"get_gicon",
"(",
"self",
",",
"icon_id",
":",
"str",
")",
"->",
"\"Gio.Icon\"",
":",
"return",
"Gio",
".",
"ThemedIcon",
".",
"new_from_names",
"(",
"self",
".",
"_icon_names",
"[",
"icon_id",
"]",
")"
] | 58 | 13 |
def execute(self, driver_command, params=None):
"""
Sends a command to be executed by a command.CommandExecutor.
:Args:
- driver_command: The name of the command to execute as a string.
- params: A dictionary of named parameters to send with the command.
:Returns:
... | [
"def",
"execute",
"(",
"self",
",",
"driver_command",
",",
"params",
"=",
"None",
")",
":",
"if",
"self",
".",
"session_id",
"is",
"not",
"None",
":",
"if",
"not",
"params",
":",
"params",
"=",
"{",
"'sessionId'",
":",
"self",
".",
"session_id",
"}",
... | 39.962963 | 19.740741 |
def ReadUserNotifications(self,
username,
state=None,
timerange=None,
cursor=None):
"""Reads notifications scheduled for a user within a given timerange."""
query = ("SELECT UNIX_TIMESTAMP(timestamp)... | [
"def",
"ReadUserNotifications",
"(",
"self",
",",
"username",
",",
"state",
"=",
"None",
",",
"timerange",
"=",
"None",
",",
"cursor",
"=",
"None",
")",
":",
"query",
"=",
"(",
"\"SELECT UNIX_TIMESTAMP(timestamp), \"",
"\" notification_state, notification \"",
... | 33.375 | 19.325 |
def _check_file_syntax(filename, temp_dir, override_lang=None, enforce=True):
"""
Checks that the code in FILENAME parses, attempting to autodetect
the language if necessary.
Raises IOError if the file cannot be read.
Raises DXSyntaxError if there is a problem and "enforce" is True.
"""
de... | [
"def",
"_check_file_syntax",
"(",
"filename",
",",
"temp_dir",
",",
"override_lang",
"=",
"None",
",",
"enforce",
"=",
"True",
")",
":",
"def",
"check_python",
"(",
"filename",
")",
":",
"# Generate a semi-recognizable name to write the pyc to. Of",
"# course it's possi... | 38.557377 | 20.721311 |
def plotProgenitor(self,d1='x',d2='z',*args,**kwargs):
"""
NAME:
plotProgenitor
PURPOSE:
plot the progenitor orbit
INPUT:
d1= plot this on the X axis ('x','y','z','R','phi','vx','vy','vz','vR','vt','ll','bb','dist','pmll','pmbb','vlos')
d... | [
"def",
"plotProgenitor",
"(",
"self",
",",
"d1",
"=",
"'x'",
",",
"d2",
"=",
"'z'",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"tts",
"=",
"self",
".",
"_progenitor",
".",
"_orb",
".",
"t",
"[",
"self",
".",
"_progenitor",
".",
"_orb",
... | 30.976744 | 25.348837 |
def build_data_access(host, port, database_name, collection_name):
"""
Create data access gateway.
:param host: The database server to connect to.
:type host: str
:param port: Database port.
:type port: int
:param database_name: Database name.
:type datab... | [
"def",
"build_data_access",
"(",
"host",
",",
"port",
",",
"database_name",
",",
"collection_name",
")",
":",
"return",
"PyMongoDataAccess",
"(",
"\"mongodb://%s:%d\"",
"%",
"(",
"host",
",",
"port",
")",
",",
"database_name",
",",
"collection_name",
")"
] | 38.066667 | 15 |
def get_user_roles(self, user):
"""Get roles associated with the given user.
Args:
user (string): User name.
Returns:
(list): List of roles that user has.
Raises:
requests.HTTPError on failure.
"""
return self.service.get_user_roles(... | [
"def",
"get_user_roles",
"(",
"self",
",",
"user",
")",
":",
"return",
"self",
".",
"service",
".",
"get_user_roles",
"(",
"user",
",",
"self",
".",
"url_prefix",
",",
"self",
".",
"auth",
",",
"self",
".",
"session",
",",
"self",
".",
"session_send_opts... | 27.928571 | 18.857143 |
def get_trainer(self, id_, respect_privacy=True, detail=True):
"""Returns the Trainer object for the ID"""
parameters = {}
if respect_privacy is False:
parameters['statistics'] = 'force'
if detail is False:
parameters['detail'] = 'low'
r = requests.get(api_url+'trainers/'+str(id_)+'/', headers=se... | [
"def",
"get_trainer",
"(",
"self",
",",
"id_",
",",
"respect_privacy",
"=",
"True",
",",
"detail",
"=",
"True",
")",
":",
"parameters",
"=",
"{",
"}",
"if",
"respect_privacy",
"is",
"False",
":",
"parameters",
"[",
"'statistics'",
"]",
"=",
"'force'",
"i... | 39.692308 | 27.769231 |
def new_linsolver(name,prop):
"""
Creates a linear solver.
Parameters
----------
name : string
prop : string
Returns
-------
solver : :class:`LinSolver <optalg.lin_solver.LinSolver>`
"""
if name == 'mumps':
return LinSolverMUMPS(prop)
elif name == 'supe... | [
"def",
"new_linsolver",
"(",
"name",
",",
"prop",
")",
":",
"if",
"name",
"==",
"'mumps'",
":",
"return",
"LinSolverMUMPS",
"(",
"prop",
")",
"elif",
"name",
"==",
"'superlu'",
":",
"return",
"LinSolverSUPERLU",
"(",
"prop",
")",
"elif",
"name",
"==",
"'... | 23.888889 | 18.185185 |
def write(self, buf):
"""Write bytes to the stream."""
underflow = self._audio_stream.write(buf)
if underflow:
logging.warning('SoundDeviceStream write underflow (size: %d)',
len(buf))
return len(buf) | [
"def",
"write",
"(",
"self",
",",
"buf",
")",
":",
"underflow",
"=",
"self",
".",
"_audio_stream",
".",
"write",
"(",
"buf",
")",
"if",
"underflow",
":",
"logging",
".",
"warning",
"(",
"'SoundDeviceStream write underflow (size: %d)'",
",",
"len",
"(",
"buf"... | 38 | 14.571429 |
def time_col_laminar(EnergyDis, Temp, ConcAl, ConcClay, coag, material,
DiamTarget, DiamTube, DIM_FRACTAL, RatioHeightDiameter):
"""Calculate single collision time for laminar flow mediated collisions.
Calculated as a function of floc size.
"""
return (((1/6) * ((6/np.pi)**(1/3))
... | [
"def",
"time_col_laminar",
"(",
"EnergyDis",
",",
"Temp",
",",
"ConcAl",
",",
"ConcClay",
",",
"coag",
",",
"material",
",",
"DiamTarget",
",",
"DiamTube",
",",
"DIM_FRACTAL",
",",
"RatioHeightDiameter",
")",
":",
"return",
"(",
"(",
"(",
"1",
"/",
"6",
... | 50 | 19.133333 |
def list_dcm_datain(datain):
''' List all DICOM file paths in the datain dictionary of input data.
'''
if not isinstance(datain, dict):
raise ValueError('The input is not a dictionary!')
dcmlst = []
# list of mu-map DICOM files
if 'mumapDCM' in datain:
dcmump = os.listdir(datai... | [
"def",
"list_dcm_datain",
"(",
"datain",
")",
":",
"if",
"not",
"isinstance",
"(",
"datain",
",",
"dict",
")",
":",
"raise",
"ValueError",
"(",
"'The input is not a dictionary!'",
")",
"dcmlst",
"=",
"[",
"]",
"# list of mu-map DICOM files",
"if",
"'mumapDCM'",
... | 30.555556 | 21.037037 |
def __verify_minion_publish(self, clear_load):
'''
Verify that the passed information authorized a minion to execute
:param dict clear_load: A publication load from a minion
:rtype: bool
:return: A boolean indicating if the minion is allowed to publish the command in the load
... | [
"def",
"__verify_minion_publish",
"(",
"self",
",",
"clear_load",
")",
":",
"# Verify that the load is valid",
"if",
"'peer'",
"not",
"in",
"self",
".",
"opts",
":",
"return",
"False",
"if",
"not",
"isinstance",
"(",
"self",
".",
"opts",
"[",
"'peer'",
"]",
... | 39.882353 | 17.372549 |
def execute_from_command_line(argv=None):
"""
Currently the only entrypoint (manage.py, demosys-admin)
"""
if not argv:
argv = sys.argv
# prog_name = argv[0]
system_commands = find_commands(system_command_dir())
project_commands = find_commands(project_command_dir())
project_pa... | [
"def",
"execute_from_command_line",
"(",
"argv",
"=",
"None",
")",
":",
"if",
"not",
"argv",
":",
"argv",
"=",
"sys",
".",
"argv",
"# prog_name = argv[0]",
"system_commands",
"=",
"find_commands",
"(",
"system_command_dir",
"(",
")",
")",
"project_commands",
"="... | 30.785714 | 13.928571 |
def _wrap_jinja_filter(self, function):
"""Propagate exceptions as undefined values filter."""
def wrapper(*args, **kwargs):
"""Filter wrapper."""
try:
return function(*args, **kwargs)
except Exception: # pylint: disable=broad-except
r... | [
"def",
"_wrap_jinja_filter",
"(",
"self",
",",
"function",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Filter wrapper.\"\"\"",
"try",
":",
"return",
"function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
... | 37.933333 | 13.866667 |
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
ex... | [
"def",
"_read_conf_file",
"(",
"path",
")",
":",
"log",
".",
"debug",
"(",
"'Reading configuration from %s'",
",",
"path",
")",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"path",
",",
"'r'",
")",
"as",
"conf_file",
":",
"try",
":",
... | 46 | 24.428571 |
def execute(helper, config, args):
"""
Lists environments
"""
versions = helper.get_versions()
out("Deployed versions:")
for version in versions:
out(version) | [
"def",
"execute",
"(",
"helper",
",",
"config",
",",
"args",
")",
":",
"versions",
"=",
"helper",
".",
"get_versions",
"(",
")",
"out",
"(",
"\"Deployed versions:\"",
")",
"for",
"version",
"in",
"versions",
":",
"out",
"(",
"version",
")"
] | 22.875 | 8.875 |
def _get_appoptics(options):
'''
Return an appoptics connection object.
'''
conn = appoptics_metrics.connect(
options.get('api_token'),
sanitizer=appoptics_metrics.sanitize_metric_name,
hostname=options.get('api_url'))
log.info("Connected to appoptics.")
return conn | [
"def",
"_get_appoptics",
"(",
"options",
")",
":",
"conn",
"=",
"appoptics_metrics",
".",
"connect",
"(",
"options",
".",
"get",
"(",
"'api_token'",
")",
",",
"sanitizer",
"=",
"appoptics_metrics",
".",
"sanitize_metric_name",
",",
"hostname",
"=",
"options",
... | 30.5 | 13.3 |
def connect(self, dest_pair):
"""
Connects to the specified destination through a proxy.
Uses the same API as socket's connect().
To select the proxy server, use set_proxy().
dest_pair - 2-tuple of (IP/hostname, port).
"""
if len(dest_pair) != 2 or dest_pair[0].s... | [
"def",
"connect",
"(",
"self",
",",
"dest_pair",
")",
":",
"if",
"len",
"(",
"dest_pair",
")",
"!=",
"2",
"or",
"dest_pair",
"[",
"0",
"]",
".",
"startswith",
"(",
"\"[\"",
")",
":",
"# Probably IPv6, not supported -- raise an error, and hope",
"# Happy Eyeballs... | 38.634146 | 20.073171 |
def trajectory(self, ini, end, delta, mass_coo, age_in_sec=False,
online=False):
"""
create a trajectory out of a stellar model
Parameters
----------
ini : integer
Initial model, inital cycle number.
end : integer
Final model, f... | [
"def",
"trajectory",
"(",
"self",
",",
"ini",
",",
"end",
",",
"delta",
",",
"mass_coo",
",",
"age_in_sec",
"=",
"False",
",",
"online",
"=",
"False",
")",
":",
"filename",
"=",
"'traj_'",
"+",
"str",
"(",
"mass_coo",
")",
"+",
"'.dat'",
"f",
"=",
... | 36.891304 | 19.391304 |
def process_features_online(self, corpus, input_features, output_path, chunk_size=1):
"""
Process all features of the given corpus and save the processed features in a feature-container.
The features are processed in **online** mode, chunk by chunk.
Args:
corpus (Corpus): Th... | [
"def",
"process_features_online",
"(",
"self",
",",
"corpus",
",",
"input_features",
",",
"output_path",
",",
"chunk_size",
"=",
"1",
")",
":",
"feat_container",
"=",
"containers",
".",
"FeatureContainer",
"(",
"output_path",
")",
"feat_container",
".",
"open",
... | 40.680851 | 28.510638 |
def make_cookie(name, load, seed, expire=0, domain="", path="",
timestamp=""):
"""
Create and return a cookie
:param name: Cookie name
:param load: Cookie load
:param seed: A seed for the HMAC function
:param expire: Number of minutes before this cookie goes stale
:param dom... | [
"def",
"make_cookie",
"(",
"name",
",",
"load",
",",
"seed",
",",
"expire",
"=",
"0",
",",
"domain",
"=",
"\"\"",
",",
"path",
"=",
"\"\"",
",",
"timestamp",
"=",
"\"\"",
")",
":",
"cookie",
"=",
"SimpleCookie",
"(",
")",
"if",
"not",
"timestamp",
... | 35.148148 | 15.518519 |
def i2b(self, pkt, x):
"""Convert internal value to internal value"""
if type(x) is str:
x = bytes([ ord(i) for i in x ])
return x | [
"def",
"i2b",
"(",
"self",
",",
"pkt",
",",
"x",
")",
":",
"if",
"type",
"(",
"x",
")",
"is",
"str",
":",
"x",
"=",
"bytes",
"(",
"[",
"ord",
"(",
"i",
")",
"for",
"i",
"in",
"x",
"]",
")",
"return",
"x"
] | 32 | 11.6 |
def submit_statistics(self):
"""
Upload the database to the FTP server. Only submit new information contained in the partial database.
Merge the partial database back into master after a successful upload.
"""
if not self._hq.get('api_key', False) or not self._enabled:
... | [
"def",
"submit_statistics",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_hq",
".",
"get",
"(",
"'api_key'",
",",
"False",
")",
"or",
"not",
"self",
".",
"_enabled",
":",
"return",
"for",
"r",
"in",
"(",
"'uuid'",
",",
"'application_name'",
",",
... | 43.623188 | 21.623188 |
def run(self, args):
"""Parse command line arguments, and run rflint"""
self.args = self.parse_and_process_args(args)
if self.args.version:
print(__version__)
return 0
if self.args.rulefile:
for filename in self.args.rulefile:
... | [
"def",
"run",
"(",
"self",
",",
"args",
")",
":",
"self",
".",
"args",
"=",
"self",
".",
"parse_and_process_args",
"(",
"args",
")",
"if",
"self",
".",
"args",
".",
"version",
":",
"print",
"(",
"__version__",
")",
"return",
"0",
"if",
"self",
".",
... | 29.444444 | 19.222222 |
def view_component_planes(self, dimensions=None, figsize=None,
colormap=cm.Spectral_r, colorbar=False,
bestmatches=False, bestmatchcolors=None,
labels=None, zoom=None, filename=None):
"""Observe the component planes in the... | [
"def",
"view_component_planes",
"(",
"self",
",",
"dimensions",
"=",
"None",
",",
"figsize",
"=",
"None",
",",
"colormap",
"=",
"cm",
".",
"Spectral_r",
",",
"colorbar",
"=",
"False",
",",
"bestmatches",
"=",
"False",
",",
"bestmatchcolors",
"=",
"None",
"... | 53.906977 | 21.255814 |
def get(self, identity):
"""
Constructs a EntityContext
:param identity: Unique identity of the Entity
:returns: twilio.rest.authy.v1.service.entity.EntityContext
:rtype: twilio.rest.authy.v1.service.entity.EntityContext
"""
return EntityContext(self._version, s... | [
"def",
"get",
"(",
"self",
",",
"identity",
")",
":",
"return",
"EntityContext",
"(",
"self",
".",
"_version",
",",
"service_sid",
"=",
"self",
".",
"_solution",
"[",
"'service_sid'",
"]",
",",
"identity",
"=",
"identity",
",",
")"
] | 37.3 | 23.5 |
def switch_client(self):
"""
Switch client to this session.
Raises
------
:exc:`exc.LibTmuxException`
"""
proc = self.cmd('switch-client', '-t%s' % self.id)
if proc.stderr:
raise exc.LibTmuxException(proc.stderr) | [
"def",
"switch_client",
"(",
"self",
")",
":",
"proc",
"=",
"self",
".",
"cmd",
"(",
"'switch-client'",
",",
"'-t%s'",
"%",
"self",
".",
"id",
")",
"if",
"proc",
".",
"stderr",
":",
"raise",
"exc",
".",
"LibTmuxException",
"(",
"proc",
".",
"stderr",
... | 21.461538 | 18.538462 |
def new_image_like(self, data):
"""
Create a new ANTsImage with the same header information, but with
a new image array.
Arguments
---------
data : ndarray or py::capsule
New array or pointer for the image.
It must have the same shape as the cur... | [
"def",
"new_image_like",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"np",
".",
"ndarray",
")",
":",
"raise",
"ValueError",
"(",
"'data must be a numpy array'",
")",
"if",
"not",
"self",
".",
"has_components",
":",
"if"... | 38.928571 | 23.428571 |
def validate_data_privacy(request, data, wrapper_kw=None):
""" Validate :data: contains only data allowed by privacy settings.
:param request: Pyramid Request instance
:param data: Dict containing request/response data which should be
validated
"""
from nefertari import wrappers
if wrap... | [
"def",
"validate_data_privacy",
"(",
"request",
",",
"data",
",",
"wrapper_kw",
"=",
"None",
")",
":",
"from",
"nefertari",
"import",
"wrappers",
"if",
"wrapper_kw",
"is",
"None",
":",
"wrapper_kw",
"=",
"{",
"}",
"wrapper",
"=",
"wrappers",
".",
"apply_priv... | 34.947368 | 18.736842 |
def get(self, name=None):
"""
Gets a list of all recipes, which are registered by the current plugin.
If a name is provided, only the requested recipe is returned or None.
:param: name: Name of the recipe
"""
return self.__app.recipes.get(name, self._plugin) | [
"def",
"get",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"return",
"self",
".",
"__app",
".",
"recipes",
".",
"get",
"(",
"name",
",",
"self",
".",
"_plugin",
")"
] | 37.5 | 18.5 |
def squad(R_in, t_in, t_out):
"""Spherical "quadrangular" interpolation of rotors with a cubic spline
This is the best way to interpolate rotations. It uses the analog
of a cubic spline, except that the interpolant is confined to the
rotor manifold in a natural way. Alternative methods involving
... | [
"def",
"squad",
"(",
"R_in",
",",
"t_in",
",",
"t_out",
")",
":",
"if",
"R_in",
".",
"size",
"==",
"0",
"or",
"t_out",
".",
"size",
"==",
"0",
":",
"return",
"np",
".",
"array",
"(",
"(",
")",
",",
"dtype",
"=",
"np",
".",
"quaternion",
")",
... | 55.760684 | 29.863248 |
def get_objective_banks(self):
"""Pass through to provider ObjectiveBankLookupSession.get_objective_banks"""
# Implemented from kitosid template for -
# osid.resource.BinLookupSession.get_bins_template
catalogs = self._get_provider_session('objective_bank_lookup_session').get_objective_b... | [
"def",
"get_objective_banks",
"(",
"self",
")",
":",
"# Implemented from kitosid template for -",
"# osid.resource.BinLookupSession.get_bins_template",
"catalogs",
"=",
"self",
".",
"_get_provider_session",
"(",
"'objective_bank_lookup_session'",
")",
".",
"get_objective_banks",
... | 56.888889 | 21 |
def _createBitpattern(functioncode, value):
"""Create the bit pattern that is used for writing single bits.
This is basically a storage of numerical constants.
Args:
* functioncode (int): can be 5 or 15
* value (int): can be 0 or 1
Returns:
The bit pattern (string).
Raise... | [
"def",
"_createBitpattern",
"(",
"functioncode",
",",
"value",
")",
":",
"_checkFunctioncode",
"(",
"functioncode",
",",
"[",
"5",
",",
"15",
"]",
")",
"_checkInt",
"(",
"value",
",",
"minvalue",
"=",
"0",
",",
"maxvalue",
"=",
"1",
",",
"description",
"... | 23.066667 | 20.533333 |
def load_recipe(self):
'''load will return a loaded in singularity recipe. The idea
is that these sections can then be parsed into a Dockerfile,
or printed back into their original form.
Returns
=======
config: a parsed recipe Singularity recipe
''... | [
"def",
"load_recipe",
"(",
"self",
")",
":",
"# Comments between sections, add to top of file",
"lines",
"=",
"self",
".",
"lines",
".",
"copy",
"(",
")",
"comments",
"=",
"[",
"]",
"# Start with a fresh config!",
"self",
".",
"config",
"=",
"dict",
"(",
")",
... | 29.960784 | 19.764706 |
def p_function_call(p):
"""
FunctionCall : FuncQName FormalArguments
"""
# FIXME: This production also matches NodeType() or
# processing-instruction("foo"), which are technically NodeTest
qname = p[1]
p[0] = ast.FunctionCall(qname[0], qname[1], p[2]) | [
"def",
"p_function_call",
"(",
"p",
")",
":",
"# FIXME: This production also matches NodeType() or",
"# processing-instruction(\"foo\"), which are technically NodeTest",
"qname",
"=",
"p",
"[",
"1",
"]",
"p",
"[",
"0",
"]",
"=",
"ast",
".",
"FunctionCall",
"(",
"qname",... | 34 | 12.5 |
def get_required_columns(self):
"""Lists names of columns that have required fields."""
required_columns = []
if self.formset_class:
empty_form = self.get_formset().empty_form
for column in self.columns.values():
field = empty_form.fields.get(column.name)
... | [
"def",
"get_required_columns",
"(",
"self",
")",
":",
"required_columns",
"=",
"[",
"]",
"if",
"self",
".",
"formset_class",
":",
"empty_form",
"=",
"self",
".",
"get_formset",
"(",
")",
".",
"empty_form",
"for",
"column",
"in",
"self",
".",
"columns",
"."... | 44.4 | 9.9 |
def clear_xcom_data(self, session=None):
"""
Clears all XCom data from the database for the task instance
"""
session.query(XCom).filter(
XCom.dag_id == self.dag_id,
XCom.task_id == self.task_id,
XCom.execution_date == self.execution_date
).del... | [
"def",
"clear_xcom_data",
"(",
"self",
",",
"session",
"=",
"None",
")",
":",
"session",
".",
"query",
"(",
"XCom",
")",
".",
"filter",
"(",
"XCom",
".",
"dag_id",
"==",
"self",
".",
"dag_id",
",",
"XCom",
".",
"task_id",
"==",
"self",
".",
"task_id"... | 34.1 | 8.7 |
def get_all_attributes(klass_or_instance):
"""Get all attribute members (attribute, property style method).
"""
pairs = list()
for attr, value in inspect.getmembers(
klass_or_instance, lambda x: not inspect.isroutine(x)):
if not (attr.startswith("__") or attr.endswith("__")):
... | [
"def",
"get_all_attributes",
"(",
"klass_or_instance",
")",
":",
"pairs",
"=",
"list",
"(",
")",
"for",
"attr",
",",
"value",
"in",
"inspect",
".",
"getmembers",
"(",
"klass_or_instance",
",",
"lambda",
"x",
":",
"not",
"inspect",
".",
"isroutine",
"(",
"x... | 40.111111 | 11.111111 |
def from_html(html, url=None, download_date=None):
"""
Extracts relevant information from an HTML page given as a string. This function does not invoke scrapy but only
uses the article extractor. If you have the original URL make sure to provide it as this helps NewsPlease
to extract the... | [
"def",
"from_html",
"(",
"html",
",",
"url",
"=",
"None",
",",
"download_date",
"=",
"None",
")",
":",
"extractor",
"=",
"article_extractor",
".",
"Extractor",
"(",
"[",
"'newspaper_extractor'",
",",
"'readability_extractor'",
",",
"'date_extractor'",
",",
"'lan... | 41.657143 | 21.828571 |
def identify_vcs(repo_url, guess=False, repo_aliases=REPO_ALIASES):
"""
Determines the type of repo that `repo_url` represents.
:param repo_url: Repo URL of unknown type.
:returns: VCS type (git, hg, etc) or raises UnknownVCS exception.
"""
repo_url = unicode(repo_url)
# Do basic alias chec... | [
"def",
"identify_vcs",
"(",
"repo_url",
",",
"guess",
"=",
"False",
",",
"repo_aliases",
"=",
"REPO_ALIASES",
")",
":",
"repo_url",
"=",
"unicode",
"(",
"repo_url",
")",
"# Do basic alias check",
"vcs",
"=",
"identify_vcs_vs_alias",
"(",
"repo_url",
",",
"guess"... | 29.458333 | 22.208333 |
def get_config(self):
"""
Load user configuration or return default when not found.
:rtype: :class:`Configuration`
"""
if not self._config:
namespace = {}
if os.path.exists(self.config_path):
execfile(self.config_path, namespace)
... | [
"def",
"get_config",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_config",
":",
"namespace",
"=",
"{",
"}",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"config_path",
")",
":",
"execfile",
"(",
"self",
".",
"config_path",
",",
"... | 30.538462 | 16.538462 |
def _add_page(self, text):
""" Helper function for PDFText, to have the document
add a page, and retry adding a large block of
text that would otherwise have been to long for the
page.
"""
save_cursor = self.parent.document.page.cursor.copy()
... | [
"def",
"_add_page",
"(",
"self",
",",
"text",
")",
":",
"save_cursor",
"=",
"self",
".",
"parent",
".",
"document",
".",
"page",
".",
"cursor",
".",
"copy",
"(",
")",
"save_cursor",
".",
"x_reset",
"(",
")",
"save_cursor",
".",
"y_reset",
"(",
")",
"... | 38.461538 | 13.384615 |
def participate(self, identity, experiment_name, variant):
"""
Set the variant for a specific user and mark a participation for the
experiment.
Participation will *only* be marked for visitors who have been verified
as humans (to avoid skewing reports with requests from bots and... | [
"def",
"participate",
"(",
"self",
",",
"identity",
",",
"experiment_name",
",",
"variant",
")",
":",
"self",
".",
"set_variant",
"(",
"identity",
",",
"experiment_name",
",",
"variant",
")",
"if",
"self",
".",
"is_verified_human",
"(",
"identity",
")",
":",... | 42.5 | 21.166667 |
def connect_to_region(region_name, **kw_params):
"""
Given a valid region name, return a
:class:`boto.sns.connection.SNSConnection`.
:type: str
:param region_name: The name of the region to connect to.
:rtype: :class:`boto.sns.connection.SNSConnection` or ``None``
:return: A connectio... | [
"def",
"connect_to_region",
"(",
"region_name",
",",
"*",
"*",
"kw_params",
")",
":",
"for",
"region",
"in",
"regions",
"(",
")",
":",
"if",
"region",
".",
"name",
"==",
"region_name",
":",
"return",
"region",
".",
"connect",
"(",
"*",
"*",
"kw_params",
... | 32.625 | 16.125 |
def aggregate(self, instance, owner):
"""Given an instance and a class, aggregate together some panglers.
Walks every class in the MRO of the `owner` class, including `owner`,
collecting panglers exposed as `self.attr_name`. The resulting pangler
will be bound to the provided `instance`... | [
"def",
"aggregate",
"(",
"self",
",",
"instance",
",",
"owner",
")",
":",
"try",
":",
"p",
"=",
"self",
".",
"pangler_factory",
".",
"from_store",
"(",
"instance",
",",
"self",
".",
"id",
")",
"except",
"KeyError",
":",
"pass",
"else",
":",
"return",
... | 32.916667 | 19 |
def get_field_type(info):
"""A field python type"""
type_ = info.get_type()
cls = get_field_class(type_)
field = cls(info, type_, None)
field.setup()
return field.py_type | [
"def",
"get_field_type",
"(",
"info",
")",
":",
"type_",
"=",
"info",
".",
"get_type",
"(",
")",
"cls",
"=",
"get_field_class",
"(",
"type_",
")",
"field",
"=",
"cls",
"(",
"info",
",",
"type_",
",",
"None",
")",
"field",
".",
"setup",
"(",
")",
"r... | 18.8 | 20.1 |
def twoslice(field, center=None, size=6.0, cmap='bone_r', vmin=0, vmax=1,
orientation='vertical', figpad=1.09, off=0.01):
"""
Plot two parts of the ortho view, the two sections given by ``orientation``.
"""
center = center or [i//2 for i in field.shape]
slices = []
for i,c in enumerate(c... | [
"def",
"twoslice",
"(",
"field",
",",
"center",
"=",
"None",
",",
"size",
"=",
"6.0",
",",
"cmap",
"=",
"'bone_r'",
",",
"vmin",
"=",
"0",
",",
"vmax",
"=",
"1",
",",
"orientation",
"=",
"'vertical'",
",",
"figpad",
"=",
"1.09",
",",
"off",
"=",
... | 30.666667 | 18.352941 |
def get_component(self, component_name):
"""
Looks up a component by its name.
Args:
component_name: The name of the component to look up.
Returns:
The component for the provided name or None if there is no such component.
"""
mapping = self.get_c... | [
"def",
"get_component",
"(",
"self",
",",
"component_name",
")",
":",
"mapping",
"=",
"self",
".",
"get_components",
"(",
")",
"return",
"mapping",
"[",
"component_name",
"]",
"if",
"component_name",
"in",
"mapping",
"else",
"None"
] | 36.272727 | 18.272727 |
def spawn_uwsgi(self, only=None):
"""Spawns uWSGI process(es) which will use configuration(s) from the module.
Returns list of tuples:
(configuration_alias, uwsgi_process_id)
If only one configuration found current process (uwsgiconf) is replaced with a new one (uWSGI),
oth... | [
"def",
"spawn_uwsgi",
"(",
"self",
",",
"only",
"=",
"None",
")",
":",
"spawned",
"=",
"[",
"]",
"configs",
"=",
"self",
".",
"configurations",
"if",
"len",
"(",
"configs",
")",
"==",
"1",
":",
"alias",
"=",
"configs",
"[",
"0",
"]",
".",
"alias",
... | 33.90625 | 23.625 |
def _spectral_norm(self):
""" spectral normalization """
w = self.params.get('weight').data(self.ctx)
w_mat = nd.reshape(w, [w.shape[0], -1])
_u = self.u.data(self.ctx)
_v = None
for _ in range(POWER_ITERATION):
_v = nd.L2Normalization(nd.dot(_u, w_mat))
... | [
"def",
"_spectral_norm",
"(",
"self",
")",
":",
"w",
"=",
"self",
".",
"params",
".",
"get",
"(",
"'weight'",
")",
".",
"data",
"(",
"self",
".",
"ctx",
")",
"w_mat",
"=",
"nd",
".",
"reshape",
"(",
"w",
",",
"[",
"w",
".",
"shape",
"[",
"0",
... | 27.2 | 18.2 |
def create_all(cls, list_of_kwargs):
"""Batch method for creating a list of instances
Args:
list_of_kwargs(list of dicts): hereA list of dicts where
each dict denotes the keyword args that you would pass
to the create method separately
Examples:
... | [
"def",
"create_all",
"(",
"cls",
",",
"list_of_kwargs",
")",
":",
"try",
":",
"return",
"cls",
".",
"add_all",
"(",
"[",
"cls",
".",
"new",
"(",
"*",
"*",
"kwargs",
")",
"if",
"kwargs",
"is",
"not",
"None",
"else",
"None",
"for",
"kwargs",
"in",
"l... | 34.8 | 22.15 |
def get_dom(self) -> str:
""" Retrieves the current value of the DOM for the step """
if self.is_running:
return self.dumps()
if self.dom is not None:
return self.dom
dom = self.dumps()
self.dom = dom
return dom | [
"def",
"get_dom",
"(",
"self",
")",
"->",
"str",
":",
"if",
"self",
".",
"is_running",
":",
"return",
"self",
".",
"dumps",
"(",
")",
"if",
"self",
".",
"dom",
"is",
"not",
"None",
":",
"return",
"self",
".",
"dom",
"dom",
"=",
"self",
".",
"dump... | 22.916667 | 19.333333 |
def redirect_stderr(self, enabled=True, log_level=logging.ERROR):
"""
Redirect sys.stderr to file-like object.
"""
if enabled:
if self.__stderr_wrapper:
self.__stderr_wrapper.update_log_level(log_level=log_level)
else:
self.__stderr... | [
"def",
"redirect_stderr",
"(",
"self",
",",
"enabled",
"=",
"True",
",",
"log_level",
"=",
"logging",
".",
"ERROR",
")",
":",
"if",
"enabled",
":",
"if",
"self",
".",
"__stderr_wrapper",
":",
"self",
".",
"__stderr_wrapper",
".",
"update_log_level",
"(",
"... | 36 | 18.875 |
def _get_multiparts(response):
"""
From this
'multipart/parallel; boundary="874e43d27ec6d83f30f37841bdaf90c7"; charset=utf-8'
get this
--874e43d27ec6d83f30f37841bdaf90c7
"""
boundary = None
for part in response.headers.get('Content-Type', '').split(';'):
... | [
"def",
"_get_multiparts",
"(",
"response",
")",
":",
"boundary",
"=",
"None",
"for",
"part",
"in",
"response",
".",
"headers",
".",
"get",
"(",
"'Content-Type'",
",",
"''",
")",
".",
"split",
"(",
"';'",
")",
":",
"if",
"'boundary='",
"in",
"part",
":"... | 33.714286 | 22.114286 |
def _pfp__add_child(self, name, child, stream=None, overwrite=False):
"""Add a child to the Struct field. If multiple consecutive fields are
added with the same name, an implicit array will be created to store
all fields of that name.
:param str name: The name of the child
:para... | [
"def",
"_pfp__add_child",
"(",
"self",
",",
"name",
",",
"child",
",",
"stream",
"=",
"None",
",",
"overwrite",
"=",
"False",
")",
":",
"if",
"not",
"overwrite",
"and",
"self",
".",
"_pfp__is_non_consecutive_duplicate",
"(",
"name",
",",
"child",
")",
":",... | 51.095238 | 20.095238 |
def layer(op):
'''Decorator for composable network layers.'''
def layer_decorated(self, *args, **kwargs):
# Automatically set a name if not provided.
name = kwargs.setdefault('name', self.get_unique_name(op.__name__))
# Figure out the layer inputs.
if len(self.terminals) == 0:
... | [
"def",
"layer",
"(",
"op",
")",
":",
"def",
"layer_decorated",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Automatically set a name if not provided.",
"name",
"=",
"kwargs",
".",
"setdefault",
"(",
"'name'",
",",
"self",
".",
"get_... | 38.391304 | 15.608696 |
def upload_file(self, local_path, remote_path):
"""
Upload a file from the local filesystem to the remote host
:type local_path: str
:param local_path: path of local file to upload
:type remote_path: str
:param remote_path: destination path of upload on remote host
... | [
"def",
"upload_file",
"(",
"self",
",",
"local_path",
",",
"remote_path",
")",
":",
"logger",
".",
"debug",
"(",
"\"{0}: uploading {1} to {0}:{2}\"",
".",
"format",
"(",
"self",
".",
"target_address",
",",
"local_path",
",",
"remote_path",
")",
")",
"try",
":"... | 45.526316 | 20.263158 |
def get_all_pipelines(app=''):
"""Get a list of all the Pipelines in _app_.
Args:
app (str): Name of Spinnaker Application.
Returns:
requests.models.Response: Response from Gate containing Pipelines.
"""
url = '{host}/applications/{app}/pipelineConfigs'.format(host=API_URL, app=ap... | [
"def",
"get_all_pipelines",
"(",
"app",
"=",
"''",
")",
":",
"url",
"=",
"'{host}/applications/{app}/pipelineConfigs'",
".",
"format",
"(",
"host",
"=",
"API_URL",
",",
"app",
"=",
"app",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"veri... | 29.368421 | 26.263158 |
def _normalize_hparams(hparams):
"""Normalize a dict keyed by `HParam`s and/or raw strings.
Args:
hparams: A `dict` whose keys are `HParam` objects and/or strings
representing hyperparameter names, and whose values are
hyperparameter values. No two keys may have the same name.
Returns:
A `di... | [
"def",
"_normalize_hparams",
"(",
"hparams",
")",
":",
"result",
"=",
"{",
"}",
"for",
"(",
"k",
",",
"v",
")",
"in",
"six",
".",
"iteritems",
"(",
"hparams",
")",
":",
"if",
"isinstance",
"(",
"k",
",",
"HParam",
")",
":",
"k",
"=",
"k",
".",
... | 31.083333 | 22.375 |
def reorder_nodes_before_add_or_move(self, pos, newpos, newdepth, target,
siblings, oldpath=None,
movebranch=False):
"""
Handles the reordering of nodes and branches when adding/moving
nodes.
:returns: A t... | [
"def",
"reorder_nodes_before_add_or_move",
"(",
"self",
",",
"pos",
",",
"newpos",
",",
"newdepth",
",",
"target",
",",
"siblings",
",",
"oldpath",
"=",
"None",
",",
"movebranch",
"=",
"False",
")",
":",
"if",
"(",
"(",
"pos",
"==",
"'last-sibling'",
")",
... | 44.539216 | 18.147059 |
def _get_base(server_certificate, **conn):
"""Fetch the base IAM Server Certificate."""
server_certificate['_version'] = 1
# Get the initial cert details:
cert_details = get_server_certificate_api(server_certificate['ServerCertificateName'], **conn)
if cert_details:
server_certificate.upda... | [
"def",
"_get_base",
"(",
"server_certificate",
",",
"*",
"*",
"conn",
")",
":",
"server_certificate",
"[",
"'_version'",
"]",
"=",
"1",
"# Get the initial cert details:",
"cert_details",
"=",
"get_server_certificate_api",
"(",
"server_certificate",
"[",
"'ServerCertific... | 47.411765 | 30.235294 |
def _getScalesDiag(self,termx=0):
"""
Internal function for parameter initialization
Uses 2 term single trait model to get covar params for initialization
Args:
termx: non-noise term terms that is used for initialization
"""
assert self.P>1, 'VarianceDec... | [
"def",
"_getScalesDiag",
"(",
"self",
",",
"termx",
"=",
"0",
")",
":",
"assert",
"self",
".",
"P",
">",
"1",
",",
"'VarianceDecomposition:: diagonal init_method allowed only for multi trait models'",
"assert",
"self",
".",
"noisPos",
"is",
"not",
"None",
",",
"'V... | 55.357143 | 27.642857 |
def set_centralized_assembled_values(self, a):
"""Set assembled matrix values on processor 0."""
if self.myid != 0:
return
assert a.size == self.id.nz
self._refs.update(a=a)
self.id.a = self.cast_array(a) | [
"def",
"set_centralized_assembled_values",
"(",
"self",
",",
"a",
")",
":",
"if",
"self",
".",
"myid",
"!=",
"0",
":",
"return",
"assert",
"a",
".",
"size",
"==",
"self",
".",
"id",
".",
"nz",
"self",
".",
"_refs",
".",
"update",
"(",
"a",
"=",
"a"... | 35.714286 | 8.428571 |
async def peers(self):
"""Returns the current Raft peer set
Returns:
Collection: addresses of peers
This endpoint retrieves the Raft peers for the datacenter in which
the agent is running. It returns a collection of addresses, such as::
[
"10.1.1... | [
"async",
"def",
"peers",
"(",
"self",
")",
":",
"response",
"=",
"await",
"self",
".",
"_api",
".",
"get",
"(",
"\"/v1/status/peers\"",
")",
"if",
"response",
".",
"status",
"==",
"200",
":",
"return",
"set",
"(",
"response",
".",
"body",
")"
] | 32.619048 | 21.142857 |
def update_group(self, group_id, group, force=False, minimal=True):
"""Update a group.
Applies writable settings in `group` to `group_id`
Note: this method can not be used to rename groups.
:param str group_id: target group ID
:param group: group settings
:type group: :... | [
"def",
"update_group",
"(",
"self",
",",
"group_id",
",",
"group",
",",
"force",
"=",
"False",
",",
"minimal",
"=",
"True",
")",
":",
"# Changes won't take if version is set - blank it for convenience",
"group",
".",
"version",
"=",
"None",
"params",
"=",
"{",
"... | 38.416667 | 21.625 |
def dump_model_data(request, app_label, model_label):
"""Exports data from a model.
"""
return dump_to_response(request, '%s.%s' % (app_label, model_label),
[], '-'.join((app_label, model_label))) | [
"def",
"dump_model_data",
"(",
"request",
",",
"app_label",
",",
"model_label",
")",
":",
"return",
"dump_to_response",
"(",
"request",
",",
"'%s.%s'",
"%",
"(",
"app_label",
",",
"model_label",
")",
",",
"[",
"]",
",",
"'-'",
".",
"join",
"(",
"(",
"app... | 46.4 | 14.4 |
def fit(self, X, y):
"""
Fit the model using X, y as training data.
Parameters
----------
X : {array-like, sparse matrix} of shape [n_samples, n_features]
Training vectors, where n_samples is the number of samples
and n_features is the number of features.... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
")",
":",
"rhl",
"=",
"self",
".",
"_create_random_layer",
"(",
")",
"self",
".",
"_genelm_regressor",
"=",
"GenELMRegressor",
"(",
"hidden_layer",
"=",
"rhl",
",",
"regressor",
"=",
"self",
".",
"regressor"... | 32.2 | 21 |
def remove_variable(self, variable, *, implied=True, verbose=True):
"""Remove variable from data.
Parameters
----------
variable : int or str
Variable index or name to remove.
implied : boolean (optional)
Toggle deletion of other variables that start with... | [
"def",
"remove_variable",
"(",
"self",
",",
"variable",
",",
"*",
",",
"implied",
"=",
"True",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"variable",
",",
"int",
")",
":",
"variable",
"=",
"self",
".",
"variable_names",
"[",
"varia... | 37.183673 | 14 |
def convert_mask_to_pil(mask, real=True):
"""Convert Mask to PIL Image."""
from PIL import Image
header = mask._layer._psd._record.header
channel_ids = [ci.id for ci in mask._layer._record.channel_info]
if real and mask._has_real():
width = mask._data.real_right - mask._data.real_left
... | [
"def",
"convert_mask_to_pil",
"(",
"mask",
",",
"real",
"=",
"True",
")",
":",
"from",
"PIL",
"import",
"Image",
"header",
"=",
"mask",
".",
"_layer",
".",
"_psd",
".",
"_record",
".",
"header",
"channel_ids",
"=",
"[",
"ci",
".",
"id",
"for",
"ci",
... | 43.578947 | 15.894737 |
def ilx_conv(graph, prefix, ilx_start):
""" convert a set of temporary identifiers to ilx and modify the graph in place """
to_sub = set()
for subject in graph.subjects(rdflib.RDF.type, rdflib.OWL.Class):
if PREFIXES[prefix] in subject:
to_sub.add(subject)
ilx_base = 'ilx_{:0>7}'
... | [
"def",
"ilx_conv",
"(",
"graph",
",",
"prefix",
",",
"ilx_start",
")",
":",
"to_sub",
"=",
"set",
"(",
")",
"for",
"subject",
"in",
"graph",
".",
"subjects",
"(",
"rdflib",
".",
"RDF",
".",
"type",
",",
"rdflib",
".",
"OWL",
".",
"Class",
")",
":",... | 35.34375 | 15.6875 |
def fso_makedirs(self, path, mode=None):
'overlays os.makedirs()'
path = self.abs(path)
cur = '/'
segments = path.split('/')
for idx, seg in enumerate(segments):
cur = os.path.join(cur, seg)
try:
st = self.fso_stat(cur)
except OSError:
st = None
if st is None:... | [
"def",
"fso_makedirs",
"(",
"self",
",",
"path",
",",
"mode",
"=",
"None",
")",
":",
"path",
"=",
"self",
".",
"abs",
"(",
"path",
")",
"cur",
"=",
"'/'",
"segments",
"=",
"path",
".",
"split",
"(",
"'/'",
")",
"for",
"idx",
",",
"seg",
"in",
"... | 28.888889 | 12.888889 |
def sanitize_tx_data(unspents, outputs, fee, leftover, combine=True,
message=None, compressed=True, absolute_fee=False,
min_change=0, version='main'):
"""
sanitize_tx_data()
fee is in satoshis per byte.
"""
outputs = outputs.copy()
for i, output in en... | [
"def",
"sanitize_tx_data",
"(",
"unspents",
",",
"outputs",
",",
"fee",
",",
"leftover",
",",
"combine",
"=",
"True",
",",
"message",
"=",
"None",
",",
"compressed",
"=",
"True",
",",
"absolute_fee",
"=",
"False",
",",
"min_change",
"=",
"0",
",",
"versi... | 34.314815 | 23.314815 |
def _get_bmdl_ratio(self, models):
"""Return BMDL ratio in list of models."""
bmdls = [model.output["BMDL"] for model in models if model.output["BMDL"] > 0]
return max(bmdls) / min(bmdls) if len(bmdls) > 0 else 0 | [
"def",
"_get_bmdl_ratio",
"(",
"self",
",",
"models",
")",
":",
"bmdls",
"=",
"[",
"model",
".",
"output",
"[",
"\"BMDL\"",
"]",
"for",
"model",
"in",
"models",
"if",
"model",
".",
"output",
"[",
"\"BMDL\"",
"]",
">",
"0",
"]",
"return",
"max",
"(",
... | 46.6 | 23 |
def _convertEntities(self, match):
"""Used in a call to re.sub to replace HTML, XML, and numeric
entities with the appropriate Unicode characters. If HTML
entities are being converted, any unrecognized entities are
escaped."""
x = match.group(1)
if self.convertHTMLEntitie... | [
"def",
"_convertEntities",
"(",
"self",
",",
"match",
")",
":",
"x",
"=",
"match",
".",
"group",
"(",
"1",
")",
"if",
"self",
".",
"convertHTMLEntities",
"and",
"x",
"in",
"name2codepoint",
":",
"return",
"unichr",
"(",
"name2codepoint",
"[",
"x",
"]",
... | 38.791667 | 11.708333 |
def spec(self):
"""Return a SourceSpec to describe this source"""
from ambry_sources.sources import SourceSpec
d = self.dict
d['url'] = self.url
# Will get the URL twice; once as ref and once as URL, but the ref is ignored
return SourceSpec(**d) | [
"def",
"spec",
"(",
"self",
")",
":",
"from",
"ambry_sources",
".",
"sources",
"import",
"SourceSpec",
"d",
"=",
"self",
".",
"dict",
"d",
"[",
"'url'",
"]",
"=",
"self",
".",
"url",
"# Will get the URL twice; once as ref and once as URL, but the ref is ignored",
... | 28.7 | 24.4 |
def _extended_gcd(self, a, b):
"""
Extended Euclidean algorithms to solve Bezout's identity:
a*x + b*y = gcd(x, y)
Finds one particular solution for x, y: s, t
Returns: gcd, s, t
"""
s, old_s = 0, 1
t, old_t = 1, 0
r, old_r = b, a
while ... | [
"def",
"_extended_gcd",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"s",
",",
"old_s",
"=",
"0",
",",
"1",
"t",
",",
"old_t",
"=",
"1",
",",
"0",
"r",
",",
"old_r",
"=",
"b",
",",
"a",
"while",
"r",
":",
"quotient",
"=",
"old_r",
"//",
"r",
... | 32.3125 | 10.9375 |
async def connect(self, timeout=None):
"""
Connects to the Lavalink player event websocket.
Parameters
----------
timeout : int
Time after which to timeout on attempting to connect to the Lavalink websocket,
``None`` is considered never, but the underlyin... | [
"async",
"def",
"connect",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"self",
".",
"_is_shutdown",
"=",
"False",
"combo_uri",
"=",
"\"ws://{}:{}\"",
".",
"format",
"(",
"self",
".",
"host",
",",
"self",
".",
"rest",
")",
"uri",
"=",
"\"ws://{}... | 32.880952 | 24.642857 |
def apply_link_ref(offset: int, length: int, value: bytes, bytecode: bytes) -> bytes:
"""
Returns the new bytecode with `value` put into the location indicated by `offset` and `length`.
"""
try:
validate_empty_bytes(offset, length, bytecode)
except ValidationError:
raise BytecodeLink... | [
"def",
"apply_link_ref",
"(",
"offset",
":",
"int",
",",
"length",
":",
"int",
",",
"value",
":",
"bytes",
",",
"bytecode",
":",
"bytes",
")",
"->",
"bytes",
":",
"try",
":",
"validate_empty_bytes",
"(",
"offset",
",",
"length",
",",
"bytecode",
")",
"... | 35.6875 | 25.1875 |
def get_document(
self,
name,
mask=None,
transaction=None,
read_time=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Gets a single document.
Example:
... | [
"def",
"get_document",
"(",
"self",
",",
"name",
",",
"mask",
"=",
"None",
",",
"transaction",
"=",
"None",
",",
"read_time",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"="... | 43.225806 | 26.989247 |
def reset(self, force):
"""Connect to the assigned bucket or create if needed. Clear all the blobs inside."""
client = self.create_client()
bucket = client.lookup_bucket(self.bucket_name)
if bucket is not None:
if not force:
self._log.error("Bucket already exi... | [
"def",
"reset",
"(",
"self",
",",
"force",
")",
":",
"client",
"=",
"self",
".",
"create_client",
"(",
")",
"bucket",
"=",
"client",
".",
"lookup_bucket",
"(",
"self",
".",
"bucket_name",
")",
"if",
"bucket",
"is",
"not",
"None",
":",
"if",
"not",
"f... | 47.071429 | 13.571429 |
def remove_non_ascii(input_string):
"""Remove non-ascii characters
Source: http://stackoverflow.com/a/1342373
"""
no_ascii = "".join(i for i in input_string if ord(i) < 128)
return no_ascii | [
"def",
"remove_non_ascii",
"(",
"input_string",
")",
":",
"no_ascii",
"=",
"\"\"",
".",
"join",
"(",
"i",
"for",
"i",
"in",
"input_string",
"if",
"ord",
"(",
"i",
")",
"<",
"128",
")",
"return",
"no_ascii"
] | 34 | 9.166667 |
def remove(self, layers):
""" Remove one or more layers from the stack of masking layers.
Args:
layers: An int, string or list of strings and/or ints. Ints are
interpreted as indices in the stack to remove; strings are
interpreted as names of layers to remove.... | [
"def",
"remove",
"(",
"self",
",",
"layers",
")",
":",
"if",
"not",
"isinstance",
"(",
"layers",
",",
"list",
")",
":",
"layers",
"=",
"[",
"layers",
"]",
"for",
"l",
"in",
"layers",
":",
"if",
"isinstance",
"(",
"l",
",",
"string_types",
")",
":",... | 41.761905 | 17.47619 |
def simplify_dicts( index, shared, simplify_dicts=SIMPLIFY_DICTS, always_compress=ALWAYS_COMPRESS_DICTS ):
"""Eliminate "noise" dictionary records from the index
index -- overall index of objects (including metadata such as type records)
shared -- parent-count mapping for records in index
mod... | [
"def",
"simplify_dicts",
"(",
"index",
",",
"shared",
",",
"simplify_dicts",
"=",
"SIMPLIFY_DICTS",
",",
"always_compress",
"=",
"ALWAYS_COMPRESS_DICTS",
")",
":",
"# things which will have their dictionaries compressed out",
"to_delete",
"=",
"set",
"(",
")",
"for",
"t... | 44.631579 | 19.298246 |
def is_unused(input, model_file=None, model_proto=None, name=None):
"""Returns true if input id is unused piece.
Args:
input: An arbitrary tensor of int32.
model_file: The sentencepiece model file path.
model_proto: The sentencepiece model serialized proto.
Either `model_file` or `mode... | [
"def",
"is_unused",
"(",
"input",
",",
"model_file",
"=",
"None",
",",
"model_proto",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"return",
"_gen_sentencepiece_processor_op",
".",
"sentencepiece_get_piece_type",
"(",
"input",
",",
"model_file",
"=",
"model_... | 38.8125 | 21.125 |
def prep_search_string(cls, search_string, match_substrings):
"""Prepares search string as a proper whoosh search string.
:param search_string: The search string which should be prepared.
:param match_substrings: ``True`` if you want to match substrings,
``False... | [
"def",
"prep_search_string",
"(",
"cls",
",",
"search_string",
",",
"match_substrings",
")",
":",
"if",
"sys",
".",
"version",
"<",
"'3'",
"and",
"not",
"isinstance",
"(",
"search_string",
",",
"unicode",
")",
":",
"search_string",
"=",
"search_string",
".",
... | 46.894737 | 17.631579 |
def connect(self):
"""Connects the client object to redis.
It's safe to use this method even if you are already connected.
Note: this method is useless with autoconnect mode (default).
Returns:
a Future object with True as result if the connection was ok.
"""
... | [
"def",
"connect",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_connected",
"(",
")",
":",
"raise",
"tornado",
".",
"gen",
".",
"Return",
"(",
"True",
")",
"cb1",
"=",
"self",
".",
"_read_callback",
"cb2",
"=",
"self",
".",
"_close_callback",
"self",
... | 43.171429 | 14.485714 |
def getAllSensors(self):
"""
Retrieve all the user's own sensors by iterating over the SensorsGet function
@return (list) - Array of sensors
"""
j = 0
sensors = []
parameters = {'page':0, 'per_page':1000, 'owned':1}
while True... | [
"def",
"getAllSensors",
"(",
"self",
")",
":",
"j",
"=",
"0",
"sensors",
"=",
"[",
"]",
"parameters",
"=",
"{",
"'page'",
":",
"0",
",",
"'per_page'",
":",
"1000",
",",
"'owned'",
":",
"1",
"}",
"while",
"True",
":",
"parameters",
"[",
"'page'",
"]... | 30.666667 | 21 |
def asdict(self, rawkey=False):
r"""Convert Result to dict.
Parameters:
rawkey(bool):
* True: dict key is Descriptor instance
* False: dict key is str
Returns:
dict
"""
if rawkey:
return dict(self.items())
... | [
"def",
"asdict",
"(",
"self",
",",
"rawkey",
"=",
"False",
")",
":",
"if",
"rawkey",
":",
"return",
"dict",
"(",
"self",
".",
"items",
"(",
")",
")",
"else",
":",
"return",
"{",
"str",
"(",
"k",
")",
":",
"v",
"for",
"k",
",",
"v",
"in",
"sel... | 21.789474 | 18 |
def unsign(self, token):
"""
Extract the data from a signed ``token``.
"""
if self.max_age is None:
data = self.signer.unsign(token)
else:
data = self.signer.unsign(token, max_age=self.max_age)
return signing.b64_decode(data.encode()) | [
"def",
"unsign",
"(",
"self",
",",
"token",
")",
":",
"if",
"self",
".",
"max_age",
"is",
"None",
":",
"data",
"=",
"self",
".",
"signer",
".",
"unsign",
"(",
"token",
")",
"else",
":",
"data",
"=",
"self",
".",
"signer",
".",
"unsign",
"(",
"tok... | 29.8 | 13.8 |
def dragLeaveEvent(self, event):
"""Clears drop cursor line"""
super(AbstractDragView, self).dragLeaveEvent(event)
self.dragline = None
self.viewport().update()
event.accept() | [
"def",
"dragLeaveEvent",
"(",
"self",
",",
"event",
")",
":",
"super",
"(",
"AbstractDragView",
",",
"self",
")",
".",
"dragLeaveEvent",
"(",
"event",
")",
"self",
".",
"dragline",
"=",
"None",
"self",
".",
"viewport",
"(",
")",
".",
"update",
"(",
")"... | 35 | 10.833333 |
def fill_form_field(self, field_name, field_value):
"""Fills given field with given value
:param field_name: name of field to fill
:param field_value: value with which to fill field
"""
self.browser.execute_script(
"document.getElementsByName(\"" + str(
... | [
"def",
"fill_form_field",
"(",
"self",
",",
"field_name",
",",
"field_value",
")",
":",
"self",
".",
"browser",
".",
"execute_script",
"(",
"\"document.getElementsByName(\\\"\"",
"+",
"str",
"(",
"field_name",
")",
"+",
"\"\\\")[0].value = \\\"\"",
"+",
"str",
"("... | 41.666667 | 14.111111 |
def request_log_level(self, req, msg):
"""Query or set the current logging level.
Parameters
----------
level : {'all', 'trace', 'debug', 'info', 'warn', 'error', 'fatal', \
'off'}, optional
Name of the logging level to set the device server to (the default
... | [
"def",
"request_log_level",
"(",
"self",
",",
"req",
",",
"msg",
")",
":",
"if",
"msg",
".",
"arguments",
":",
"try",
":",
"self",
".",
"log",
".",
"set_log_level_by_name",
"(",
"msg",
".",
"arguments",
"[",
"0",
"]",
")",
"except",
"ValueError",
",",
... | 29.057143 | 20.685714 |
def cdpop():
"""
Return the last directory.
Returns absolute path to new working directory.
"""
if len(_cdhist) >= 1:
old = _cdhist.pop() # Pop from history.
os.chdir(old)
return old
else:
return pwd() | [
"def",
"cdpop",
"(",
")",
":",
"if",
"len",
"(",
"_cdhist",
")",
">=",
"1",
":",
"old",
"=",
"_cdhist",
".",
"pop",
"(",
")",
"# Pop from history.",
"os",
".",
"chdir",
"(",
"old",
")",
"return",
"old",
"else",
":",
"return",
"pwd",
"(",
")"
] | 20.666667 | 17 |
def has(cmd):
"""Returns true if the give shell command is available.
**Examples**:
::
auxly.shell.has("ls") # True
"""
helps = ["--help", "-h", "--version"]
if "nt" == os.name:
helps.insert(0, "/?")
fakecmd = "fakecmd"
cmderr = strerr(fakecmd).replace(fakecmd, cmd)
... | [
"def",
"has",
"(",
"cmd",
")",
":",
"helps",
"=",
"[",
"\"--help\"",
",",
"\"-h\"",
",",
"\"--version\"",
"]",
"if",
"\"nt\"",
"==",
"os",
".",
"name",
":",
"helps",
".",
"insert",
"(",
"0",
",",
"\"/?\"",
")",
"fakecmd",
"=",
"\"fakecmd\"",
"cmderr"... | 25.666667 | 14.714286 |
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
pretty = spaces + 'class ' + self.name
if self.superclasses:
... | [
"def",
"pretty_str",
"(",
"self",
",",
"indent",
"=",
"0",
")",
":",
"spaces",
"=",
"' '",
"*",
"indent",
"pretty",
"=",
"spaces",
"+",
"'class '",
"+",
"self",
".",
"name",
"if",
"self",
".",
"superclasses",
":",
"superclasses",
"=",
"', '",
".",
"j... | 33.2 | 13.85 |
def serialize_text_node(self, elt, sw, pyobj):
'''Serialize without an element node.
'''
self.set_prefix(elt, pyobj)
return String.serialize_text_node(self, elt, sw, pyobj) | [
"def",
"serialize_text_node",
"(",
"self",
",",
"elt",
",",
"sw",
",",
"pyobj",
")",
":",
"self",
".",
"set_prefix",
"(",
"elt",
",",
"pyobj",
")",
"return",
"String",
".",
"serialize_text_node",
"(",
"self",
",",
"elt",
",",
"sw",
",",
"pyobj",
")"
] | 40 | 13.6 |
def extract_smiles(s):
"""Return a list of SMILES identifiers extracted from the string."""
# TODO: This still gets a lot of false positives.
smiles = []
for t in s.split():
if len(t) > 2 and SMILES_RE.match(t) and not t.endswith('.') and bracket_level(t) == 0:
smiles.append(t)
r... | [
"def",
"extract_smiles",
"(",
"s",
")",
":",
"# TODO: This still gets a lot of false positives.",
"smiles",
"=",
"[",
"]",
"for",
"t",
"in",
"s",
".",
"split",
"(",
")",
":",
"if",
"len",
"(",
"t",
")",
">",
"2",
"and",
"SMILES_RE",
".",
"match",
"(",
... | 40.625 | 20.375 |
def parse_gmsh(filename, boundary_file):
"""
Parse a GMSH .msh file and return a dictionary containing the data
neccessary to create CRTomo grids
"""
mesh = {}
fid = open(filename, 'r')
line = fid.readline()
while(line):
if(line.startswith('$MeshFormat')):
pass
... | [
"def",
"parse_gmsh",
"(",
"filename",
",",
"boundary_file",
")",
":",
"mesh",
"=",
"{",
"}",
"fid",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
"line",
"=",
"fid",
".",
"readline",
"(",
")",
"while",
"(",
"line",
")",
":",
"if",
"(",
"line",
"... | 42.505618 | 17.314607 |
def _configure_device(commands, **kwargs):
'''
Helper function to send configuration commands to the device over a
proxy minion or native minion using NX-API or SSH.
'''
if salt.utils.platform.is_proxy():
return __proxy__['nxos.proxy_config'](commands, **kwargs)
else:
return _nxa... | [
"def",
"_configure_device",
"(",
"commands",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"salt",
".",
"utils",
".",
"platform",
".",
"is_proxy",
"(",
")",
":",
"return",
"__proxy__",
"[",
"'nxos.proxy_config'",
"]",
"(",
"commands",
",",
"*",
"*",
"kwargs",... | 37.888889 | 19.888889 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.