text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def wait(self, timeout=None):
"""
Blocking wait for task status.
"""
if self._thread is None:
return
self._thread.join(timeout=timeout) | [
"def",
"wait",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"self",
".",
"_thread",
"is",
"None",
":",
"return",
"self",
".",
"_thread",
".",
"join",
"(",
"timeout",
"=",
"timeout",
")"
] | 25.857143 | 0.010695 |
def StatusLine(self):
"""Generate the colored line indicating plugin status."""
pid = self.inferior.pid
curthread = None
threadnum = 0
if pid:
if not self.inferior.is_running:
logging.warning('Inferior is not running.')
self.Detach()
pid = None
else:
try:
... | [
"def",
"StatusLine",
"(",
"self",
")",
":",
"pid",
"=",
"self",
".",
"inferior",
".",
"pid",
"curthread",
"=",
"None",
"threadnum",
"=",
"0",
"if",
"pid",
":",
"if",
"not",
"self",
".",
"inferior",
".",
"is_running",
":",
"logging",
".",
"warning",
"... | 35.925926 | 0.01004 |
def process_samples_table(samples_table,
instruments_table,
mef_transform_fxns=None,
beads_table=None,
base_dir=".",
verbose=False,
plot=False,
... | [
"def",
"process_samples_table",
"(",
"samples_table",
",",
"instruments_table",
",",
"mef_transform_fxns",
"=",
"None",
",",
"beads_table",
"=",
"None",
",",
"base_dir",
"=",
"\".\"",
",",
"verbose",
"=",
"False",
",",
"plot",
"=",
"False",
",",
"plot_dir",
"=... | 46.130435 | 0.001779 |
def process_options(pkg_version, sys_argv, option_list=None):
"""Handle debugger options. Set `option_list' if you are writing
another main program and want to extend the existing set of debugger
options.
The options dicionary from opt_parser is return. sys_argv is
also updated."""
usage_str=""... | [
"def",
"process_options",
"(",
"pkg_version",
",",
"sys_argv",
",",
"option_list",
"=",
"None",
")",
":",
"usage_str",
"=",
"\"\"\"%prog [debugger-options]]\n\n Client connection to an out-of-process trepan3k debugger session\"\"\"",
"# serverChoices = ('TCP','FIFO', None) # we use ... | 44.272727 | 0.00134 |
def t_IDENTIFIER(self, t):
r'[a-zA-Z_][a-zA-Z0-9_]*'
t.type = self.reserved_words.get(t.value, 'IDENTIFIER')
return t | [
"def",
"t_IDENTIFIER",
"(",
"self",
",",
"t",
")",
":",
"t",
".",
"type",
"=",
"self",
".",
"reserved_words",
".",
"get",
"(",
"t",
".",
"value",
",",
"'IDENTIFIER'",
")",
"return",
"t"
] | 34.5 | 0.014184 |
def _write_enums(self, entity_name, attributes):
""" This method writes the ouput for a particular specification.
"""
self.enum_attrs_for_locale[entity_name] = attributes;
for attribute in attributes:
enum_name = "%s%sEnum" % (entity_name, attribute.name[0].upper() ... | [
"def",
"_write_enums",
"(",
"self",
",",
"entity_name",
",",
"attributes",
")",
":",
"self",
".",
"enum_attrs_for_locale",
"[",
"entity_name",
"]",
"=",
"attributes",
"for",
"attribute",
"in",
"attributes",
":",
"enum_name",
"=",
"\"%s%sEnum\"",
"%",
"(",
"ent... | 48.25 | 0.022872 |
def _find_common_roots(paths):
"""Out of some paths it finds the common roots that need monitoring."""
paths = [x.split(os.path.sep) for x in paths]
root = {}
for chunks in sorted(paths, key=len, reverse=True):
node = root
for chunk in chunks:
node = node.setdefault(chunk, {}... | [
"def",
"_find_common_roots",
"(",
"paths",
")",
":",
"paths",
"=",
"[",
"x",
".",
"split",
"(",
"os",
".",
"path",
".",
"sep",
")",
"for",
"x",
"in",
"paths",
"]",
"root",
"=",
"{",
"}",
"for",
"chunks",
"in",
"sorted",
"(",
"paths",
",",
"key",
... | 27.35 | 0.001767 |
def wol(mac, bcast='255.255.255.255', destport=9):
'''
Send a "Magic Packet" to wake up a Minion
CLI Example:
.. code-block:: bash
salt-run network.wol 08-00-27-13-69-77
salt-run network.wol 080027136977 255.255.255.255 7
salt-run network.wol 08:00:27:13:69:77 255.255.255.255 ... | [
"def",
"wol",
"(",
"mac",
",",
"bcast",
"=",
"'255.255.255.255'",
",",
"destport",
"=",
"9",
")",
":",
"dest",
"=",
"salt",
".",
"utils",
".",
"network",
".",
"mac_str_to_bytes",
"(",
"mac",
")",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
"... | 33.470588 | 0.001709 |
def full_data(tgt,
fun,
arg=None,
tgt_type='glob',
returner='',
timeout=5):
'''
Return the full data about the publication, this is invoked in the same
way as the publish function
CLI Example:
.. code-block:: bash
salt ... | [
"def",
"full_data",
"(",
"tgt",
",",
"fun",
",",
"arg",
"=",
"None",
",",
"tgt_type",
"=",
"'glob'",
",",
"returner",
"=",
"''",
",",
"timeout",
"=",
"5",
")",
":",
"return",
"_publish",
"(",
"tgt",
",",
"fun",
",",
"arg",
"=",
"arg",
",",
"tgt_t... | 26.085714 | 0.001056 |
def format(sql, encoding=None, **options):
"""Format *sql* according to *options*.
Available options are documented in :ref:`formatting`.
In addition to the formatting options this function accepts the
keyword "encoding" which determines the encoding of the statement.
:returns: The formatted SQL ... | [
"def",
"format",
"(",
"sql",
",",
"encoding",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"stack",
"=",
"engine",
".",
"FilterStack",
"(",
")",
"options",
"=",
"formatter",
".",
"validate_options",
"(",
"options",
")",
"stack",
"=",
"formatter",
"... | 38.533333 | 0.001689 |
def fix_e265(source, aggressive=False): # pylint: disable=unused-argument
"""Format block comments."""
if '#' not in source:
# Optimization.
return source
ignored_line_numbers = multiline_string_lines(
source,
include_docstrings=True) | set(commented_out_code_lines(source))... | [
"def",
"fix_e265",
"(",
"source",
",",
"aggressive",
"=",
"False",
")",
":",
"# pylint: disable=unused-argument",
"if",
"'#'",
"not",
"in",
"source",
":",
"# Optimization.",
"return",
"source",
"ignored_line_numbers",
"=",
"multiline_string_lines",
"(",
"source",
",... | 34.763158 | 0.000736 |
def imrescale(img, scale, return_scale=False, interpolation='bilinear'):
"""Resize image while keeping the aspect ratio.
Args:
img (ndarray): The input image.
scale (float or tuple[int]): The scaling factor or maximum size.
If it is a float number, then the image will be rescaled by... | [
"def",
"imrescale",
"(",
"img",
",",
"scale",
",",
"return_scale",
"=",
"False",
",",
"interpolation",
"=",
"'bilinear'",
")",
":",
"h",
",",
"w",
"=",
"img",
".",
"shape",
"[",
":",
"2",
"]",
"if",
"isinstance",
"(",
"scale",
",",
"(",
"float",
",... | 38.864865 | 0.000678 |
def send_photo(self, photo: str, caption: str=None, reply: Message=None, on_success: callable=None,
reply_markup: botapi.ReplyMarkup=None):
"""
Send photo to this peer.
:param photo: File path to photo to send.
:param caption: Caption for photo
:param reply: Me... | [
"def",
"send_photo",
"(",
"self",
",",
"photo",
":",
"str",
",",
"caption",
":",
"str",
"=",
"None",
",",
"reply",
":",
"Message",
"=",
"None",
",",
"on_success",
":",
"callable",
"=",
"None",
",",
"reply_markup",
":",
"botapi",
".",
"ReplyMarkup",
"="... | 47.923077 | 0.020472 |
def decode_cookie(cookie, key=None):
'''
This decodes a cookie given by `encode_cookie`. If verification of the
cookie fails, ``None`` will be implicitly returned.
:param cookie: An encoded cookie.
:type cookie: str
:param key: The key to use when creating the cookie digest. If not
... | [
"def",
"decode_cookie",
"(",
"cookie",
",",
"key",
"=",
"None",
")",
":",
"try",
":",
"payload",
",",
"digest",
"=",
"cookie",
".",
"rsplit",
"(",
"u'|'",
",",
"1",
")",
"if",
"hasattr",
"(",
"digest",
",",
"'decode'",
")",
":",
"digest",
"=",
"dig... | 32.285714 | 0.001433 |
def digit(decimal, digit, input_base=10):
"""
Find the value of an integer at a specific digit when represented in a
particular base.
Args:
decimal(int): A number represented in base 10 (positive integer).
digit(int): The digit to find where zero is the first, lowest, digit.
... | [
"def",
"digit",
"(",
"decimal",
",",
"digit",
",",
"input_base",
"=",
"10",
")",
":",
"if",
"decimal",
"==",
"0",
":",
"return",
"0",
"if",
"digit",
"!=",
"0",
":",
"return",
"(",
"decimal",
"//",
"(",
"input_base",
"**",
"digit",
")",
")",
"%",
... | 29.264706 | 0.000973 |
def capabilities(self, keyword=None):
"""CAPABILITIES command.
Determines the capabilities of the server.
Although RFC3977 states that this is a required command for servers to
implement not all servers do, so expect that NNTPPermanentError may be
raised when this command is is... | [
"def",
"capabilities",
"(",
"self",
",",
"keyword",
"=",
"None",
")",
":",
"args",
"=",
"keyword",
"code",
",",
"message",
"=",
"self",
".",
"command",
"(",
"\"CAPABILITIES\"",
",",
"args",
")",
"if",
"code",
"!=",
"101",
":",
"raise",
"NNTPReplyError",
... | 34.153846 | 0.002191 |
def request(self, path, method='GET', params=None, type=REST_TYPE):
"""Builds a request, gets a response and decodes it."""
response_text = self._get_http_client(type).request(path, method, params)
if not response_text:
return response_text
response_json = json.loads(respon... | [
"def",
"request",
"(",
"self",
",",
"path",
",",
"method",
"=",
"'GET'",
",",
"params",
"=",
"None",
",",
"type",
"=",
"REST_TYPE",
")",
":",
"response_text",
"=",
"self",
".",
"_get_http_client",
"(",
"type",
")",
".",
"request",
"(",
"path",
",",
"... | 36.307692 | 0.008264 |
def create_canonical_classpath(cls, classpath_products, targets, basedir,
save_classpath_file=False,
internal_classpath_only=True,
excludes=None):
"""Create a stable classpath of symlinks with standardized names.
... | [
"def",
"create_canonical_classpath",
"(",
"cls",
",",
"classpath_products",
",",
"targets",
",",
"basedir",
",",
"save_classpath_file",
"=",
"False",
",",
"internal_classpath_only",
"=",
"True",
",",
"excludes",
"=",
"None",
")",
":",
"def",
"delete_old_target_outpu... | 51.133333 | 0.012059 |
def get_all_knoreq_user_objects(self, include_machine = False):
"""
Fetches all user objects with useraccountcontrol DONT_REQ_PREAUTH flag set from the AD, and returns MSADUser object.
"""
logger.debug('Polling AD for all user objects, machine accounts included: %s'% include_machine)
if include_machine == ... | [
"def",
"get_all_knoreq_user_objects",
"(",
"self",
",",
"include_machine",
"=",
"False",
")",
":",
"logger",
".",
"debug",
"(",
"'Polling AD for all user objects, machine accounts included: %s'",
"%",
"include_machine",
")",
"if",
"include_machine",
"==",
"True",
":",
"... | 44.5625 | 0.032967 |
def plotHistogram(freqCounts, title='On-Times Histogram', xLabel='On-Time'):
"""
This is usually used to display a histogram of the on-times encountered
in a particular output.
The freqCounts is a vector containg the frequency counts of each on-time
(starting at an on-time of 0 and going to an on-time = len(... | [
"def",
"plotHistogram",
"(",
"freqCounts",
",",
"title",
"=",
"'On-Times Histogram'",
",",
"xLabel",
"=",
"'On-Time'",
")",
":",
"import",
"pylab",
"pylab",
".",
"ion",
"(",
")",
"pylab",
".",
"figure",
"(",
")",
"pylab",
".",
"bar",
"(",
"numpy",
".",
... | 29.64 | 0.010458 |
async def _process_lines(self, pattern: Optional[str] = None) -> None:
"""Read line from pipe they match with pattern."""
if pattern is not None:
cmp = re.compile(pattern)
_LOGGER.debug("Start working with pattern '%s'.", pattern)
# read lines
while self.is_running:... | [
"async",
"def",
"_process_lines",
"(",
"self",
",",
"pattern",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"None",
":",
"if",
"pattern",
"is",
"not",
"None",
":",
"cmp",
"=",
"re",
".",
"compile",
"(",
"pattern",
")",
"_LOGGER",
".",
... | 33.814815 | 0.00213 |
def query_insert(self, direction='max'):
"""
Query to get latest (default) or earliest update to repository
"""
if direction == 'min':
return Layer.objects.aggregate(
Min('last_updated'))['last_updated__min'].strftime('%Y-%m-%dT%H:%M:%SZ')
return self.... | [
"def",
"query_insert",
"(",
"self",
",",
"direction",
"=",
"'max'",
")",
":",
"if",
"direction",
"==",
"'min'",
":",
"return",
"Layer",
".",
"objects",
".",
"aggregate",
"(",
"Min",
"(",
"'last_updated'",
")",
")",
"[",
"'last_updated__min'",
"]",
".",
"... | 48.777778 | 0.008949 |
def bytes_required(self):
"""
Returns
-------
int
Estimated number of bytes required by arrays registered
on the cube, taking their extents into account.
"""
return np.sum([hcu.array_bytes(a) for a
in self.arrays(reify=True).itervalues(... | [
"def",
"bytes_required",
"(",
"self",
")",
":",
"return",
"np",
".",
"sum",
"(",
"[",
"hcu",
".",
"array_bytes",
"(",
"a",
")",
"for",
"a",
"in",
"self",
".",
"arrays",
"(",
"reify",
"=",
"True",
")",
".",
"itervalues",
"(",
")",
"]",
")"
] | 31.4 | 0.009288 |
def new_pos(self, html_div):
"""factory method pattern"""
pos = self.Position(self, html_div)
pos.bind_mov()
self.positions.append(pos)
return pos | [
"def",
"new_pos",
"(",
"self",
",",
"html_div",
")",
":",
"pos",
"=",
"self",
".",
"Position",
"(",
"self",
",",
"html_div",
")",
"pos",
".",
"bind_mov",
"(",
")",
"self",
".",
"positions",
".",
"append",
"(",
"pos",
")",
"return",
"pos"
] | 30.166667 | 0.010753 |
def decode(secret: Union[str, bytes], token: Union[str, bytes],
alg: str = default_alg) -> Tuple[dict, dict]:
"""
Decodes the given token's header and payload and validates the signature.
:param secret: The secret used to decode the token. Must match the
secret used when creating the tok... | [
"def",
"decode",
"(",
"secret",
":",
"Union",
"[",
"str",
",",
"bytes",
"]",
",",
"token",
":",
"Union",
"[",
"str",
",",
"bytes",
"]",
",",
"alg",
":",
"str",
"=",
"default_alg",
")",
"->",
"Tuple",
"[",
"dict",
",",
"dict",
"]",
":",
"secret",
... | 42.142857 | 0.000552 |
def DualDBFlow(cls):
"""Decorator that creates AFF4 and RELDB flows from a given mixin."""
if issubclass(cls, flow.GRRFlow):
raise ValueError("Mixin class shouldn't inherit from GRRFlow.")
if cls.__name__[-5:] != "Mixin":
raise ValueError("Flow mixin should have a name that ends in 'Mixin'.")
flow_na... | [
"def",
"DualDBFlow",
"(",
"cls",
")",
":",
"if",
"issubclass",
"(",
"cls",
",",
"flow",
".",
"GRRFlow",
")",
":",
"raise",
"ValueError",
"(",
"\"Mixin class shouldn't inherit from GRRFlow.\"",
")",
"if",
"cls",
".",
"__name__",
"[",
"-",
"5",
":",
"]",
"!=... | 32.368421 | 0.018957 |
def url_concat(
url: str,
args: Union[
None, Dict[str, str], List[Tuple[str, str]], Tuple[Tuple[str, str], ...]
],
) -> str:
"""Concatenate url and arguments regardless of whether
url has existing query parameters.
``args`` may be either a dictionary or a list of key-value pairs
(th... | [
"def",
"url_concat",
"(",
"url",
":",
"str",
",",
"args",
":",
"Union",
"[",
"None",
",",
"Dict",
"[",
"str",
",",
"str",
"]",
",",
"List",
"[",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
",",
"Tuple",
"[",
"Tuple",
"[",
"str",
",",
"str",
"]... | 32.266667 | 0.001337 |
def dispatch_event(self, event, *args):
"""Dispatches an event.
Returns a boolean indicating whether or not a handler
suppressed further handling of the event (even the last).
"""
if event not in self.event_handlers:
_log.error("Dispatch requested for unknown event '... | [
"def",
"dispatch_event",
"(",
"self",
",",
"event",
",",
"*",
"args",
")",
":",
"if",
"event",
"not",
"in",
"self",
".",
"event_handlers",
":",
"_log",
".",
"error",
"(",
"\"Dispatch requested for unknown event '%s'\"",
",",
"event",
")",
"return",
"False",
... | 38.296296 | 0.001887 |
def little_endian(self):
"""
Return the little_endian attribute of the BFD file being processed.
"""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(self._ptr, BfdAttributes.IS_LITTLE_ENDIAN) | [
"def",
"little_endian",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_ptr",
":",
"raise",
"BfdException",
"(",
"\"BFD not initialized\"",
")",
"return",
"_bfd",
".",
"get_bfd_attribute",
"(",
"self",
".",
"_ptr",
",",
"BfdAttributes",
".",
"IS_LITTLE_ENDI... | 34.875 | 0.01049 |
def get_labels(ids_find):
""" Labels to make Cannon model spectra """
a = pyfits.open("%s/lamost_catalog_full.fits" %LAB_DIR)
data = a[1].data
a.close()
id_all = data['lamost_id']
id_all = np.array(id_all)
id_all = np.array([val.strip() for val in id_all])
snr_all = data['cannon_snrg']
... | [
"def",
"get_labels",
"(",
"ids_find",
")",
":",
"a",
"=",
"pyfits",
".",
"open",
"(",
"\"%s/lamost_catalog_full.fits\"",
"%",
"LAB_DIR",
")",
"data",
"=",
"a",
"[",
"1",
"]",
".",
"data",
"a",
".",
"close",
"(",
")",
"id_all",
"=",
"data",
"[",
"'lam... | 36.28 | 0.009667 |
def prob(self, pw):
"""
returns the probabiltiy of pw in the model.
P[pw] = n(pw)/n(__total__)
"""
return float(self._T.get(pw, 0)) / self._T[TOTALF_W] | [
"def",
"prob",
"(",
"self",
",",
"pw",
")",
":",
"return",
"float",
"(",
"self",
".",
"_T",
".",
"get",
"(",
"pw",
",",
"0",
")",
")",
"/",
"self",
".",
"_T",
"[",
"TOTALF_W",
"]"
] | 31 | 0.010471 |
def find_project_file(start_dir, basename):
'''Walk up the directory tree until we find a file of the given name.'''
prefix = os.path.abspath(start_dir)
while True:
candidate = os.path.join(prefix, basename)
if os.path.isfile(candidate):
return candidate
if os.path.exists... | [
"def",
"find_project_file",
"(",
"start_dir",
",",
"basename",
")",
":",
"prefix",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"start_dir",
")",
"while",
"True",
":",
"candidate",
"=",
"os",
".",
"path",
".",
"join",
"(",
"prefix",
",",
"basename",
")... | 45.466667 | 0.001437 |
def save(cls, network, phases=[], filename=''):
r"""
Saves data from the given objects into the specified file.
Parameters
----------
network : OpenPNM Network Object
The network containing the desired data
phases : list of OpenPNM Phase Objects (optional, d... | [
"def",
"save",
"(",
"cls",
",",
"network",
",",
"phases",
"=",
"[",
"]",
",",
"filename",
"=",
"''",
")",
":",
"project",
",",
"network",
",",
"phases",
"=",
"cls",
".",
"_parse_args",
"(",
"network",
"=",
"network",
",",
"phases",
"=",
"phases",
"... | 38.834862 | 0.000461 |
def organization_memberships(self, organization):
"""
Retrieve tche organization fields for this organization.
:param organization: Organization object or id
"""
return self._query_zendesk(self.endpoint.organization_memberships, 'organization_membership', id=organization) | [
"def",
"organization_memberships",
"(",
"self",
",",
"organization",
")",
":",
"return",
"self",
".",
"_query_zendesk",
"(",
"self",
".",
"endpoint",
".",
"organization_memberships",
",",
"'organization_membership'",
",",
"id",
"=",
"organization",
")"
] | 43.857143 | 0.009585 |
def to_native(self, value, context=None):
""" Schematics deserializer override
We return a phoenumbers.PhoneNumber object so any kind
of formatting can be trivially performed. Additionally,
some convenient properties have been added:
e164: string formatted '+11234567890'
... | [
"def",
"to_native",
"(",
"self",
",",
"value",
",",
"context",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"pn",
".",
"phonenumber",
".",
"PhoneNumber",
")",
":",
"return",
"value",
"try",
":",
"phone",
"=",
"pn",
".",
"parse",
"(",... | 34.354839 | 0.001826 |
def restore_bios_config(irmc_info, bios_config):
"""restore bios configuration
This function sends a RESTORE BIOS request to the server. Then when the
bios
is ready for restoring, it will apply the provided settings and return.
Note that this operation may take time.
:param irmc_info: node inf... | [
"def",
"restore_bios_config",
"(",
"irmc_info",
",",
"bios_config",
")",
":",
"def",
"_process_bios_config",
"(",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"bios_config",
",",
"dict",
")",
":",
"input_data",
"=",
"bios_config",
"else",
":",
"input_data",
... | 38.339286 | 0.000454 |
def index_whichnot(ol,value,which):
'''
from elist.elist import *
ol = [1,'a',3,'a',4,'a',5]
index_whichnot(ol,'a',0)
index_whichnot(ol,'a',1)
index_whichnot(ol,'a',2)
'''
length = ol.__len__()
seq = -1
for i in range(0,length):
if(value == ol[i]):
... | [
"def",
"index_whichnot",
"(",
"ol",
",",
"value",
",",
"which",
")",
":",
"length",
"=",
"ol",
".",
"__len__",
"(",
")",
"seq",
"=",
"-",
"1",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"length",
")",
":",
"if",
"(",
"value",
"==",
"ol",
"[",
... | 23.3 | 0.008247 |
def update(self,
task_id,
progress):
"""
Defines the current progress for this progress bar id in iteration units (not percent).
If the given id does not exist or the given progress is identical to the current, then does nothing.
Logger uses a redraw rate be... | [
"def",
"update",
"(",
"self",
",",
"task_id",
",",
"progress",
")",
":",
"self",
".",
"queue",
".",
"put",
"(",
"dill",
".",
"dumps",
"(",
"UpdateProgressCommand",
"(",
"task_id",
"=",
"task_id",
",",
"progress",
"=",
"progress",
")",
")",
")"
] | 70.2 | 0.010309 |
def isCountRate(self):
"""
isCountRate: Method or IRInputObject used to indicate if the
science data is in units of counts or count rate. This method
assumes that the keyword 'BUNIT' is in the header of the input
FITS file.
"""
has_bunit = False
if 'BUNIT... | [
"def",
"isCountRate",
"(",
"self",
")",
":",
"has_bunit",
"=",
"False",
"if",
"'BUNIT'",
"in",
"self",
".",
"_image",
"[",
"'sci'",
",",
"1",
"]",
".",
"header",
":",
"has_bunit",
"=",
"True",
"countrate",
"=",
"False",
"if",
"(",
"self",
".",
"_imag... | 35.588235 | 0.012882 |
def get_performed_builds(self, id, **kwargs):
"""
Gets the set of builds performed during in a Product Milestone cycle
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when re... | [
"def",
"get_performed_builds",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"get_performed_builds_with_... | 42.034483 | 0.002406 |
def dens(self,R,z,phi=0.,t=0.,forcepoisson=False):
"""
NAME:
dens
PURPOSE:
evaluate the density rho(R,z,t)
INPUT:
R - Cylindrical Galactocentric radius (can be Quantity)
z - vertical height (can be Quantity)
phi - azimuth (opt... | [
"def",
"dens",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
",",
"forcepoisson",
"=",
"False",
")",
":",
"try",
":",
"if",
"forcepoisson",
":",
"raise",
"AttributeError",
"#Hack!",
"return",
"self",
".",
"_amp",
"*",... | 27.380952 | 0.030227 |
def random_square_mask(shape, fraction):
"""Create a numpy array with specified shape and masked fraction.
Args:
shape: tuple, shape of the mask to create.
fraction: float, fraction of the mask area to populate with `mask_scalar`.
Returns:
numpy.array: A numpy array storing the mask.
"""
mask =... | [
"def",
"random_square_mask",
"(",
"shape",
",",
"fraction",
")",
":",
"mask",
"=",
"np",
".",
"ones",
"(",
"shape",
")",
"patch_area",
"=",
"shape",
"[",
"0",
"]",
"*",
"shape",
"[",
"1",
"]",
"*",
"fraction",
"patch_dim",
"=",
"np",
".",
"int",
"(... | 26.166667 | 0.015361 |
def refine(video, **kwargs):
"""Refine a video by searching `TheTVDB <http://thetvdb.com/>`_.
.. note::
This refiner only work for instances of :class:`~subliminal.video.Episode`.
Several attributes can be found:
* :attr:`~subliminal.video.Episode.series`
* :attr:`~subliminal.video.E... | [
"def",
"refine",
"(",
"video",
",",
"*",
"*",
"kwargs",
")",
":",
"# only deal with Episode videos",
"if",
"not",
"isinstance",
"(",
"video",
",",
"Episode",
")",
":",
"logger",
".",
"error",
"(",
"'Cannot refine episodes'",
")",
"return",
"# exit if the informa... | 35.412281 | 0.001928 |
def docopt(doc, argv=None, help=True, version=None, options_first=False):
"""Parse `argv` based on command-line interface described in `doc`.
`docopt` creates your command-line interface based on its
description that you pass as `doc`. Such description can contain
--options, <positional-argument>, comm... | [
"def",
"docopt",
"(",
"doc",
",",
"argv",
"=",
"None",
",",
"help",
"=",
"True",
",",
"version",
"=",
"None",
",",
"options_first",
"=",
"False",
")",
":",
"if",
"argv",
"is",
"None",
":",
"argv",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"D... | 34.875 | 0.000951 |
def p_createx(self,t):
"""expression : kw_create kw_table nexists NAME '(' tablespecs ')' opt_inheritx
| kw_create kw_table nexists NAME inheritx
"""
if len(t)==6:
t[0] = CreateX(t[3], t[4], [], None, [], t[5])
else:
all_constraints = {k:list(group) for k, group in itertool... | [
"def",
"p_createx",
"(",
"self",
",",
"t",
")",
":",
"if",
"len",
"(",
"t",
")",
"==",
"6",
":",
"t",
"[",
"0",
"]",
"=",
"CreateX",
"(",
"t",
"[",
"3",
"]",
",",
"t",
"[",
"4",
"]",
",",
"[",
"]",
",",
"None",
",",
"[",
"]",
",",
"t"... | 61.357143 | 0.021789 |
def tf_lanczos_smallest_eigval(vector_prod_fn,
matrix_dim,
initial_vector,
num_iter=1000,
max_iter=1000,
collapse_tol=1e-9,
dtype=tf.f... | [
"def",
"tf_lanczos_smallest_eigval",
"(",
"vector_prod_fn",
",",
"matrix_dim",
",",
"initial_vector",
",",
"num_iter",
"=",
"1000",
",",
"max_iter",
"=",
"1000",
",",
"collapse_tol",
"=",
"1e-9",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
":",
"# alpha will... | 35.305263 | 0.010441 |
def _add_finder(importer, finder):
"""Register a new pkg_resources path finder that does not replace the existing finder."""
existing_finder = _get_finder(importer)
if not existing_finder:
pkg_resources.register_finder(importer, finder)
else:
pkg_resources.register_finder(importer, ChainedFinder.of(ex... | [
"def",
"_add_finder",
"(",
"importer",
",",
"finder",
")",
":",
"existing_finder",
"=",
"_get_finder",
"(",
"importer",
")",
"if",
"not",
"existing_finder",
":",
"pkg_resources",
".",
"register_finder",
"(",
"importer",
",",
"finder",
")",
"else",
":",
"pkg_re... | 37.222222 | 0.020408 |
def register(cls, name: str, plugin: Type[ConnectionPlugin]) -> None:
"""Registers a connection plugin with a specified name
Args:
name: name of the connection plugin to register
plugin: defined connection plugin class
Raises:
:obj:`nornir.core.exceptions.Co... | [
"def",
"register",
"(",
"cls",
",",
"name",
":",
"str",
",",
"plugin",
":",
"Type",
"[",
"ConnectionPlugin",
"]",
")",
"->",
"None",
":",
"existing_plugin",
"=",
"cls",
".",
"available",
".",
"get",
"(",
"name",
")",
"if",
"existing_plugin",
"is",
"Non... | 43.4 | 0.002255 |
def _set_pose_num(self, pose_num):
"""WARNING: Applies only to the MDAnalysis_Wrapper
"""
current_mobile_coord = self.mobile_origin_coord
self.static_mobile_copy_uni.trajectory.ts._pos[self.static_num_atoms:,:] = self.zdock_trans_rot(self.grid_size, self.grid_spacing, self.init_t... | [
"def",
"_set_pose_num",
"(",
"self",
",",
"pose_num",
")",
":",
"current_mobile_coord",
"=",
"self",
".",
"mobile_origin_coord",
"self",
".",
"static_mobile_copy_uni",
".",
"trajectory",
".",
"ts",
".",
"_pos",
"[",
"self",
".",
"static_num_atoms",
":",
",",
"... | 64 | 0.013216 |
def set_up_resource_parameters(self):
"""Set up the resource parameter for the add/edit view.
"""
name_parameter = StringParameter('UUID-1')
name_parameter.name = self.resource_parameters['Resource name']
name_parameter.help_text = tr(
'Name of the resource that will ... | [
"def",
"set_up_resource_parameters",
"(",
"self",
")",
":",
"name_parameter",
"=",
"StringParameter",
"(",
"'UUID-1'",
")",
"name_parameter",
".",
"name",
"=",
"self",
".",
"resource_parameters",
"[",
"'Resource name'",
"]",
"name_parameter",
".",
"help_text",
"=",
... | 48.488095 | 0.000241 |
def get_workflow_actions_for(brain_or_object):
"""Returns a list with the actions (transitions) supported by the workflows
the object pass in is bound to. Note it returns all actions, not only those
allowed for the object based on its current state and permissions.
"""
portal_type = api.get_portal_t... | [
"def",
"get_workflow_actions_for",
"(",
"brain_or_object",
")",
":",
"portal_type",
"=",
"api",
".",
"get_portal_type",
"(",
"brain_or_object",
")",
"actions",
"=",
"actions_by_type",
".",
"get",
"(",
"portal_type",
",",
"None",
")",
"if",
"actions",
":",
"retur... | 41.142857 | 0.002262 |
def img2img_transformer2d_tiny():
"""Tiny params."""
hparams = img2img_transformer2d_base()
hparams.num_decoder_layers = 2
hparams.hidden_size = 128
hparams.batch_size = 4
hparams.max_length = 128
hparams.attention_key_channels = hparams.attention_value_channels = 0
hparams.filter_size = 128
hparams.n... | [
"def",
"img2img_transformer2d_tiny",
"(",
")",
":",
"hparams",
"=",
"img2img_transformer2d_base",
"(",
")",
"hparams",
".",
"num_decoder_layers",
"=",
"2",
"hparams",
".",
"hidden_size",
"=",
"128",
"hparams",
".",
"batch_size",
"=",
"4",
"hparams",
".",
"max_le... | 29.615385 | 0.032746 |
def build(self):
"""Builds the `HelicalHelix`."""
helical_helix = Polypeptide()
primitive_coords = self.curve_primitive.coordinates
helices = [Helix.from_start_and_end(start=primitive_coords[i],
end=primitive_coords[i + 1],
... | [
"def",
"build",
"(",
"self",
")",
":",
"helical_helix",
"=",
"Polypeptide",
"(",
")",
"primitive_coords",
"=",
"self",
".",
"curve_primitive",
".",
"coordinates",
"helices",
"=",
"[",
"Helix",
".",
"from_start_and_end",
"(",
"start",
"=",
"primitive_coords",
"... | 49.55 | 0.001979 |
def get_mounts_by_path():
'''
Gets all mounted devices and paths
:return: dict of mounted devices and related information by path
'''
mount_info = []
f = open('/proc/mounts', 'r')
for line in f:
_tmp = line.split(" ")
mount_info.append({'path': _tmp[1],
... | [
"def",
"get_mounts_by_path",
"(",
")",
":",
"mount_info",
"=",
"[",
"]",
"f",
"=",
"open",
"(",
"'/proc/mounts'",
",",
"'r'",
")",
"for",
"line",
"in",
"f",
":",
"_tmp",
"=",
"line",
".",
"split",
"(",
"\" \"",
")",
"mount_info",
".",
"append",
"(",
... | 31.0625 | 0.001953 |
def p_lpartselect_minus(self, p):
'lpartselect : identifier LBRACKET expression MINUSCOLON expression RBRACKET'
p[0] = Partselect(p[1], p[3], Minus(p[3], p[5]), lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_lpartselect_minus",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"Partselect",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"3",
"]",
",",
"Minus",
"(",
"p",
"[",
"3",
"]",
",",
"p",
"[",
"5",
"]",
")",
",",
"lineno",
"=... | 57.5 | 0.012876 |
def request_and_get_output(self, table, outtype, outfn):
"""
Shorthand for requesting an output file and then downloading it when
ready.
## Arguments
* `table` (str): The name of the table to export.
* `outtype` (str): The type of output. Must be one of:
CSV... | [
"def",
"request_and_get_output",
"(",
"self",
",",
"table",
",",
"outtype",
",",
"outfn",
")",
":",
"job_id",
"=",
"self",
".",
"request_output",
"(",
"table",
",",
"outtype",
")",
"status",
"=",
"self",
".",
"monitor",
"(",
"job_id",
")",
"if",
"status"... | 38.272727 | 0.002317 |
def set_level(self,
level,
console_only=False):
"""
Defines the logging level (from standard logging module) for log messages.
:param level: Level of logging for the file logger.
:param console_only: [Optional] If True then the file logger... | [
"def",
"set_level",
"(",
"self",
",",
"level",
",",
"console_only",
"=",
"False",
")",
":",
"self",
".",
"queue",
".",
"put",
"(",
"dill",
".",
"dumps",
"(",
"SetLevelCommand",
"(",
"level",
"=",
"level",
",",
"console_only",
"=",
"console_only",
")",
... | 48.7 | 0.012097 |
def style_from_dict(style_dict, include_defaults=True):
"""
Create a ``Style`` instance from a dictionary or other mapping.
The dictionary is equivalent to the ``Style.styles`` dictionary from
pygments, with a few additions: it supports 'reverse' and 'blink'.
Usage::
style_from_dict({
... | [
"def",
"style_from_dict",
"(",
"style_dict",
",",
"include_defaults",
"=",
"True",
")",
":",
"assert",
"isinstance",
"(",
"style_dict",
",",
"Mapping",
")",
"if",
"include_defaults",
":",
"s2",
"=",
"{",
"}",
"s2",
".",
"update",
"(",
"DEFAULT_STYLE_EXTENSIONS... | 32.724138 | 0.000341 |
def is_in(self, point_x, point_y):
""" Test if the point is within this ellipse """
x = self.x_origin
y = self.y_origin
a = self.e_width#/2 # FIXME: Why divide by two
b = self.e_height#/2
return ((point_x-x)**2/(a**2)) + ((point_y-y)**2/(b**2)) < 1.0 | [
"def",
"is_in",
"(",
"self",
",",
"point_x",
",",
"point_y",
")",
":",
"x",
"=",
"self",
".",
"x_origin",
"y",
"=",
"self",
".",
"y_origin",
"a",
"=",
"self",
".",
"e_width",
"#/2 # FIXME: Why divide by two",
"b",
"=",
"self",
".",
"e_height",
"#/2",
"... | 32.444444 | 0.02 |
def diag_stressor(self, stressor, name=None):
""" Diagonalize one row of the stressor matrix for a flow analysis.
This method takes one row of the F matrix and diagonalize
to the full region/sector format. Footprints calculation based
on this matrix show the flow of embodied stressors f... | [
"def",
"diag_stressor",
"(",
"self",
",",
"stressor",
",",
"name",
"=",
"None",
")",
":",
"if",
"type",
"(",
"stressor",
")",
"is",
"int",
":",
"stressor",
"=",
"self",
".",
"F",
".",
"index",
"[",
"stressor",
"]",
"if",
"len",
"(",
"stressor",
")"... | 32.982143 | 0.001052 |
def steps_for_spec(builder, spec, processed_modules=None):
'''
Sets `builder` configuration, and returns all the builder steps
necessary to build `spec` and its dependencies.
Traverses the dependencies in depth-first order, honoring the sequencing
in each 'depends_on' list.
'''
if processed... | [
"def",
"steps_for_spec",
"(",
"builder",
",",
"spec",
",",
"processed_modules",
"=",
"None",
")",
":",
"if",
"processed_modules",
"is",
"None",
":",
"processed_modules",
"=",
"set",
"(",
")",
"steps",
"=",
"[",
"]",
"for",
"module",
"in",
"spec",
".",
"g... | 34.428571 | 0.001346 |
def to_file(self, destination, format='csv', csv_delimiter=',', csv_header=True):
"""Save the results to a local file in CSV format.
Args:
destination: path on the local filesystem for the saved results.
format: the format to use for the exported data; currently only 'csv' is supported.
csv_d... | [
"def",
"to_file",
"(",
"self",
",",
"destination",
",",
"format",
"=",
"'csv'",
",",
"csv_delimiter",
"=",
"','",
",",
"csv_header",
"=",
"True",
")",
":",
"f",
"=",
"codecs",
".",
"open",
"(",
"destination",
",",
"'w'",
",",
"'utf-8'",
")",
"fieldname... | 40.869565 | 0.009356 |
def emit_pdf(outputs, options):
'''Runs the PDF conversion command to generate the PDF.'''
cmd = options.pdf_cmd
cmd = cmd.replace('%o', options.pdfname)
if len(outputs) > 2:
cmd_print = cmd.replace('%i', ' '.join(outputs[:2] + ['...']))
else:
cmd_print = cmd.replace('%i', ' '.join... | [
"def",
"emit_pdf",
"(",
"outputs",
",",
"options",
")",
":",
"cmd",
"=",
"options",
".",
"pdf_cmd",
"cmd",
"=",
"cmd",
".",
"replace",
"(",
"'%o'",
",",
"options",
".",
"pdfname",
")",
"if",
"len",
"(",
"outputs",
")",
">",
"2",
":",
"cmd_print",
"... | 28.36 | 0.001364 |
def files(self, pattern=None, sort_key=lambda k: k, sort_reverse=False, abspath=False):
""" Return a sorted list containing relative path of all files (recursively).
:type pattern: str
:param pattern: Unix style (glob like/gitignore like) pattern
:param sort_key: key argument for sorte... | [
"def",
"files",
"(",
"self",
",",
"pattern",
"=",
"None",
",",
"sort_key",
"=",
"lambda",
"k",
":",
"k",
",",
"sort_reverse",
"=",
"False",
",",
"abspath",
"=",
"False",
")",
":",
"return",
"sorted",
"(",
"self",
".",
"iterfiles",
"(",
"pattern",
","... | 36.733333 | 0.00885 |
def license_from_trove(trove):
"""Finds out license from list of trove classifiers.
Args:
trove: list of trove classifiers
Returns:
Fedora name of the package license or empty string, if no licensing
information is found in trove classifiers.
"""
license = []
for classifi... | [
"def",
"license_from_trove",
"(",
"trove",
")",
":",
"license",
"=",
"[",
"]",
"for",
"classifier",
"in",
"trove",
":",
"if",
"'License'",
"in",
"classifier",
":",
"stripped",
"=",
"classifier",
".",
"strip",
"(",
")",
"# if taken from EGG-INFO, begins with Clas... | 39.176471 | 0.001466 |
def patch(self, measurementId):
"""
Patches the metadata associated with the new measurement, if this impacts the measurement length then a new
measurement is created otherwise it just updates it in place.
:param measurementId:
:return:
"""
data = request.get_j... | [
"def",
"patch",
"(",
"self",
",",
"measurementId",
")",
":",
"data",
"=",
"request",
".",
"get_json",
"(",
")",
"if",
"data",
"is",
"not",
"None",
":",
"logger",
".",
"debug",
"(",
"'Received payload for '",
"+",
"measurementId",
"+",
"' - '",
"+",
"str"... | 43.333333 | 0.010038 |
def _randomize_single_subject(data, seed=None):
"""Randomly permute the voxels of the subject.
The subject is organized as Voxel x TR,
this method shuffles the voxel dimension in place.
Parameters
----------
data: 2D array in shape [nVoxels, nTRs]
Activity image data to be shuffled.
... | [
"def",
"_randomize_single_subject",
"(",
"data",
",",
"seed",
"=",
"None",
")",
":",
"if",
"seed",
"is",
"not",
"None",
":",
"np",
".",
"random",
".",
"seed",
"(",
"seed",
")",
"np",
".",
"random",
".",
"shuffle",
"(",
"data",
")"
] | 25.5 | 0.00189 |
def create_analysis(context, source, **kwargs):
"""Create a new Analysis. The source can be an Analysis Service or
an existing Analysis, and all possible field values will be set to the
values found in the source object.
:param context: The analysis will be created inside this object.
:param source... | [
"def",
"create_analysis",
"(",
"context",
",",
"source",
",",
"*",
"*",
"kwargs",
")",
":",
"an_id",
"=",
"kwargs",
".",
"get",
"(",
"'id'",
",",
"source",
".",
"getKeyword",
"(",
")",
")",
"analysis",
"=",
"_createObjectByType",
"(",
"\"Analysis\"",
","... | 46.033333 | 0.000709 |
def get_name_init(self, name):
"""Get initial name of symbol.
"""
self._register_name(name)
return self._var_name_mappers[name].get_init() | [
"def",
"get_name_init",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"_register_name",
"(",
"name",
")",
"return",
"self",
".",
"_var_name_mappers",
"[",
"name",
"]",
".",
"get_init",
"(",
")"
] | 27.666667 | 0.011696 |
def organization_subscription_delete(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/organization_subscriptions#delete-organization-subscription"
api_path = "/api/v2/organization_subscriptions/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, ... | [
"def",
"organization_subscription_delete",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/organization_subscriptions/{id}.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"id",
"=",
"id",
")",
"return",
"self",
".... | 68.4 | 0.008671 |
def stream(self, date_created_from=values.unset, date_created_to=values.unset,
limit=None, page_size=None):
"""
Streams ExecutionInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
... | [
"def",
"stream",
"(",
"self",
",",
"date_created_from",
"=",
"values",
".",
"unset",
",",
"date_created_to",
"=",
"values",
".",
"unset",
",",
"limit",
"=",
"None",
",",
"page_size",
"=",
"None",
")",
":",
"limits",
"=",
"self",
".",
"_version",
".",
"... | 55.655172 | 0.008526 |
def run(self):
""" Run the deduplication process.
We apply the removal strategy one duplicate set at a time to keep
memory footprint low and make the log of actions easier to read.
"""
logger.info(
"The {} strategy will be applied on each duplicate set.".format(
... | [
"def",
"run",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"The {} strategy will be applied on each duplicate set.\"",
".",
"format",
"(",
"self",
".",
"conf",
".",
"strategy",
")",
")",
"self",
".",
"stats",
"[",
"'set_total'",
"]",
"=",
"len",
"(",... | 34.347826 | 0.002463 |
def change_password(*_, user_id=None, password=None):
""" Change user password """
click.echo(green('\nChange password:'))
click.echo(green('-' * 40))
with get_app().app_context():
user = find_user(dict(id=user_id))
if not user:
click.echo(red('User not found\n'))
... | [
"def",
"change_password",
"(",
"*",
"_",
",",
"user_id",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"click",
".",
"echo",
"(",
"green",
"(",
"'\\nChange password:'",
")",
")",
"click",
".",
"echo",
"(",
"green",
"(",
"'-'",
"*",
"40",
")",
... | 31.105263 | 0.001642 |
def location_check(lat, lon):
"""For use by Core client wrappers"""
if not (isinstance(lat, number_types) and -90 <= lat <= 90):
raise ValueError("Latitude: '{latitude}' invalid".format(latitude=lat))
if not (isinstance(lon, number_types) and -180 <= lon <= 180):
raise V... | [
"def",
"location_check",
"(",
"lat",
",",
"lon",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"lat",
",",
"number_types",
")",
"and",
"-",
"90",
"<=",
"lat",
"<=",
"90",
")",
":",
"raise",
"ValueError",
"(",
"\"Latitude: '{latitude}' invalid\"",
".",
"... | 54.428571 | 0.010336 |
def delete_lbaas_member(self, lbaas_member, lbaas_pool):
"""Deletes the specified lbaas_member."""
return self.delete(self.lbaas_member_path % (lbaas_pool, lbaas_member)) | [
"def",
"delete_lbaas_member",
"(",
"self",
",",
"lbaas_member",
",",
"lbaas_pool",
")",
":",
"return",
"self",
".",
"delete",
"(",
"self",
".",
"lbaas_member_path",
"%",
"(",
"lbaas_pool",
",",
"lbaas_member",
")",
")"
] | 61.333333 | 0.010753 |
def pruneChanges(self, changeHorizon):
"""
Called periodically by DBConnector, this method deletes changes older
than C{changeHorizon}.
"""
if not changeHorizon:
return None
def thd(conn):
changes_tbl = self.db.model.changes
# First,... | [
"def",
"pruneChanges",
"(",
"self",
",",
"changeHorizon",
")",
":",
"if",
"not",
"changeHorizon",
":",
"return",
"None",
"def",
"thd",
"(",
"conn",
")",
":",
"changes_tbl",
"=",
"self",
".",
"db",
".",
"model",
".",
"changes",
"# First, get the list of chang... | 43.333333 | 0.001368 |
def rasterize_pdf(
input_file,
output_file,
xres,
yres,
raster_device,
log,
pageno=1,
page_dpi=None,
rotation=None,
filter_vector=False,
):
"""Rasterize one page of a PDF at resolution (xres, yres) in canvas units.
The image is sized to match the integer pixels dimension... | [
"def",
"rasterize_pdf",
"(",
"input_file",
",",
"output_file",
",",
"xres",
",",
"yres",
",",
"raster_device",
",",
"log",
",",
"pageno",
"=",
"1",
",",
"page_dpi",
"=",
"None",
",",
"rotation",
"=",
"None",
",",
"filter_vector",
"=",
"False",
",",
")",
... | 34.292929 | 0.000573 |
def exportFile(self, jobStoreFileID, dstUrl):
"""
Exports file to destination pointed at by the destination URL.
Refer to :meth:`.AbstractJobStore.importFile` documentation for currently supported URL schemes.
Note that the helper method _exportFile is used to read from the source and ... | [
"def",
"exportFile",
"(",
"self",
",",
"jobStoreFileID",
",",
"dstUrl",
")",
":",
"dstUrl",
"=",
"urlparse",
".",
"urlparse",
"(",
"dstUrl",
")",
"otherCls",
"=",
"self",
".",
"_findJobStoreForUrl",
"(",
"dstUrl",
",",
"export",
"=",
"True",
")",
"self",
... | 54.529412 | 0.008484 |
def max_entropy_distribution(node_indices, number_of_nodes):
"""Return the maximum entropy distribution over a set of nodes.
This is different from the network's uniform distribution because nodes
outside ``node_indices`` are fixed and treated as if they have only 1
state.
Args:
node_indic... | [
"def",
"max_entropy_distribution",
"(",
"node_indices",
",",
"number_of_nodes",
")",
":",
"distribution",
"=",
"np",
".",
"ones",
"(",
"repertoire_shape",
"(",
"node_indices",
",",
"number_of_nodes",
")",
")",
"return",
"distribution",
"/",
"distribution",
".",
"s... | 38 | 0.001427 |
def all(self, query=None, **kwargs):
"""
Gets all organizations.
"""
return super(OrganizationsProxy, self).all(query=query) | [
"def",
"all",
"(",
"self",
",",
"query",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"OrganizationsProxy",
",",
"self",
")",
".",
"all",
"(",
"query",
"=",
"query",
")"
] | 25.333333 | 0.012739 |
def logpdf_sum(self, f, y, Y_metadata=None):
"""
Convenience function that can overridden for functions where this could
be computed more efficiently
"""
return np.sum(self.logpdf(f, y, Y_metadata=Y_metadata)) | [
"def",
"logpdf_sum",
"(",
"self",
",",
"f",
",",
"y",
",",
"Y_metadata",
"=",
"None",
")",
":",
"return",
"np",
".",
"sum",
"(",
"self",
".",
"logpdf",
"(",
"f",
",",
"y",
",",
"Y_metadata",
"=",
"Y_metadata",
")",
")"
] | 40.666667 | 0.008032 |
def path_or_git_url(self, repo, owner='kivy', branch='master',
url_format='https://github.com/{owner}/{repo}.git',
platform=None,
squash_hyphen=True):
"""Get source location for a git checkout
This method will check the `buildozer.... | [
"def",
"path_or_git_url",
"(",
"self",
",",
"repo",
",",
"owner",
"=",
"'kivy'",
",",
"branch",
"=",
"'master'",
",",
"url_format",
"=",
"'https://github.com/{owner}/{repo}.git'",
",",
"platform",
"=",
"None",
",",
"squash_hyphen",
"=",
"True",
")",
":",
"if",... | 40.0375 | 0.001828 |
def get_element(text_or_tree_or_element):
"""
Get back an ET.Element for several possible input formats
"""
if isinstance(text_or_tree_or_element, ET.Element):
return text_or_tree_or_element
elif isinstance(text_or_tree_or_element, ET.ElementTree):
return text_or_tree_or_element.getr... | [
"def",
"get_element",
"(",
"text_or_tree_or_element",
")",
":",
"if",
"isinstance",
"(",
"text_or_tree_or_element",
",",
"ET",
".",
"Element",
")",
":",
"return",
"text_or_tree_or_element",
"elif",
"isinstance",
"(",
"text_or_tree_or_element",
",",
"ET",
".",
"Eleme... | 41.75 | 0.001953 |
def execute_command(parser, config, ext_classes):
"""
Banana banana
"""
res = 0
cmd = config.get('command')
get_private_folder = config.get('get_private_folder', False)
if cmd == 'help':
parser.print_help()
elif cmd == 'run' or get_private_folder: # git.mk backward compat
... | [
"def",
"execute_command",
"(",
"parser",
",",
"config",
",",
"ext_classes",
")",
":",
"res",
"=",
"0",
"cmd",
"=",
"config",
".",
"get",
"(",
"'command'",
")",
"get_private_folder",
"=",
"config",
".",
"get",
"(",
"'get_private_folder'",
",",
"False",
")",... | 32.55 | 0.000497 |
def cluster(args):
"""
Creating clusters
"""
args = _check_args(args)
read_stats_file = op.join(args.dir_out, "read_stats.tsv")
if file_exists(read_stats_file):
os.remove(read_stats_file)
bam_file, seq_obj = _clean_alignment(args)
logger.info("Parsing matrix file")
seqL, y... | [
"def",
"cluster",
"(",
"args",
")",
":",
"args",
"=",
"_check_args",
"(",
"args",
")",
"read_stats_file",
"=",
"op",
".",
"join",
"(",
"args",
".",
"dir_out",
",",
"\"read_stats.tsv\"",
")",
"if",
"file_exists",
"(",
"read_stats_file",
")",
":",
"os",
".... | 37.661972 | 0.002187 |
def ptz_status_send(self, zoom, pan, tilt, force_mavlink1=False):
'''
Transmits the actual Pan, Tilt and Zoom values of the camera unit
zoom : The actual Zoom Value (uint8_t)
pan : The Pan value in 10ths of degre... | [
"def",
"ptz_status_send",
"(",
"self",
",",
"zoom",
",",
"pan",
",",
"tilt",
",",
"force_mavlink1",
"=",
"False",
")",
":",
"return",
"self",
".",
"send",
"(",
"self",
".",
"ptz_status_encode",
"(",
"zoom",
",",
"pan",
",",
"tilt",
")",
",",
"force_mav... | 53.6 | 0.011009 |
def mchirp_sampler_lnm(**kwargs):
''' Draw chirp mass samples for uniform-in-log model
Parameters
----------
**kwargs: string
Keyword arguments as model parameters and number of samples
Returns
-------
mchirp-astro: array
The chirp mass samples... | [
"def",
"mchirp_sampler_lnm",
"(",
"*",
"*",
"kwargs",
")",
":",
"m1",
",",
"m2",
"=",
"draw_lnm_samples",
"(",
"*",
"*",
"kwargs",
")",
"mchirp_astro",
"=",
"mchirp_from_mass1_mass2",
"(",
"m1",
",",
"m2",
")",
"return",
"mchirp_astro"
] | 26.294118 | 0.00216 |
def add_masquerade(zone=None, permanent=True):
'''
Enable masquerade on a zone.
If zone is omitted, default zone will be used.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.add_masquerade
To enable masquerade on a specific zone
.. code-bloc... | [
"def",
"add_masquerade",
"(",
"zone",
"=",
"None",
",",
"permanent",
"=",
"True",
")",
":",
"if",
"zone",
":",
"cmd",
"=",
"'--zone={0} --add-masquerade'",
".",
"format",
"(",
"zone",
")",
"else",
":",
"cmd",
"=",
"'--add-masquerade'",
"if",
"permanent",
"... | 19.642857 | 0.001733 |
def _represent_ordereddict(dump, tag, mapping, flow_style=None):
"""PyYAML representer function for OrderedDict.
This is needed for yaml.safe_dump() to support OrderedDict.
Courtesy:
https://blog.elsdoerfer.name/2012/07/26/make-pyyaml-output-an-ordereddict/
"""
value = []
node = yaml.Mappin... | [
"def",
"_represent_ordereddict",
"(",
"dump",
",",
"tag",
",",
"mapping",
",",
"flow_style",
"=",
"None",
")",
":",
"value",
"=",
"[",
"]",
"node",
"=",
"yaml",
".",
"MappingNode",
"(",
"tag",
",",
"value",
",",
"flow_style",
"=",
"flow_style",
")",
"i... | 41 | 0.000794 |
def serialize(self, method="urlencoded", lev=0, **kwargs):
"""
Convert this instance to another representation. Which representation
is given by the choice of serialization method.
:param method: A serialization method. Presently 'urlencoded', 'json',
'jwt' and 'dic... | [
"def",
"serialize",
"(",
"self",
",",
"method",
"=",
"\"urlencoded\"",
",",
"lev",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"getattr",
"(",
"self",
",",
"\"to_%s\"",
"%",
"method",
")",
"(",
"lev",
"=",
"lev",
",",
"*",
"*",
"kwargs",... | 45.833333 | 0.008913 |
def get_shutit_pexpect_sessions(self, note=None):
"""Returns all the shutit_pexpect_session keys for this object.
@return: list of all shutit_pexpect_session keys (pexpect_session_ids)
"""
self.handle_note(note)
sessions = []
for key in self.shutit_pexpect_sessions:
sessions.append(shutit_object.shutit_... | [
"def",
"get_shutit_pexpect_sessions",
"(",
"self",
",",
"note",
"=",
"None",
")",
":",
"self",
".",
"handle_note",
"(",
"note",
")",
"sessions",
"=",
"[",
"]",
"for",
"key",
"in",
"self",
".",
"shutit_pexpect_sessions",
":",
"sessions",
".",
"append",
"(",... | 34.636364 | 0.028133 |
def handle_rereduce(self, reduce_function_names, values):
"""Re-reduce a set of values, with a list of rereduction functions."""
# This gets a large list of reduction functions, given their names.
reduce_functions = []
for reduce_function_name in reduce_function_names:
try:
... | [
"def",
"handle_rereduce",
"(",
"self",
",",
"reduce_function_names",
",",
"values",
")",
":",
"# This gets a large list of reduction functions, given their names.",
"reduce_functions",
"=",
"[",
"]",
"for",
"reduce_function_name",
"in",
"reduce_function_names",
":",
"try",
... | 48.272727 | 0.001847 |
def _dist_wrapper():
"""Add temporary distribution build files (and then clean up)."""
try:
# Copy select *.rst files to *.txt for build.
for rst_file, txt_file in zip(SDIST_RST_FILES, SDIST_TXT_FILES):
local("cp %s %s" % (rst_file, txt_file))
# Perform action.
yield... | [
"def",
"_dist_wrapper",
"(",
")",
":",
"try",
":",
"# Copy select *.rst files to *.txt for build.",
"for",
"rst_file",
",",
"txt_file",
"in",
"zip",
"(",
"SDIST_RST_FILES",
",",
"SDIST_TXT_FILES",
")",
":",
"local",
"(",
"\"cp %s %s\"",
"%",
"(",
"rst_file",
",",
... | 35 | 0.002141 |
def connect(dbapi_connection, connection_record):
"""
Called once by SQLAlchemy for each new SQLite DB-API connection.
Here is where we issue some PRAGMA statements to configure how we're
going to access the SQLite database.
@param dbapi_connection:
A newly connecte... | [
"def",
"connect",
"(",
"dbapi_connection",
",",
"connection_record",
")",
":",
"try",
":",
"cursor",
"=",
"dbapi_connection",
".",
"cursor",
"(",
")",
"try",
":",
"cursor",
".",
"execute",
"(",
"\"PRAGMA foreign_keys = ON;\"",
")",
"cursor",
".",
"execute",
"(... | 33.36 | 0.002331 |
def create(cls, name, certificate):
"""
Create a new external VPN CA for signing internal gateway
certificates.
:param str name: Name of VPN CA
:param str certificate: file name, path or certificate string.
:raises CreateElementFailed: Failed creating cert with r... | [
"def",
"create",
"(",
"cls",
",",
"name",
",",
"certificate",
")",
":",
"json",
"=",
"{",
"'name'",
":",
"name",
",",
"'certificate'",
":",
"certificate",
"}",
"return",
"ElementCreator",
"(",
"cls",
",",
"json",
")"
] | 34.357143 | 0.008097 |
def write_force_constants_to_hdf5(force_constants,
filename='force_constants.hdf5',
p2s_map=None,
physical_unit=None,
compression=None):
"""Write force constants in hdf5 format.
... | [
"def",
"write_force_constants_to_hdf5",
"(",
"force_constants",
",",
"filename",
"=",
"'force_constants.hdf5'",
",",
"p2s_map",
"=",
"None",
",",
"physical_unit",
"=",
"None",
",",
"compression",
"=",
"None",
")",
":",
"try",
":",
"import",
"h5py",
"except",
"Im... | 35.642857 | 0.00065 |
def filter_paths(pathnames,
included_patterns=None,
excluded_patterns=None,
case_sensitive=True):
"""
Filters from a set of paths based on acceptable patterns and
ignorable patterns.
:param pathnames:
A list of path names that will be filtered ... | [
"def",
"filter_paths",
"(",
"pathnames",
",",
"included_patterns",
"=",
"None",
",",
"excluded_patterns",
"=",
"None",
",",
"case_sensitive",
"=",
"True",
")",
":",
"included",
"=",
"[",
"\"*\"",
"]",
"if",
"included_patterns",
"is",
"None",
"else",
"included_... | 44.47619 | 0.001572 |
def timeout_exponential_backoff(
retries: int,
timeout: int,
maximum: int,
) -> Iterator[int]:
""" Timeouts generator with an exponential backoff strategy.
Timeouts start spaced by `timeout`, after `retries` exponentially increase
the retry delays until `maximum`, then maximum is re... | [
"def",
"timeout_exponential_backoff",
"(",
"retries",
":",
"int",
",",
"timeout",
":",
"int",
",",
"maximum",
":",
"int",
",",
")",
"->",
"Iterator",
"[",
"int",
"]",
":",
"yield",
"timeout",
"tries",
"=",
"1",
"while",
"tries",
"<",
"retries",
":",
"t... | 24.434783 | 0.001712 |
def is_merged(self):
"""
:calls: `GET /repos/:owner/:repo/pulls/:number/merge <http://developer.github.com/v3/pulls>`_
:rtype: bool
"""
status, headers, data = self._requester.requestJson(
"GET",
self.url + "/merge"
)
return status == 204 | [
"def",
"is_merged",
"(",
"self",
")",
":",
"status",
",",
"headers",
",",
"data",
"=",
"self",
".",
"_requester",
".",
"requestJson",
"(",
"\"GET\"",
",",
"self",
".",
"url",
"+",
"\"/merge\"",
")",
"return",
"status",
"==",
"204"
] | 30.9 | 0.009434 |
def _transform_gradients(self, g):
"""
Transform the gradients by multiplying the gradient factor for each
constraint to it.
"""
#py3 fix
#[np.put(g, i, c.gradfactor(self.param_array[i], g[i])) for c, i in self.constraints.iteritems() if c != __fixed__]
[np.put(g,... | [
"def",
"_transform_gradients",
"(",
"self",
",",
"g",
")",
":",
"#py3 fix",
"#[np.put(g, i, c.gradfactor(self.param_array[i], g[i])) for c, i in self.constraints.iteritems() if c != __fixed__]",
"[",
"np",
".",
"put",
"(",
"g",
",",
"i",
",",
"c",
".",
"gradfactor",
"(",
... | 48.1 | 0.014286 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.