text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def set_who(voevent, date=None, author_ivorn=None):
"""Sets the minimal 'Who' attributes: date of authoring, AuthorIVORN.
Args:
voevent(:class:`Voevent`): Root node of a VOEvent etree.
date(datetime.datetime): Date of authoring.
NB Microseconds are ignored, as per the VOEvent spec.... | [
"def",
"set_who",
"(",
"voevent",
",",
"date",
"=",
"None",
",",
"author_ivorn",
"=",
"None",
")",
":",
"if",
"author_ivorn",
"is",
"not",
"None",
":",
"voevent",
".",
"Who",
".",
"AuthorIVORN",
"=",
"''",
".",
"join",
"(",
"(",
"'ivo://'",
",",
"aut... | 42.5625 | 19.375 |
def with_metaclass(meta, *bases):
"""copied from https://github.com/Byron/bcore/blob/master/src/python/butility/future.py#L15"""
class metaclass(meta):
__call__ = type.__call__
__init__ = type.__init__
def __new__(cls, name, nbases, d):
if nbases is None:
ret... | [
"def",
"with_metaclass",
"(",
"meta",
",",
"*",
"bases",
")",
":",
"class",
"metaclass",
"(",
"meta",
")",
":",
"__call__",
"=",
"type",
".",
"__call__",
"__init__",
"=",
"type",
".",
"__init__",
"def",
"__new__",
"(",
"cls",
",",
"name",
",",
"nbases"... | 46.733333 | 14.6 |
def draw(self, data):
"""Display decoded characters at the current cursor position and
advances the cursor if :data:`~pyte.modes.DECAWM` is set.
:param str data: text to display.
.. versionchanged:: 0.5.0
Character width is taken into account. Specifically, zero-width
... | [
"def",
"draw",
"(",
"self",
",",
"data",
")",
":",
"data",
"=",
"data",
".",
"translate",
"(",
"self",
".",
"g1_charset",
"if",
"self",
".",
"charset",
"else",
"self",
".",
"g0_charset",
")",
"for",
"char",
"in",
"data",
":",
"char_width",
"=",
"wcwi... | 46.742424 | 21.969697 |
def vcenter_connect(self):
"""
Attempt to connect to vCenter
:return:
"""
try:
si = SmartConnect(
host=self.host,
user=self.user,
pwd=self.password,
port=self.port)
# disconnect vc
... | [
"def",
"vcenter_connect",
"(",
"self",
")",
":",
"try",
":",
"si",
"=",
"SmartConnect",
"(",
"host",
"=",
"self",
".",
"host",
",",
"user",
"=",
"self",
".",
"user",
",",
"pwd",
"=",
"self",
".",
"password",
",",
"port",
"=",
"self",
".",
"port",
... | 29.411765 | 12.235294 |
def refresh_image(self):
"""Get the most recent camera image."""
url = str.replace(CONST.TIMELINE_IMAGES_ID_URL,
'$DEVID$', self.device_id)
response = self._abode.send_request("get", url)
_LOGGER.debug("Get image response: %s", response.text)
return se... | [
"def",
"refresh_image",
"(",
"self",
")",
":",
"url",
"=",
"str",
".",
"replace",
"(",
"CONST",
".",
"TIMELINE_IMAGES_ID_URL",
",",
"'$DEVID$'",
",",
"self",
".",
"device_id",
")",
"response",
"=",
"self",
".",
"_abode",
".",
"send_request",
"(",
"\"get\""... | 40.333333 | 20.888889 |
def docx_text_from_xml(xml: str, config: TextProcessingConfig) -> str:
"""
Converts an XML tree of a DOCX file to string contents.
Args:
xml: raw XML text
config: :class:`TextProcessingConfig` control object
Returns:
contents as a string
"""
root = ElementTree.fromstrin... | [
"def",
"docx_text_from_xml",
"(",
"xml",
":",
"str",
",",
"config",
":",
"TextProcessingConfig",
")",
"->",
"str",
":",
"root",
"=",
"ElementTree",
".",
"fromstring",
"(",
"xml",
")",
"return",
"docx_text_from_xml_node",
"(",
"root",
",",
"0",
",",
"config",... | 28.153846 | 19.076923 |
def visit(self, node):
'''The main visit function. Visits the passed-in node and calls
finalize.
'''
for token in self.itervisit(node):
pass
result = self.finalize()
if result is not self:
return result | [
"def",
"visit",
"(",
"self",
",",
"node",
")",
":",
"for",
"token",
"in",
"self",
".",
"itervisit",
"(",
"node",
")",
":",
"pass",
"result",
"=",
"self",
".",
"finalize",
"(",
")",
"if",
"result",
"is",
"not",
"self",
":",
"return",
"result"
] | 29.555556 | 17.777778 |
def _deep_tuple(self, x):
"""Converts nested `tuple`, `list`, or `dict` to nested `tuple`."""
if isinstance(x, dict):
return self._deep_tuple(tuple(sorted(x.items())))
elif isinstance(x, (list, tuple)):
return tuple(map(self._deep_tuple, x))
return x | [
"def",
"_deep_tuple",
"(",
"self",
",",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"dict",
")",
":",
"return",
"self",
".",
"_deep_tuple",
"(",
"tuple",
"(",
"sorted",
"(",
"x",
".",
"items",
"(",
")",
")",
")",
")",
"elif",
"isinstance",
... | 34 | 14.625 |
def putkeyword(self, keyword, value, makesubrecord=False):
"""Put the value of a column keyword.
(see :func:`table.putcolkeyword`)"""
return self._table.putcolkeyword(self._column, keyword, value, makesubrecord) | [
"def",
"putkeyword",
"(",
"self",
",",
"keyword",
",",
"value",
",",
"makesubrecord",
"=",
"False",
")",
":",
"return",
"self",
".",
"_table",
".",
"putcolkeyword",
"(",
"self",
".",
"_column",
",",
"keyword",
",",
"value",
",",
"makesubrecord",
")"
] | 58 | 15.75 |
def get_config(self, key_name):
"""
Return configuration value
Args:
key_name (str): configuration key
Returns:
The value for the specified configuration key, or if not found
in the config the default value specified in the Configuration Handler
... | [
"def",
"get_config",
"(",
"self",
",",
"key_name",
")",
":",
"if",
"key_name",
"in",
"self",
".",
"config",
":",
"return",
"self",
".",
"config",
".",
"get",
"(",
"key_name",
")",
"return",
"self",
".",
"Configuration",
".",
"default",
"(",
"key_name",
... | 31.6875 | 19.1875 |
def find_gui_and_backend(gui=None):
"""Given a gui string return the gui and mpl backend.
Parameters
----------
gui : str
Can be one of ('tk','gtk','wx','qt','qt4','inline').
Returns
-------
A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg',
'WXAgg','Qt4Agg','... | [
"def",
"find_gui_and_backend",
"(",
"gui",
"=",
"None",
")",
":",
"import",
"matplotlib",
"if",
"gui",
"and",
"gui",
"!=",
"'auto'",
":",
"# select backend based on requested gui",
"backend",
"=",
"backends",
"[",
"gui",
"]",
"else",
":",
"backend",
"=",
"matp... | 30.56 | 22.32 |
def cancel(self, campaign_id):
"""
Cancel a Regular or Plain-Text Campaign after you send, before all of
your recipients receive it. This feature is included with MailChimp
Pro.
:param campaign_id: The unique id for the campaign.
:type campaign_id: :py:class:`str`
... | [
"def",
"cancel",
"(",
"self",
",",
"campaign_id",
")",
":",
"self",
".",
"campaign_id",
"=",
"campaign_id",
"return",
"self",
".",
"_mc_client",
".",
"_post",
"(",
"url",
"=",
"self",
".",
"_build_path",
"(",
"campaign_id",
",",
"'actions/cancel-send'",
")",... | 40.818182 | 20.636364 |
def to_dict(self):
'''Save this preceding condition into a dictionary.'''
d = super(Preceding, self).to_dict()
e = {}
if self.timeout != 0:
e['timeout'] = self.timeout
if self.sending_timing:
e['sendingTiming'] = self.sending_timing
pcs = []
... | [
"def",
"to_dict",
"(",
"self",
")",
":",
"d",
"=",
"super",
"(",
"Preceding",
",",
"self",
")",
".",
"to_dict",
"(",
")",
"e",
"=",
"{",
"}",
"if",
"self",
".",
"timeout",
"!=",
"0",
":",
"e",
"[",
"'timeout'",
"]",
"=",
"self",
".",
"timeout",... | 33.333333 | 12.8 |
def diet_expert(x, hidden_size, params):
"""A two-layer feed-forward network with relu activation on hidden layer.
Uses diet variables.
Recomputes hidden layer on backprop to save activation memory.
Args:
x: a Tensor with shape [batch, io_size]
hidden_size: an integer
params: a diet variable HPara... | [
"def",
"diet_expert",
"(",
"x",
",",
"hidden_size",
",",
"params",
")",
":",
"@",
"fn_with_diet_vars",
"(",
"params",
")",
"def",
"diet_expert_internal",
"(",
"x",
")",
":",
"dim",
"=",
"x",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"[",
... | 28.708333 | 18.291667 |
def _handle_root():
"""Handles index.html requests."""
res_filename = os.path.join(
os.path.dirname(__file__), _PROFILE_HTML)
with io.open(res_filename, 'rb') as res_file:
content = res_file.read()
return content, 'text/html' | [
"def",
"_handle_root",
"(",
")",
":",
"res_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"_PROFILE_HTML",
")",
"with",
"io",
".",
"open",
"(",
"res_filename",
",",
"'rb'",
")",
"as"... | 39.285714 | 8.428571 |
def set_color_in_grid(self, color_in_grid):
"""Set the pixel at the position of the :paramref:`color_in_grid`
to its color.
:param color_in_grid: must have the following attributes:
- ``color`` is the :ref:`color <png-color>` to set the pixel to
- ``x`` is the x position of... | [
"def",
"set_color_in_grid",
"(",
"self",
",",
"color_in_grid",
")",
":",
"self",
".",
"_set_pixel_and_convert_color",
"(",
"color_in_grid",
".",
"x",
",",
"color_in_grid",
".",
"y",
",",
"color_in_grid",
".",
"color",
")"
] | 39.714286 | 19.285714 |
async def set_max_relative_mod(self, max_mod,
timeout=OTGW_DEFAULT_TIMEOUT):
"""
Override the maximum relative modulation from the thermostat.
Valid values are 0 through 100. Clear the setting by specifying
a non-numeric value.
Return the newly ... | [
"async",
"def",
"set_max_relative_mod",
"(",
"self",
",",
"max_mod",
",",
"timeout",
"=",
"OTGW_DEFAULT_TIMEOUT",
")",
":",
"if",
"isinstance",
"(",
"max_mod",
",",
"int",
")",
"and",
"not",
"0",
"<=",
"max_mod",
"<=",
"100",
":",
"return",
"None",
"cmd",
... | 37.083333 | 16.333333 |
def install_caller_instruction(self, token_type="Unrestricted",
transaction_id=None):
"""
Set us up as a caller
This will install a new caller_token into the FPS section.
This should really only be called to regenerate the caller token.
"""
... | [
"def",
"install_caller_instruction",
"(",
"self",
",",
"token_type",
"=",
"\"Unrestricted\"",
",",
"transaction_id",
"=",
"None",
")",
":",
"response",
"=",
"self",
".",
"install_payment_instruction",
"(",
"\"MyRole=='Caller';\"",
",",
"token_type",
"=",
"token_type",... | 46.68 | 18.04 |
def OnViewFrozen(self, event):
"""Show cells as frozen status"""
self.grid._view_frozen = not self.grid._view_frozen
self.grid.grid_renderer.cell_cache.clear()
self.grid.ForceRefresh()
event.Skip() | [
"def",
"OnViewFrozen",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"grid",
".",
"_view_frozen",
"=",
"not",
"self",
".",
"grid",
".",
"_view_frozen",
"self",
".",
"grid",
".",
"grid_renderer",
".",
"cell_cache",
".",
"clear",
"(",
")",
"self",
".... | 25.777778 | 20.777778 |
def smiles_to_compound(smiles, assign_descriptors=True):
"""Convert SMILES text to compound object
Raises:
ValueError: SMILES with unsupported format
"""
it = iter(smiles)
mol = molecule()
try:
for token in it:
mol(token)
result, _ = mol(None)
except ... | [
"def",
"smiles_to_compound",
"(",
"smiles",
",",
"assign_descriptors",
"=",
"True",
")",
":",
"it",
"=",
"iter",
"(",
"smiles",
")",
"mol",
"=",
"molecule",
"(",
")",
"try",
":",
"for",
"token",
"in",
"it",
":",
"mol",
"(",
"token",
")",
"result",
",... | 27.684211 | 16.105263 |
def write_switch(self, module_address, state, callback_fn):
"""Set relay state."""
_LOGGER.info("write_switch: setstate,{},{}{}"
.format(module_address, str(state), chr(13)))
self.subscribe("state," + module_address, callback_fn)
self.send("setstate,{},{}{}"
... | [
"def",
"write_switch",
"(",
"self",
",",
"module_address",
",",
"state",
",",
"callback_fn",
")",
":",
"_LOGGER",
".",
"info",
"(",
"\"write_switch: setstate,{},{}{}\"",
".",
"format",
"(",
"module_address",
",",
"str",
"(",
"state",
")",
",",
"chr",
"(",
"1... | 53.571429 | 15.714286 |
def xmlobject_to_dict(instance, fields=None, exclude=None, prefix=''):
"""
Generate a dictionary based on the data in an XmlObject instance to pass as
a Form's ``initial`` keyword argument.
:param instance: instance of :class:`~eulxml.xmlmap.XmlObject`
:param fields: optional list of fields - if sp... | [
"def",
"xmlobject_to_dict",
"(",
"instance",
",",
"fields",
"=",
"None",
",",
"exclude",
"=",
"None",
",",
"prefix",
"=",
"''",
")",
":",
"data",
"=",
"{",
"}",
"# convert prefix to combining form for convenience",
"if",
"prefix",
":",
"prefix",
"=",
"'%s-'",
... | 40.263158 | 20.263158 |
def write_outro (self):
"""Write outro comments."""
self.stoptime = time.time()
duration = self.stoptime - self.starttime
self.comment(_("Stopped checking at %(time)s (%(duration)s)") %
{"time": strformat.strtime(self.stoptime),
"duration": strformat.strduratio... | [
"def",
"write_outro",
"(",
"self",
")",
":",
"self",
".",
"stoptime",
"=",
"time",
".",
"time",
"(",
")",
"duration",
"=",
"self",
".",
"stoptime",
"-",
"self",
".",
"starttime",
"self",
".",
"comment",
"(",
"_",
"(",
"\"Stopped checking at %(time)s (%(dur... | 47.428571 | 14.428571 |
def create_volume(self, volume_name: str, driver_spec: str = None):
"""Create new docker volumes.
Only the manager nodes can create a volume
Args:
volume_name (string): Name for the new docker volume
driver_spec (string): Driver for the docker volume
"""
... | [
"def",
"create_volume",
"(",
"self",
",",
"volume_name",
":",
"str",
",",
"driver_spec",
":",
"str",
"=",
"None",
")",
":",
"# Default values",
"if",
"driver_spec",
":",
"driver",
"=",
"driver_spec",
"else",
":",
"driver",
"=",
"'local'",
"# Raise an exception... | 32.904762 | 20.904762 |
def model_eval(sess, x, y, predictions, X_test=None, Y_test=None,
feed=None, args=None):
"""
Compute the accuracy of a TF model on some data
:param sess: TF session to use
:param x: input placeholder
:param y: output placeholder (for labels)
:param predictions: model output predictions
:par... | [
"def",
"model_eval",
"(",
"sess",
",",
"x",
",",
"y",
",",
"predictions",
",",
"X_test",
"=",
"None",
",",
"Y_test",
"=",
"None",
",",
"feed",
"=",
"None",
",",
"args",
"=",
"None",
")",
":",
"global",
"_model_eval_cache",
"args",
"=",
"_ArgsWrapper",
... | 35.891892 | 16.243243 |
def initialize_worker(self, process_num=None):
"""
reinitialize consumer for process in multiprocesing
"""
self.initialize(self.grid, self.num_of_paths, self.seed) | [
"def",
"initialize_worker",
"(",
"self",
",",
"process_num",
"=",
"None",
")",
":",
"self",
".",
"initialize",
"(",
"self",
".",
"grid",
",",
"self",
".",
"num_of_paths",
",",
"self",
".",
"seed",
")"
] | 38.2 | 9.8 |
def add_alias(self, entry):
""" Adds id to the current list 'aliased_by'
"""
assert isinstance(entry, SymbolVAR)
self.aliased_by.append(entry) | [
"def",
"add_alias",
"(",
"self",
",",
"entry",
")",
":",
"assert",
"isinstance",
"(",
"entry",
",",
"SymbolVAR",
")",
"self",
".",
"aliased_by",
".",
"append",
"(",
"entry",
")"
] | 34 | 3.8 |
def group_id(self):
"""
Returns the @GROUPID.
If derived_from is set, returns that group_id.
"""
if self.derived_from is not None:
return self.derived_from.group_id()
if self.file_uuid is None:
return None
return utils.GROUP_ID_PREFIX + se... | [
"def",
"group_id",
"(",
"self",
")",
":",
"if",
"self",
".",
"derived_from",
"is",
"not",
"None",
":",
"return",
"self",
".",
"derived_from",
".",
"group_id",
"(",
")",
"if",
"self",
".",
"file_uuid",
"is",
"None",
":",
"return",
"None",
"return",
"uti... | 29.272727 | 11.818182 |
def getLeastUsedCell(self, c):
"""For the least used cell in a column"""
segmentsPerCell = numpy.zeros(self.cellsPerColumn, dtype='uint32')
for i in range(self.cellsPerColumn):
segmentsPerCell[i] = self.getNumSegmentsInCell(c,i)
cellMinUsage = numpy.where(segmentsPerCell==segmentsPerCell.min())[0... | [
"def",
"getLeastUsedCell",
"(",
"self",
",",
"c",
")",
":",
"segmentsPerCell",
"=",
"numpy",
".",
"zeros",
"(",
"self",
".",
"cellsPerColumn",
",",
"dtype",
"=",
"'uint32'",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"cellsPerColumn",
")",
":",
... | 46.416667 | 21 |
def delete_free_shipping_promotion_by_id(cls, free_shipping_promotion_id, **kwargs):
"""Delete FreeShippingPromotion
Delete an instance of FreeShippingPromotion by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=Tr... | [
"def",
"delete_free_shipping_promotion_by_id",
"(",
"cls",
",",
"free_shipping_promotion_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
... | 49.809524 | 27.809524 |
def make_ring_dict(self, galkey):
""" Make a dictionary mapping the merged component names to list of template files
Parameters
----------
galkey : str
Unique key for this ring dictionary
Returns `model_component.GalpropMergedRingInfo`
"""
galprop_r... | [
"def",
"make_ring_dict",
"(",
"self",
",",
"galkey",
")",
":",
"galprop_rings",
"=",
"self",
".",
"read_galprop_rings_yaml",
"(",
"galkey",
")",
"galprop_run",
"=",
"galprop_rings",
"[",
"'galprop_run'",
"]",
"ring_limits",
"=",
"galprop_rings",
"[",
"'ring_limits... | 46.486486 | 19.054054 |
def compile(self):
"""
Build the abstract Parsley tree starting from the root node
(recursive)
"""
if not isinstance(self.parselet, dict):
raise ValueError("Parselet must be a dict of some sort. Or use .from_jsonstring(), " \
".from_jsonfile(), .from_y... | [
"def",
"compile",
"(",
"self",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"parselet",
",",
"dict",
")",
":",
"raise",
"ValueError",
"(",
"\"Parselet must be a dict of some sort. Or use .from_jsonstring(), \"",
"\".from_jsonfile(), .from_yamlstring(), or .from_ya... | 44.888889 | 20.888889 |
def hume_process_jsonld():
"""Process Hume JSON-LD and return INDRA Statements."""
if request.method == 'OPTIONS':
return {}
response = request.body.read().decode('utf-8')
body = json.loads(response)
jsonld_str = body.get('jsonld')
jsonld = json.loads(jsonld_str)
hp = hume.process_js... | [
"def",
"hume_process_jsonld",
"(",
")",
":",
"if",
"request",
".",
"method",
"==",
"'OPTIONS'",
":",
"return",
"{",
"}",
"response",
"=",
"request",
".",
"body",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"body",
"=",
"json",
".",
"lo... | 35.5 | 8.4 |
def permissions_for(self, member):
"""Handles permission resolution for the current :class:`Member`.
This function takes into consideration the following cases:
- Guild owner
- Guild roles
- Channel overrides
- Member overrides
Parameters
----------
... | [
"def",
"permissions_for",
"(",
"self",
",",
"member",
")",
":",
"# The current cases can be explained as:",
"# Guild owner get all permissions -- no questions asked. Otherwise...",
"# The @everyone role gets the first application.",
"# After that, the applied roles that the user has in the cha... | 36.663366 | 20.623762 |
def rmse(self):
"""Get RMSE for regression model evaluation results.
Returns:
the RMSE float number.
Raises:
Exception if the CSV headers do not include 'target' or 'predicted', or BigQuery
does not return 'target' or 'predicted' column, or if target or predicted is not
number.
... | [
"def",
"rmse",
"(",
"self",
")",
":",
"if",
"self",
".",
"_input_csv_files",
":",
"df",
"=",
"self",
".",
"_get_data_from_csv_files",
"(",
")",
"if",
"'target'",
"not",
"in",
"df",
"or",
"'predicted'",
"not",
"in",
"df",
":",
"raise",
"ValueError",
"(",
... | 33.483871 | 22.580645 |
def user_with_name(self, given_name=None, sn=None):
"""Get a unique user object by given name (first/nickname and last)."""
results = []
if sn and not given_name:
results = User.objects.filter(last_name=sn)
elif given_name:
query = {'first_name': given_name}
... | [
"def",
"user_with_name",
"(",
"self",
",",
"given_name",
"=",
"None",
",",
"sn",
"=",
"None",
")",
":",
"results",
"=",
"[",
"]",
"if",
"sn",
"and",
"not",
"given_name",
":",
"results",
"=",
"User",
".",
"objects",
".",
"filter",
"(",
"last_name",
"=... | 32.772727 | 15.727273 |
def register_alias(self, alias, key):
"""Aliases provide another accessor for the same key.
This enables one to change a name without breaking the application.
"""
alias = alias.lower()
key = key.lower()
if alias != key and alias != self._real_key(key):
exists... | [
"def",
"register_alias",
"(",
"self",
",",
"alias",
",",
"key",
")",
":",
"alias",
"=",
"alias",
".",
"lower",
"(",
")",
"key",
"=",
"key",
".",
"lower",
"(",
")",
"if",
"alias",
"!=",
"key",
"and",
"alias",
"!=",
"self",
".",
"_real_key",
"(",
"... | 41.647059 | 14.470588 |
def as_dict(self):
"""
Serializes the object necessary data in a dictionary.
:returns: Serialized data in a dictionary.
:rtype: dict
"""
result_dict = super(Profile, self).as_dict()
statuses = list()
version = None
titles = list()
descri... | [
"def",
"as_dict",
"(",
"self",
")",
":",
"result_dict",
"=",
"super",
"(",
"Profile",
",",
"self",
")",
".",
"as_dict",
"(",
")",
"statuses",
"=",
"list",
"(",
")",
"version",
"=",
"None",
"titles",
"=",
"list",
"(",
")",
"descriptions",
"=",
"list",... | 31.888889 | 13.355556 |
def _set_field(self, fieldname, bytestring, transfunc=None):
"""convienience function to set fields of the tinytag by name.
the payload (bytestring) can be changed using the transfunc"""
if getattr(self, fieldname): # do not overwrite existing data
return
value = bytestring ... | [
"def",
"_set_field",
"(",
"self",
",",
"fieldname",
",",
"bytestring",
",",
"transfunc",
"=",
"None",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"fieldname",
")",
":",
"# do not overwrite existing data",
"return",
"value",
"=",
"bytestring",
"if",
"transfunc... | 51.1 | 18.5 |
def update_parent_sequence_map(child_part, delete=False):
"""Updates the child map of a simple sequence assessment assessment part"""
if child_part.has_parent_part():
object_map = child_part.get_assessment_part()._my_map
database = 'assessment_authoring'
collection_type = 'AssessmentPart... | [
"def",
"update_parent_sequence_map",
"(",
"child_part",
",",
"delete",
"=",
"False",
")",
":",
"if",
"child_part",
".",
"has_parent_part",
"(",
")",
":",
"object_map",
"=",
"child_part",
".",
"get_assessment_part",
"(",
")",
".",
"_my_map",
"database",
"=",
"'... | 46.2 | 11.85 |
def file_handler(self, handler_type, path, prefixed_path, source_storage):
"""
Create a dict with all kwargs of the `copy_file` or `link_file` method of the super class and add it to
the queue for later processing.
"""
if self.faster:
if prefixed_path not in self.foun... | [
"def",
"file_handler",
"(",
"self",
",",
"handler_type",
",",
"path",
",",
"prefixed_path",
",",
"source_storage",
")",
":",
"if",
"self",
".",
"faster",
":",
"if",
"prefixed_path",
"not",
"in",
"self",
".",
"found_files",
":",
"self",
".",
"found_files",
... | 41.571429 | 20.047619 |
def count_het(self, allele=None, axis=None):
"""Count heterozygous genotypes.
Parameters
----------
allele : int, optional
Allele index.
axis : int, optional
Axis over which to count, or None to perform overall count.
"""
b = self.is_het(... | [
"def",
"count_het",
"(",
"self",
",",
"allele",
"=",
"None",
",",
"axis",
"=",
"None",
")",
":",
"b",
"=",
"self",
".",
"is_het",
"(",
"allele",
"=",
"allele",
")",
"return",
"np",
".",
"sum",
"(",
"b",
",",
"axis",
"=",
"axis",
")"
] | 27.538462 | 15.615385 |
def get_all(self, collection_name, since=None):
""" method returns all job records from a particular collection that are older than <since> """
if since is None:
query = {}
else:
query = {job.TIMEPERIOD: {'$gte': since}}
collection = self.ds.connection(collection_... | [
"def",
"get_all",
"(",
"self",
",",
"collection_name",
",",
"since",
"=",
"None",
")",
":",
"if",
"since",
"is",
"None",
":",
"query",
"=",
"{",
"}",
"else",
":",
"query",
"=",
"{",
"job",
".",
"TIMEPERIOD",
":",
"{",
"'$gte'",
":",
"since",
"}",
... | 47.5 | 20.583333 |
def create_choice(choice_list, help_string=NO_HELP, default=NO_DEFAULT):
# type: (List[str], str, Union[Any, NO_DEFAULT_TYPE]) -> str
"""
Create a choice config
:param choice_list:
:param help_string:
:param default:
:return:
"""
# noinspection PyT... | [
"def",
"create_choice",
"(",
"choice_list",
",",
"help_string",
"=",
"NO_HELP",
",",
"default",
"=",
"NO_DEFAULT",
")",
":",
"# type: (List[str], str, Union[Any, NO_DEFAULT_TYPE]) -> str",
"# noinspection PyTypeChecker",
"return",
"ParamChoice",
"(",
"help_string",
"=",
"he... | 30.466667 | 13.666667 |
def create_parser(subparsers):
'''
:param subparsers:
:return:
'''
parser = subparsers.add_parser(
'restart',
help='Restart a topology',
usage="%(prog)s [options] cluster/[role]/[env] <topology-name> [container-id]",
add_help=True)
args.add_titles(parser)
args.add_cluster_role_env... | [
"def",
"create_parser",
"(",
"subparsers",
")",
":",
"parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"'restart'",
",",
"help",
"=",
"'Restart a topology'",
",",
"usage",
"=",
"\"%(prog)s [options] cluster/[role]/[env] <topology-name> [container-id]\"",
",",
"add_help... | 22.5 | 22.142857 |
def compile_patterns_in_dictionary(dictionary):
"""
Replace all strings in dictionary with compiled
version of themselves and return dictionary.
"""
for key, value in dictionary.items():
if isinstance(value, str):
dictionary[key] = re.compile(value)
elif isinstance(value,... | [
"def",
"compile_patterns_in_dictionary",
"(",
"dictionary",
")",
":",
"for",
"key",
",",
"value",
"in",
"dictionary",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"dictionary",
"[",
"key",
"]",
"=",
"re",
".",
"c... | 35.363636 | 6.454545 |
def add_grid(self):
"""Add axis and ticks to figure.
Notes
-----
I know that visvis and pyqtgraphs can do this in much simpler way, but
those packages create too large a padding around the figure and this is
pretty fast.
"""
value = self.config.value
... | [
"def",
"add_grid",
"(",
"self",
")",
":",
"value",
"=",
"self",
".",
"config",
".",
"value",
"# X-AXIS",
"# x-bottom",
"self",
".",
"scene",
".",
"addLine",
"(",
"value",
"[",
"'x_min'",
"]",
",",
"value",
"[",
"'y_min'",
"]",
",",
"value",
"[",
"'x_... | 43.25 | 18.1875 |
def terminate(self, sigkill=False):
"""
Terminate (and then kill) the process launched to process the file.
:param sigkill: whether to issue a SIGKILL if SIGTERM doesn't work.
:type sigkill: bool
"""
if self._process is None:
raise AirflowException("Tried to ... | [
"def",
"terminate",
"(",
"self",
",",
"sigkill",
"=",
"False",
")",
":",
"if",
"self",
".",
"_process",
"is",
"None",
":",
"raise",
"AirflowException",
"(",
"\"Tried to call stop before starting!\"",
")",
"# The queue will likely get corrupted, so remove the reference",
... | 42.588235 | 16.588235 |
def time_boxed(func, iterable, time_budget, *args):
"""
Apply a function to the items of an iterable within a given time budget.
Loop the given iterable, calling the given function on each item. The expended
time is compared to the given time budget after each iteration.
"""
time_budget = time_... | [
"def",
"time_boxed",
"(",
"func",
",",
"iterable",
",",
"time_budget",
",",
"*",
"args",
")",
":",
"time_budget",
"=",
"time_budget",
"/",
"1000",
"# budget in milliseconds",
"start",
"=",
"time",
".",
"time",
"(",
")",
"for",
"thing",
"in",
"iterable",
":... | 36 | 21.777778 |
def detect_and_decorate(decorator, args, kwargs):
"""
Helper for applying a decorator when it is applied directly, and also
applying it when it is given arguments and then applied to a function.
"""
# special behavior when invoked with only one non-keyword argument: act as
# a normal decorator, ... | [
"def",
"detect_and_decorate",
"(",
"decorator",
",",
"args",
",",
"kwargs",
")",
":",
"# special behavior when invoked with only one non-keyword argument: act as",
"# a normal decorator, decorating and returning that argument with",
"# click.option",
"if",
"len",
"(",
"args",
")",
... | 40.148148 | 22.666667 |
def try_except_handler(self, node):
"""Handler for try except statement to ignore excepted exceptions."""
# List all excepted exception's names
excepted_types = []
for handler in node.handlers:
if handler.type is None:
excepted_types = None
bre... | [
"def",
"try_except_handler",
"(",
"self",
",",
"node",
")",
":",
"# List all excepted exception's names",
"excepted_types",
"=",
"[",
"]",
"for",
"handler",
"in",
"node",
".",
"handlers",
":",
"if",
"handler",
".",
"type",
"is",
"None",
":",
"excepted_types",
... | 38 | 18.970588 |
def seed_response(self, command, response):
# type: (Text, dict) -> MockAdapter
"""
Sets the response that the adapter will return for the specified
command.
You can seed multiple responses per command; the adapter will
put them into a FIFO queue. When a request comes i... | [
"def",
"seed_response",
"(",
"self",
",",
"command",
",",
"response",
")",
":",
"# type: (Text, dict) -> MockAdapter",
"if",
"command",
"not",
"in",
"self",
".",
"responses",
":",
"self",
".",
"responses",
"[",
"command",
"]",
"=",
"deque",
"(",
")",
"self",... | 32.571429 | 21.214286 |
def set_stack(self, stack_dump, stack_top):
"""
Stack dump is a dump of the stack from gdb, i.e. the result of the following gdb command :
``dump binary memory [stack_dump] [begin_addr] [end_addr]``
We set the stack to the same addresses as the gdb session to avoid pointers corruption.... | [
"def",
"set_stack",
"(",
"self",
",",
"stack_dump",
",",
"stack_top",
")",
":",
"data",
"=",
"self",
".",
"_read_data",
"(",
"stack_dump",
")",
"self",
".",
"real_stack_top",
"=",
"stack_top",
"addr",
"=",
"stack_top",
"-",
"len",
"(",
"data",
")",
"# Ad... | 46.235294 | 24.941176 |
def _authenticate(secrets_file):
"""Runs the OAuth 2.0 installed application flow.
Returns:
An authorized httplib2.Http instance.
"""
flow = oauthclient.flow_from_clientsecrets(
secrets_file,
scope=OAUTH_SCOPE,
message=('Failed to initialized OAuth 2.0 flow with secrets '
... | [
"def",
"_authenticate",
"(",
"secrets_file",
")",
":",
"flow",
"=",
"oauthclient",
".",
"flow_from_clientsecrets",
"(",
"secrets_file",
",",
"scope",
"=",
"OAUTH_SCOPE",
",",
"message",
"=",
"(",
"'Failed to initialized OAuth 2.0 flow with secrets '",
"'file: %s'",
"%",... | 38.352941 | 15.294118 |
def patch_data(data, L=100, try_diag=True, verbose=False):
'''Patch ``data`` (for example Markov chain output) into parts of
length ``L``. Return a Gaussian mixture where each component gets
the empirical mean and covariance of one patch.
:param data:
Matrix-like array; the points to be patche... | [
"def",
"patch_data",
"(",
"data",
",",
"L",
"=",
"100",
",",
"try_diag",
"=",
"True",
",",
"verbose",
"=",
"False",
")",
":",
"# patch data into length L patches",
"patches",
"=",
"_np",
".",
"array",
"(",
"[",
"data",
"[",
"patch_start",
":",
"patch_start... | 36.910448 | 23.119403 |
def build_trading_timeline(start, end):
''' Build the daily-based index we will trade on '''
EMPTY_DATES = pd.date_range('2000/01/01', periods=0, tz=pytz.utc)
now = dt.datetime.now(tz=pytz.utc)
if not start:
if not end:
# Live trading until the end of the day
bt_dates = ... | [
"def",
"build_trading_timeline",
"(",
"start",
",",
"end",
")",
":",
"EMPTY_DATES",
"=",
"pd",
".",
"date_range",
"(",
"'2000/01/01'",
",",
"periods",
"=",
"0",
",",
"tz",
"=",
"pytz",
".",
"utc",
")",
"now",
"=",
"dt",
".",
"datetime",
".",
"now",
"... | 39.096774 | 13.645161 |
def find_urls(thing, base_url=None, mimetype=None, log=False):
""" This function uses several methods to extract URLs from 'thing', which can be a string or raw bytes.
If you supply the base URL, it will attempt to use it with urljoin to create full URLs from relative paths. """
if log:
logging... | [
"def",
"find_urls",
"(",
"thing",
",",
"base_url",
"=",
"None",
",",
"mimetype",
"=",
"None",
",",
"log",
"=",
"False",
")",
":",
"if",
"log",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"INFO",
",",
"format",
"=",
"'%(asct... | 38.128342 | 24.144385 |
def change_keyboard_control(self, onerror = None, **keys):
"""Change the parameters provided as keyword arguments:
key_click_percent
The volume of key clicks between 0 (off) and 100 (load).
-1 will restore default setting.
bell_percent
The base volume of the ... | [
"def",
"change_keyboard_control",
"(",
"self",
",",
"onerror",
"=",
"None",
",",
"*",
"*",
"keys",
")",
":",
"request",
".",
"ChangeKeyboardControl",
"(",
"display",
"=",
"self",
".",
"display",
",",
"onerror",
"=",
"onerror",
",",
"attrs",
"=",
"keys",
... | 42.551724 | 22.37931 |
def cli(env):
"""List object storage accounts."""
mgr = SoftLayer.ObjectStorageManager(env.client)
accounts = mgr.list_accounts()
table = formatting.Table(['id', 'name', 'apiType'])
table.sortby = 'id'
api_type = None
for account in accounts:
if 'vendorName' in account and account['... | [
"def",
"cli",
"(",
"env",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"ObjectStorageManager",
"(",
"env",
".",
"client",
")",
"accounts",
"=",
"mgr",
".",
"list_accounts",
"(",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'id'",
",",
"'name'",... | 27.952381 | 19.904762 |
def app_trim_memory(self, pid: int or str, level: str = 'RUNNING_LOW') -> None:
'''Trim memory.
Args:
level: HIDDEN | RUNNING_MODERATE | BACKGROUNDRUNNING_LOW | \
MODERATE | RUNNING_CRITICAL | COMPLETE
'''
_, error = self._execute('-s', self.device_sn, '... | [
"def",
"app_trim_memory",
"(",
"self",
",",
"pid",
":",
"int",
"or",
"str",
",",
"level",
":",
"str",
"=",
"'RUNNING_LOW'",
")",
"->",
"None",
":",
"_",
",",
"error",
"=",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'... | 46.727273 | 27.272727 |
def pad(self, minibatch):
"""Pad a batch of examples using this field.
Pads to self.fix_length if provided, otherwise pads to the length of
the longest example in the batch. Prepends self.init_token and appends
self.eos_token if those attributes are not None. Returns a tuple of the
... | [
"def",
"pad",
"(",
"self",
",",
"minibatch",
")",
":",
"minibatch",
"=",
"list",
"(",
"minibatch",
")",
"if",
"not",
"self",
".",
"sequential",
":",
"return",
"minibatch",
"if",
"self",
".",
"fix_length",
"is",
"None",
":",
"max_len",
"=",
"max",
"(",
... | 49.222222 | 21.805556 |
def update(self, id_equipment, id_environment, is_router):
"""Remove Related Equipment with Environment from by the identifier.
:param id_equipment: Identifier of the Equipment. Integer value and greater than zero.
:param id_environment: Identifier of the Environment. Integer value and greater ... | [
"def",
"update",
"(",
"self",
",",
"id_equipment",
",",
"id_environment",
",",
"is_router",
")",
":",
"if",
"not",
"is_valid_int_param",
"(",
"id_equipment",
")",
":",
"raise",
"InvalidParameterError",
"(",
"u'The identifier of Equipment is invalid or was not informed.'",... | 48.176471 | 28.441176 |
def __authorize(self, client_id, client_secret, credit_card_id, **kwargs):
"""Call documentation: `/credit_card/authorize
<https://www.wepay.com/developer/reference/credit_card#authorize>`_,
plus extra keyword parameter:
:keyword bool batch_mode: turn on/off the batch_mode, see ... | [
"def",
"__authorize",
"(",
"self",
",",
"client_id",
",",
"client_secret",
",",
"credit_card_id",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'client_id'",
":",
"client_id",
",",
"'client_secret'",
":",
"client_secret",
",",
"'credit_card_id'",
":"... | 37.142857 | 19.190476 |
def get_single(self, key, lang=None):
""" Returns a single triple related to this node.
:param key: Predicate of the triple
:param lang: Language of the triple if applicable
:rtype: Literal or BNode or URIRef
"""
if not isinstance(key, URIRef):
key = URIRef(k... | [
"def",
"get_single",
"(",
"self",
",",
"key",
",",
"lang",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"key",
",",
"URIRef",
")",
":",
"key",
"=",
"URIRef",
"(",
"key",
")",
"if",
"lang",
"is",
"not",
"None",
":",
"default",
"=",
"None... | 32.25 | 13.35 |
def merge(self, samples_uuid):
"""
The method to merge the datamodels belonging to different references
:param samples_uuid: The unique identifier metadata column name to identify the identical samples having different references
:return: Returns the merged dataframe
"""
... | [
"def",
"merge",
"(",
"self",
",",
"samples_uuid",
")",
":",
"all_meta_data",
"=",
"pd",
".",
"DataFrame",
"(",
")",
"for",
"dm",
"in",
"self",
".",
"data_model",
":",
"all_meta_data",
"=",
"pd",
".",
"concat",
"(",
"[",
"all_meta_data",
",",
"dm",
".",... | 40.142857 | 23.971429 |
def setup(self, filters=()):
"""Sets up a cache of python interpreters.
:param filters: A sequence of strings that constrain the interpreter compatibility for this
cache, using the Requirement-style format, e.g. ``'CPython>=3', or just ['>=2.7','<3']``
for requirements agnostic to interpreter class... | [
"def",
"setup",
"(",
"self",
",",
"filters",
"=",
"(",
")",
")",
":",
"# We filter the interpreter cache itself (and not just the interpreters we pull from it)",
"# because setting up some python versions (e.g., 3<=python<3.3) crashes, and this gives us",
"# an escape hatch.",
"filters",... | 47.027027 | 28.513514 |
def J(self, log_sigma):
"""Return the sensitivity matrix
Parameters
----------
log_sigma : numpy.ndarray
log_e conductivities
"""
m = 1.0 / np.exp(log_sigma)
tdm = self._get_tdm(m)
tdm.model(
sensitivities=True,
# out... | [
"def",
"J",
"(",
"self",
",",
"log_sigma",
")",
":",
"m",
"=",
"1.0",
"/",
"np",
".",
"exp",
"(",
"log_sigma",
")",
"tdm",
"=",
"self",
".",
"_get_tdm",
"(",
"m",
")",
"tdm",
".",
"model",
"(",
"sensitivities",
"=",
"True",
",",
"# output_directory... | 29.734694 | 18.693878 |
def seek_write(path, data, offset):
'''
.. versionadded:: 2014.1.0
Seek to a position on a file and write to it
path
path to file
data
data to write to file
offset
position in file to start writing
CLI Example:
.. code-block:: bash
salt '*' file.see... | [
"def",
"seek_write",
"(",
"path",
",",
"data",
",",
"offset",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
"seek_fh",
"=",
"os",
".",
"open",
"(",
"path",
",",
"os",
".",
"O_WRONLY",
")",
"try",
":",
"os",
".",
... | 19.433333 | 22.766667 |
def component_mget(self, zip_data, components):
"""Call the zip component_mget endpoint
Args:
- zip_data - As described in the class docstring.
- components - A list of strings for each component to include in the request.
Example: ["zip/details", "zip/volatility... | [
"def",
"component_mget",
"(",
"self",
",",
"zip_data",
",",
"components",
")",
":",
"if",
"not",
"isinstance",
"(",
"components",
",",
"list",
")",
":",
"print",
"(",
"\"Components param must be a list\"",
")",
"return",
"query_params",
"=",
"{",
"\"components\"... | 37.75 | 20.25 |
def MoveToAttributeNo(self, no):
"""Moves the position of the current instance to the attribute
with the specified index relative to the containing element. """
ret = libxml2mod.xmlTextReaderMoveToAttributeNo(self._o, no)
return ret | [
"def",
"MoveToAttributeNo",
"(",
"self",
",",
"no",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlTextReaderMoveToAttributeNo",
"(",
"self",
".",
"_o",
",",
"no",
")",
"return",
"ret"
] | 52.4 | 11.6 |
def create(self, title, body, labels):
"""Create an issue in Github.
For JSON data returned by Github refer:
https://developer.github.com/v3/issues/#create-an-issue
:param title: title of the issue
:param body: body of the issue
:param labels: list of labels for the issu... | [
"def",
"create",
"(",
"self",
",",
"title",
",",
"body",
",",
"labels",
")",
":",
"url",
"=",
"\"https://api.github.com/repos/{}/{}/issues\"",
".",
"format",
"(",
"self",
".",
"user",
",",
"self",
".",
"repo",
")",
"data",
"=",
"{",
"'title'",
":",
"titl... | 29.777778 | 18.666667 |
def _format_numer(number_format, prefix='', suffix=''):
"""Format a number to a string."""
@_surpress_formatting_errors
def inner(v):
if isinstance(v, Number):
return ("{{}}{{:{}}}{{}}"
.format(number_format)
.format(prefix, v, suffix))
els... | [
"def",
"_format_numer",
"(",
"number_format",
",",
"prefix",
"=",
"''",
",",
"suffix",
"=",
"''",
")",
":",
"@",
"_surpress_formatting_errors",
"def",
"inner",
"(",
"v",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"Number",
")",
":",
"return",
"(",
"\... | 34.909091 | 11.818182 |
def get_names_in_namespace_page(namespace_id, offset, count, proxy=None, hostport=None):
"""
Get a page of names in a namespace
Returns the list of names on success
Returns {'error': ...} on error
"""
assert proxy or hostport, 'Need proxy or hostport'
if proxy is None:
proxy = connec... | [
"def",
"get_names_in_namespace_page",
"(",
"namespace_id",
",",
"offset",
",",
"count",
",",
"proxy",
"=",
"None",
",",
"hostport",
"=",
"None",
")",
":",
"assert",
"proxy",
"or",
"hostport",
",",
"'Need proxy or hostport'",
"if",
"proxy",
"is",
"None",
":",
... | 30.571429 | 22.4 |
def rewind(self):
"""
Put us back at the beginning of the file again.
"""
# Superclass rewind
super(FileRecordStream, self).rewind()
self.close()
self._file = open(self._filename, self._mode)
self._reader = csv.reader(self._file, dialect="excel")
# Skip header rows
self._reade... | [
"def",
"rewind",
"(",
"self",
")",
":",
"# Superclass rewind",
"super",
"(",
"FileRecordStream",
",",
"self",
")",
".",
"rewind",
"(",
")",
"self",
".",
"close",
"(",
")",
"self",
".",
"_file",
"=",
"open",
"(",
"self",
".",
"_filename",
",",
"self",
... | 21.894737 | 18.842105 |
def spawn_daemon(fork=None, pgrpfile=None, outfile='out.txt'):
'causes run to be executed in a newly spawned daemon process'
global LAST_PGRP_PATH
fork = fork or os.fork
open(outfile, 'a').close() # TODO: configurable output file
if pgrpfile and os.path.exists(pgrpfile):
try:
cu... | [
"def",
"spawn_daemon",
"(",
"fork",
"=",
"None",
",",
"pgrpfile",
"=",
"None",
",",
"outfile",
"=",
"'out.txt'",
")",
":",
"global",
"LAST_PGRP_PATH",
"fork",
"=",
"fork",
"or",
"os",
".",
"fork",
"open",
"(",
"outfile",
",",
"'a'",
")",
".",
"close",
... | 41.346154 | 18.192308 |
def global_workflow_add_authorized_users(name_or_id, alias=None, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /globalworkflow-xxxx/addAuthorizedUsers API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Global-Workflows#API-method:-/globalworkflow-xxxx%5B/yyy... | [
"def",
"global_workflow_add_authorized_users",
"(",
"name_or_id",
",",
"alias",
"=",
"None",
",",
"input_params",
"=",
"{",
"}",
",",
"always_retry",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"fully_qualified_version",
"=",
"name_or_id",
"+",
"(",
"(",
... | 68.5 | 46.75 |
def _getusers(self, ids=None, names=None, match=None):
"""
Return a list of users that match criteria.
:kwarg ids: list of user ids to return data on
:kwarg names: list of user names to return data on
:kwarg match: list of patterns. Returns users whose real name or
... | [
"def",
"_getusers",
"(",
"self",
",",
"ids",
"=",
"None",
",",
"names",
"=",
"None",
",",
"match",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"ids",
":",
"params",
"[",
"'ids'",
"]",
"=",
"self",
".",
"_listify",
"(",
"ids",
")",
"if... | 37.137931 | 18.172414 |
def get_centers(self, estimation):
"""Get estimation on centers
Parameters
----------
estimation : 1D arrary
Either prior of posterior estimation
Returns
-------
centers : 2D array, in shape [K, n_dim]
Estimation on centers
"""
... | [
"def",
"get_centers",
"(",
"self",
",",
"estimation",
")",
":",
"centers",
"=",
"estimation",
"[",
"0",
":",
"self",
".",
"map_offset",
"[",
"1",
"]",
"]",
".",
"reshape",
"(",
"self",
".",
"K",
",",
"self",
".",
"n_dim",
")",
"return",
"centers"
] | 23.222222 | 17.833333 |
def _dtype(cls, tensor: tf.Tensor) -> tf.Tensor:
'''Converts `tensor` to tf.float32 datatype if needed.'''
if tensor.dtype != tf.float32:
tensor = tf.cast(tensor, tf.float32)
return tensor | [
"def",
"_dtype",
"(",
"cls",
",",
"tensor",
":",
"tf",
".",
"Tensor",
")",
"->",
"tf",
".",
"Tensor",
":",
"if",
"tensor",
".",
"dtype",
"!=",
"tf",
".",
"float32",
":",
"tensor",
"=",
"tf",
".",
"cast",
"(",
"tensor",
",",
"tf",
".",
"float32",
... | 44 | 12.4 |
def H7(self):
"Sum variance (error in Haralick's original paper here)."
h6 = np.tile(self.H6(), (self.rlevels2.shape[1], 1)).transpose()
return (((self.rlevels2 + 2) - h6) ** 2 * self.p_xplusy).sum(1) | [
"def",
"H7",
"(",
"self",
")",
":",
"h6",
"=",
"np",
".",
"tile",
"(",
"self",
".",
"H6",
"(",
")",
",",
"(",
"self",
".",
"rlevels2",
".",
"shape",
"[",
"1",
"]",
",",
"1",
")",
")",
".",
"transpose",
"(",
")",
"return",
"(",
"(",
"(",
"... | 55.25 | 28.75 |
def exclude_candidates(self, candidates, reason):
"""
mark one or more candidates as excluded from the count
candidates: list of candidate_ids to exclude
reason: the reason for the exclusion
"""
# put some paranoia around exclusion: we want to make sure that
# `c... | [
"def",
"exclude_candidates",
"(",
"self",
",",
"candidates",
",",
"reason",
")",
":",
"# put some paranoia around exclusion: we want to make sure that",
"# `candidates` is unique, and that none of these candidates have",
"# been previously excluded",
"for",
"candidate_id",
"in",
"can... | 45.9375 | 19.5 |
def remote_sys_name_uneq_store(self, remote_system_name):
"""This function saves the system name, if different from stored. """
if remote_system_name != self.remote_system_name:
self.remote_system_name = remote_system_name
return True
return False | [
"def",
"remote_sys_name_uneq_store",
"(",
"self",
",",
"remote_system_name",
")",
":",
"if",
"remote_system_name",
"!=",
"self",
".",
"remote_system_name",
":",
"self",
".",
"remote_system_name",
"=",
"remote_system_name",
"return",
"True",
"return",
"False"
] | 48.333333 | 14.5 |
def unpublish(self):
"""
Unpublish this item.
This will set and currently published versions to
the archived state and delete all currently scheduled
versions.
"""
assert self.state == self.DRAFT
with xact():
self._publish(published=False)
... | [
"def",
"unpublish",
"(",
"self",
")",
":",
"assert",
"self",
".",
"state",
"==",
"self",
".",
"DRAFT",
"with",
"xact",
"(",
")",
":",
"self",
".",
"_publish",
"(",
"published",
"=",
"False",
")",
"# Delete all scheduled items",
"klass",
"=",
"self",
".",... | 29.941176 | 17.823529 |
def _construct_role(self, managed_policy_map):
"""Constructs a Lambda execution role based on this SAM function's Policies property.
:returns: the generated IAM Role
:rtype: model.iam.IAMRole
"""
execution_role = IAMRole(self.logical_id + 'Role', attributes=self.get_passthrough_... | [
"def",
"_construct_role",
"(",
"self",
",",
"managed_policy_map",
")",
":",
"execution_role",
"=",
"IAMRole",
"(",
"self",
".",
"logical_id",
"+",
"'Role'",
",",
"attributes",
"=",
"self",
".",
"get_passthrough_resource_attributes",
"(",
")",
")",
"execution_role"... | 50.590164 | 30.786885 |
def check_for_duplicate_assignments(participant):
"""Check that the assignment_id of the participant is unique.
If it isnt the older participants will be failed.
"""
participants = models.Participant.query.filter_by(
assignment_id=participant.assignment_id
).all()
duplicates = [
... | [
"def",
"check_for_duplicate_assignments",
"(",
"participant",
")",
":",
"participants",
"=",
"models",
".",
"Participant",
".",
"query",
".",
"filter_by",
"(",
"assignment_id",
"=",
"participant",
".",
"assignment_id",
")",
".",
"all",
"(",
")",
"duplicates",
"=... | 37.461538 | 19.923077 |
def ess(weights):
r"""Calculate the normalized effective sample size :math:`ESS` [LC95]_
of samples with ``weights`` :math:`\omega_i`. :math:`ESS=0` is
terrible and :math:`ESS=1` is perfect.
.. math::
ESS = \frac{1}{1+C^2}
where
.. math::
C^2 = \frac{1}{N} \sum_{i=1}^N (N \... | [
"def",
"ess",
"(",
"weights",
")",
":",
"# normalize weights",
"w",
"=",
"_np",
".",
"asarray",
"(",
"weights",
")",
"/",
"_np",
".",
"sum",
"(",
"weights",
")",
"# ess",
"coeff_var",
"=",
"_np",
".",
"sum",
"(",
"(",
"len",
"(",
"w",
")",
"*",
"... | 20.548387 | 25.677419 |
def format_files(src: str, dest: str, **fmt_vars: str) -> None:
"""Copies all files inside src into dest while formatting the contents
of the files into the output.
For example, a file with the following contents:
{foo} bar {baz}
and the vars {'foo': 'herp', 'baz': 'derp'}
will end up in the... | [
"def",
"format_files",
"(",
"src",
":",
"str",
",",
"dest",
":",
"str",
",",
"*",
"*",
"fmt_vars",
":",
"str",
")",
"->",
"None",
":",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"src",
")",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
... | 35.2 | 17.166667 |
def xml_path_completion(xml_path):
"""
Takes in a local xml path and returns a full path.
if @xml_path is absolute, do nothing
if @xml_path is not absolute, load xml that is shipped by the package
"""
if xml_path.startswith("/"):
full_path = xml_path
else:
full_path =... | [
"def",
"xml_path_completion",
"(",
"xml_path",
")",
":",
"if",
"xml_path",
".",
"startswith",
"(",
"\"/\"",
")",
":",
"full_path",
"=",
"xml_path",
"else",
":",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"robosuite",
".",
"models",
".",
"asse... | 34.909091 | 14.909091 |
def remove_run_script(self, script, target_name=None):
"""
Removes the given script string from the given target
:param script: The script string to be removed from the target
:param target_name: Target name or list of target names to remove the run script from or None for every target
... | [
"def",
"remove_run_script",
"(",
"self",
",",
"script",
",",
"target_name",
"=",
"None",
")",
":",
"for",
"target",
"in",
"self",
".",
"objects",
".",
"get_targets",
"(",
"target_name",
")",
":",
"for",
"build_phase_id",
"in",
"target",
".",
"buildPhases",
... | 48.5 | 21.625 |
def set_state(self, updater=None, **kwargs):
"""Update the datastore.
:param func|dict updater: (state) => state_change or dict state_change
:rtype: Iterable[tornado.concurrent.Future]
"""
if callable(updater):
state_change = updater(self)
elif updater is not... | [
"def",
"set_state",
"(",
"self",
",",
"updater",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"callable",
"(",
"updater",
")",
":",
"state_change",
"=",
"updater",
"(",
"self",
")",
"elif",
"updater",
"is",
"not",
"None",
":",
"state_change",
... | 33.1875 | 13.875 |
def get_shell(pid=None, max_depth=6):
"""Get the shell that the supplied pid or os.getpid() is running in.
"""
pid = str(pid or os.getpid())
mapping = _get_process_mapping()
for proc_cmd in _iter_process_command(mapping, pid, max_depth):
if proc_cmd.startswith('-'): # Login shell! Let's u... | [
"def",
"get_shell",
"(",
"pid",
"=",
"None",
",",
"max_depth",
"=",
"6",
")",
":",
"pid",
"=",
"str",
"(",
"pid",
"or",
"os",
".",
"getpid",
"(",
")",
")",
"mapping",
"=",
"_get_process_mapping",
"(",
")",
"for",
"proc_cmd",
"in",
"_iter_process_comman... | 44.75 | 12.166667 |
def strip_wsgi(request):
"""Strip WSGI data out of the request META data."""
meta = copy(request.META)
for key in meta:
if key[:4] == 'wsgi':
meta[key] = None
return meta | [
"def",
"strip_wsgi",
"(",
"request",
")",
":",
"meta",
"=",
"copy",
"(",
"request",
".",
"META",
")",
"for",
"key",
"in",
"meta",
":",
"if",
"key",
"[",
":",
"4",
"]",
"==",
"'wsgi'",
":",
"meta",
"[",
"key",
"]",
"=",
"None",
"return",
"meta"
] | 25 | 16.875 |
def itemData(self, item, column, role=Qt.DisplayRole):
""" Returns the data stored under the given role for the item. O
The column parameter may be used to differentiate behavior per column.
The default implementation does nothing. Descendants should typically override this
... | [
"def",
"itemData",
"(",
"self",
",",
"item",
",",
"column",
",",
"role",
"=",
"Qt",
".",
"DisplayRole",
")",
":",
"if",
"role",
"==",
"Qt",
".",
"DecorationRole",
":",
"if",
"column",
"==",
"self",
".",
"COL_DECORATION",
":",
"return",
"item",
".",
"... | 36.296296 | 20.925926 |
def tear_down(self):
"""Tear down the instance
"""
import boto.ec2
if not self.browser_config.get('terminate'):
self.warning_log("Skipping terminate")
return
self.info_log("Tearing down...")
ec2 = boto.ec2.connect_to_region(self.browser_config.g... | [
"def",
"tear_down",
"(",
"self",
")",
":",
"import",
"boto",
".",
"ec2",
"if",
"not",
"self",
".",
"browser_config",
".",
"get",
"(",
"'terminate'",
")",
":",
"self",
".",
"warning_log",
"(",
"\"Skipping terminate\"",
")",
"return",
"self",
".",
"info_log"... | 29.692308 | 20 |
def create(self, dcid, vpsplanid, osid, params=None):
''' /v1/server/create
POST - account
Create a new virtual machine. You will start being billed for this
immediately. The response only contains the SUBID for the new machine.
You should use v1/server/list to poll and wait for ... | [
"def",
"create",
"(",
"self",
",",
"dcid",
",",
"vpsplanid",
",",
"osid",
",",
"params",
"=",
"None",
")",
":",
"params",
"=",
"update_params",
"(",
"params",
",",
"{",
"'DCID'",
":",
"dcid",
",",
"'VPSPLANID'",
":",
"vpsplanid",
",",
"'OSID'",
":",
... | 40.4375 | 20.9375 |
def delete_enrollment_claim(self, id, **kwargs):
"""Delete"""
api = self._get_api(enrollment.PublicAPIApi)
return api.delete_device_enrollment(id=id) | [
"def",
"delete_enrollment_claim",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"api",
"=",
"self",
".",
"_get_api",
"(",
"enrollment",
".",
"PublicAPIApi",
")",
"return",
"api",
".",
"delete_device_enrollment",
"(",
"id",
"=",
"id",
")"
] | 42.5 | 7.5 |
def random_box(molecules, total=None, proportions=None, size=[1.,1.,1.], maxtries=100):
'''Create a System made of a series of random molecules.
Parameters:
total:
molecules:
proportions:
'''
# Setup proportions to be right
if proportions is None:
proportions = np.... | [
"def",
"random_box",
"(",
"molecules",
",",
"total",
"=",
"None",
",",
"proportions",
"=",
"None",
",",
"size",
"=",
"[",
"1.",
",",
"1.",
",",
"1.",
"]",
",",
"maxtries",
"=",
"100",
")",
":",
"# Setup proportions to be right",
"if",
"proportions",
"is"... | 33.31746 | 22.460317 |
def _hasattr(self, fieldname):
"""Returns True if this packet contains fieldname, False otherwise."""
special = 'history', 'raw'
return (fieldname in special or
fieldname in self._defn.fieldmap or
fieldname in self._defn.derivationmap) | [
"def",
"_hasattr",
"(",
"self",
",",
"fieldname",
")",
":",
"special",
"=",
"'history'",
",",
"'raw'",
"return",
"(",
"fieldname",
"in",
"special",
"or",
"fieldname",
"in",
"self",
".",
"_defn",
".",
"fieldmap",
"or",
"fieldname",
"in",
"self",
".",
"_de... | 47.833333 | 6.833333 |
def _list_objects(self, client_kwargs, max_request_entries):
"""
Lists objects.
args:
client_kwargs (dict): Client arguments.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
generator of tuple: o... | [
"def",
"_list_objects",
"(",
"self",
",",
"client_kwargs",
",",
"max_request_entries",
")",
":",
"client_kwargs",
"=",
"self",
".",
"_update_listing_client_kwargs",
"(",
"client_kwargs",
",",
"max_request_entries",
")",
"with",
"_handle_azure_exception",
"(",
")",
":"... | 35.75 | 20.35 |
def deserialize(raw):
"""Instantiate :py:class:`ofxclient.Institution` from dictionary
:param raw: serialized ``Institution``
:param type: dict per :py:method:`~Institution.serialize`
:rtype: subclass of :py:class:`ofxclient.Institution`
"""
return Institution(
... | [
"def",
"deserialize",
"(",
"raw",
")",
":",
"return",
"Institution",
"(",
"id",
"=",
"raw",
"[",
"'id'",
"]",
",",
"org",
"=",
"raw",
"[",
"'org'",
"]",
",",
"url",
"=",
"raw",
"[",
"'url'",
"]",
",",
"broker_id",
"=",
"raw",
".",
"get",
"(",
"... | 36.176471 | 13.647059 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.