text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def get_event_position(voevent, index=0):
"""Extracts the `AstroCoords` from a given `WhereWhen.ObsDataLocation`.
Note that a packet may include multiple 'ObsDataLocation' entries
under the 'WhereWhen' section, for example giving locations of an object
moving over time. Most packets will have only one,... | [
"def",
"get_event_position",
"(",
"voevent",
",",
"index",
"=",
"0",
")",
":",
"od",
"=",
"voevent",
".",
"WhereWhen",
".",
"ObsDataLocation",
"[",
"index",
"]",
"ac",
"=",
"od",
".",
"ObservationLocation",
".",
"AstroCoords",
"ac_sys",
"=",
"voevent",
"."... | 43.133333 | 22.6 |
def parse_env_file(envfile):
"""Parse the content of an iterable of lines as ``.env``.
Return a dict of config variables.
>>> parse_env_file(['DUDE=Abides'])
{'DUDE': 'Abides'}
"""
data = {}
for line_no, line in enumerate(envfile):
line = line.strip()
if not line or line.s... | [
"def",
"parse_env_file",
"(",
"envfile",
")",
":",
"data",
"=",
"{",
"}",
"for",
"line_no",
",",
"line",
"in",
"enumerate",
"(",
"envfile",
")",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"not",
"line",
"or",
"line",
".",
"startswith",
... | 29.307692 | 18.923077 |
def refresh_session(self, sessionkey, refresh_token=None):
'''
Refresh Session Token
'''
if not refresh_token:
refresh_token = sessionkey
params = {
'appkey' : self.API_KEY,
'sessionkey' : sessionkey,
'refresh_token': refresh_token... | [
"def",
"refresh_session",
"(",
"self",
",",
"sessionkey",
",",
"refresh_token",
"=",
"None",
")",
":",
"if",
"not",
"refresh_token",
":",
"refresh_token",
"=",
"sessionkey",
"params",
"=",
"{",
"'appkey'",
":",
"self",
".",
"API_KEY",
",",
"'sessionkey'",
":... | 39.083333 | 16.25 |
def get_collaborator_permission(self, collaborator):
"""
:calls: `GET /repos/:owner/:repo/collaborators/:username/permission <http://developer.github.com/v3/repos/collaborators>`_
:param collaborator: string or :class:`github.NamedUser.NamedUser`
:rtype: string
"""
assert... | [
"def",
"get_collaborator_permission",
"(",
"self",
",",
"collaborator",
")",
":",
"assert",
"isinstance",
"(",
"collaborator",
",",
"github",
".",
"NamedUser",
".",
"NamedUser",
")",
"or",
"isinstance",
"(",
"collaborator",
",",
"(",
"str",
",",
"unicode",
")"... | 52.142857 | 27.428571 |
def set_window_focus_callback(window, cbfun):
"""
Sets the focus callback for the specified window.
Wrapper for:
GLFWwindowfocusfun glfwSetWindowFocusCallback(GLFWwindow* window, GLFWwindowfocusfun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
c... | [
"def",
"set_window_focus_callback",
"(",
"window",
",",
"cbfun",
")",
":",
"window_addr",
"=",
"ctypes",
".",
"cast",
"(",
"ctypes",
".",
"pointer",
"(",
"window",
")",
",",
"ctypes",
".",
"POINTER",
"(",
"ctypes",
".",
"c_long",
")",
")",
".",
"contents... | 40.285714 | 19.714286 |
def post_check(self, check):
"""
:param check: Check to post to Metricly
:type check: object
"""
if self.disabled is True:
logging.error('Posting has been disabled. '
'See previous errors for details.')
return(False)
... | [
"def",
"post_check",
"(",
"self",
",",
"check",
")",
":",
"if",
"self",
".",
"disabled",
"is",
"True",
":",
"logging",
".",
"error",
"(",
"'Posting has been disabled. '",
"'See previous errors for details.'",
")",
"return",
"(",
"False",
")",
"url",
"=",
"self... | 33.594595 | 16.081081 |
def replace_all_calls(mod, orig, repl):
"""Replace all calls to `orig` to `repl` in module `mod`.
Returns the references to the returned calls
"""
rc = ReplaceCalls(orig, repl)
rc.visit(mod)
return rc.calls | [
"def",
"replace_all_calls",
"(",
"mod",
",",
"orig",
",",
"repl",
")",
":",
"rc",
"=",
"ReplaceCalls",
"(",
"orig",
",",
"repl",
")",
"rc",
".",
"visit",
"(",
"mod",
")",
"return",
"rc",
".",
"calls"
] | 32 | 8.571429 |
def paste(self, target_state_m, cursor_position=None, limited=None, convert=False):
"""Paste objects to target state
The method checks whether the target state is a execution state or a container state and inserts respective
elements and notifies the user if the parts can not be insert to the t... | [
"def",
"paste",
"(",
"self",
",",
"target_state_m",
",",
"cursor_position",
"=",
"None",
",",
"limited",
"=",
"None",
",",
"convert",
"=",
"False",
")",
":",
"self",
".",
"reset_clipboard_mapping_dicts",
"(",
")",
"if",
"not",
"isinstance",
"(",
"target_stat... | 67.016393 | 40.180328 |
def help(opts, bot, _):
"""Usage: help [<command>]
With no arguments, print the form of all supported commands.
With an argument, print a detailed explanation of a command.
"""
command = opts['<command>']
if command is None:
return bot.help_text()
if command not in bot.commands:
... | [
"def",
"help",
"(",
"opts",
",",
"bot",
",",
"_",
")",
":",
"command",
"=",
"opts",
"[",
"'<command>'",
"]",
"if",
"command",
"is",
"None",
":",
"return",
"bot",
".",
"help_text",
"(",
")",
"if",
"command",
"not",
"in",
"bot",
".",
"commands",
":",... | 28.5 | 17 |
def find_for_event(cls, event, include_hidden=False, **kwargs):
"""Returns a Query that retrieves the chatrooms for an event
:param event: an indico event (with a numeric ID)
:param include_hidden: if hidden chatrooms should be included, too
:param kwargs: extra kwargs to pass to ``find... | [
"def",
"find_for_event",
"(",
"cls",
",",
"event",
",",
"include_hidden",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"query",
"=",
"cls",
".",
"find",
"(",
"event_id",
"=",
"event",
".",
"id",
",",
"*",
"*",
"kwargs",
")",
"if",
"not",
"inclu... | 43.454545 | 16.272727 |
def is_global(self):
"""Test if this address is allocated for public networks.
Returns:
A boolean, True if the address is not reserved per
iana-ipv4-special-registry.
"""
return (not (self.network_address in IPv4Network('100.64.0.0/10') and
self.... | [
"def",
"is_global",
"(",
"self",
")",
":",
"return",
"(",
"not",
"(",
"self",
".",
"network_address",
"in",
"IPv4Network",
"(",
"'100.64.0.0/10'",
")",
"and",
"self",
".",
"broadcast_address",
"in",
"IPv4Network",
"(",
"'100.64.0.0/10'",
")",
")",
"and",
"no... | 36.454545 | 20.272727 |
def parse_mpi(s):
"""See https://tools.ietf.org/html/rfc4880#section-3.2 for details."""
bits = s.readfmt('>H')
blob = bytearray(s.read(int((bits + 7) // 8)))
return sum(v << (8 * i) for i, v in enumerate(reversed(blob))) | [
"def",
"parse_mpi",
"(",
"s",
")",
":",
"bits",
"=",
"s",
".",
"readfmt",
"(",
"'>H'",
")",
"blob",
"=",
"bytearray",
"(",
"s",
".",
"read",
"(",
"int",
"(",
"(",
"bits",
"+",
"7",
")",
"//",
"8",
")",
")",
")",
"return",
"sum",
"(",
"v",
"... | 46.6 | 14.6 |
def AssignGroupNodes(r, group, nodes, force=False, dry_run=False):
"""
Assigns nodes to a group.
@type group: string
@param group: Node gropu name
@type nodes: list of strings
@param nodes: List of nodes to assign to the group
@rtype: int
@return: job id
"""
query = {
... | [
"def",
"AssignGroupNodes",
"(",
"r",
",",
"group",
",",
"nodes",
",",
"force",
"=",
"False",
",",
"dry_run",
"=",
"False",
")",
":",
"query",
"=",
"{",
"\"force\"",
":",
"force",
",",
"\"dry-run\"",
":",
"dry_run",
",",
"}",
"body",
"=",
"{",
"\"node... | 20.16 | 23.36 |
def publish(self):
'''
Perform HTTP session to transmit defined weather values.
'''
return self._publish( self.args, self.server, self.URI) | [
"def",
"publish",
"(",
"self",
")",
":",
"return",
"self",
".",
"_publish",
"(",
"self",
".",
"args",
",",
"self",
".",
"server",
",",
"self",
".",
"URI",
")"
] | 31.8 | 25.4 |
def layers(self):
""" gets the layers for the feature service """
if self._layers is None:
self.__init()
self._getLayers()
return self._layers | [
"def",
"layers",
"(",
"self",
")",
":",
"if",
"self",
".",
"_layers",
"is",
"None",
":",
"self",
".",
"__init",
"(",
")",
"self",
".",
"_getLayers",
"(",
")",
"return",
"self",
".",
"_layers"
] | 30.166667 | 12.333333 |
def validated_type(base_type, name=None, validate=None):
"""Convenient way to create a new type by adding validation to existing type.
Example: ::
Ipv4Address = validated_type(
String, 'Ipv4Address',
# regexp simplified for demo purposes
Regexp('^\d+\.\d+\.\d+\.\d+$... | [
"def",
"validated_type",
"(",
"base_type",
",",
"name",
"=",
"None",
",",
"validate",
"=",
"None",
")",
":",
"if",
"validate",
"is",
"None",
":",
"validate",
"=",
"[",
"]",
"if",
"not",
"is_sequence",
"(",
"validate",
")",
":",
"validate",
"=",
"[",
... | 35.065217 | 19.934783 |
def plotTraces (include = None, timeRange = None, overlay = False, oneFigPer = 'cell', rerun = False, colors = None, ylim = None, axis='on', fontSize=12,
figSize = (10,8), saveData = None, saveFig = None, showFig = True):
'''
Plot recorded traces
- include (['all',|'allCells','allNetStims',|,120,|... | [
"def",
"plotTraces",
"(",
"include",
"=",
"None",
",",
"timeRange",
"=",
"None",
",",
"overlay",
"=",
"False",
",",
"oneFigPer",
"=",
"'cell'",
",",
"rerun",
"=",
"False",
",",
"colors",
"=",
"None",
",",
"ylim",
"=",
"None",
",",
"axis",
"=",
"'on'"... | 50.622047 | 26.84252 |
def _stripped_name_version(self):
"""Returns filename stripped of the suffix.
Returns:
Filename stripped of the suffix (extension).
"""
# we don't use splitext, because on "a.tar.gz" it returns ("a.tar",
# "gz")
filename = os.path.basename(self.local_file)
... | [
"def",
"_stripped_name_version",
"(",
"self",
")",
":",
"# we don't use splitext, because on \"a.tar.gz\" it returns (\"a.tar\",",
"# \"gz\")",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"self",
".",
"local_file",
")",
"for",
"archive_suffix",
"in",
"sett... | 45.866667 | 18.133333 |
def validate_cmaps(cmaps):
"""Validate a dictionary of color lists
Parameters
----------
cmaps: dict
a mapping from a colormap name to a list of colors
Raises
------
ValueError
If one of the values in `cmaps` is not a color list
Notes
-----
For all items (listn... | [
"def",
"validate_cmaps",
"(",
"cmaps",
")",
":",
"cmaps",
"=",
"{",
"validate_str",
"(",
"key",
")",
":",
"validate_colorlist",
"(",
"val",
")",
"for",
"key",
",",
"val",
"in",
"cmaps",
"}",
"for",
"key",
",",
"val",
"in",
"six",
".",
"iteritems",
"(... | 28.238095 | 23.47619 |
def _update_proxy(self, change):
""" Update the proxy widget when the Widget data
changes.
"""
#: Try default handler
if change['type'] == 'update' and self.proxy_is_active:
handler = getattr(self.proxy, 'set_' + change['name'], None)
if handler is not Non... | [
"def",
"_update_proxy",
"(",
"self",
",",
"change",
")",
":",
"#: Try default handler",
"if",
"change",
"[",
"'type'",
"]",
"==",
"'update'",
"and",
"self",
".",
"proxy_is_active",
":",
"handler",
"=",
"getattr",
"(",
"self",
".",
"proxy",
",",
"'set_'",
"... | 40.5 | 13.25 |
def _connect(self):
"""Connect to server."""
self._soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._soc.connect((self._ipaddr, self._port))
self._soc.send(_build_request({'cmd': cmd.CMD_MESSAGE_PASSWORD,
'sha': self._password})) | [
"def",
"_connect",
"(",
"self",
")",
":",
"self",
".",
"_soc",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"self",
".",
"_soc",
".",
"connect",
"(",
"(",
"self",
".",
"_ipaddr",
",",
"self",
... | 51.166667 | 19.5 |
def on_change_dir_button(self, event=None):
"""
create change directory frame
"""
currentDirectory = self.WD #os.getcwd()
change_dir_dialog = wx.DirDialog(self.panel,
"Choose your working directory to create or edit a MagIC contribution:",... | [
"def",
"on_change_dir_button",
"(",
"self",
",",
"event",
"=",
"None",
")",
":",
"currentDirectory",
"=",
"self",
".",
"WD",
"#os.getcwd()",
"change_dir_dialog",
"=",
"wx",
".",
"DirDialog",
"(",
"self",
".",
"panel",
",",
"\"Choose your working directory to creat... | 45.529412 | 16 |
def build_function(func):
"""
Build a function from a templated function. The function must look like
template<class I, class T, ...>
void func(const p[], p_size, ...)
rules:
- a pointer or array p is followed by int p_size
- all arrays are templated
- non arrays are basic ... | [
"def",
"build_function",
"(",
"func",
")",
":",
"indent",
"=",
"' '",
"# temlpate and function name",
"if",
"func",
"[",
"'template'",
"]",
":",
"fdef",
"=",
"func",
"[",
"'template'",
"]",
"+",
"'\\n'",
"else",
":",
"fdef",
"=",
"''",
"newcall",
"=",
... | 28.268908 | 17.462185 |
def setVisible(self, state):
"""
Sets whether or not this toolbar is visible. If shown, it will rebuild.
:param state | <bool>
"""
super(XDockToolbar, self).setVisible(state)
if state:
self.rebuild()
self.setCurren... | [
"def",
"setVisible",
"(",
"self",
",",
"state",
")",
":",
"super",
"(",
"XDockToolbar",
",",
"self",
")",
".",
"setVisible",
"(",
"state",
")",
"if",
"state",
":",
"self",
".",
"rebuild",
"(",
")",
"self",
".",
"setCurrentAction",
"(",
"None",
")"
] | 29.363636 | 15.181818 |
def _get_tokens_rate_limits(self):
"""Return array of all tokens remaining API points"""
remainings = [0] * self.n_tokens
# Turn off archiving when checking rates, because that would cause
# archive key conflict (the same URLs giving different responses)
arch = self.archive
... | [
"def",
"_get_tokens_rate_limits",
"(",
"self",
")",
":",
"remainings",
"=",
"[",
"0",
"]",
"*",
"self",
".",
"n_tokens",
"# Turn off archiving when checking rates, because that would cause",
"# archive key conflict (the same URLs giving different responses)",
"arch",
"=",
"self... | 46.733333 | 18.666667 |
def get_object(self, *args, **kwargs):
"""
Should memoize the object to avoid multiple query if get_object is used many times in the view
"""
self.category_instance = get_object_or_404(Category, slug=self.kwargs['category_slug'])
return get_object_or_404(Post, thread__id=self.kwa... | [
"def",
"get_object",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"category_instance",
"=",
"get_object_or_404",
"(",
"Category",
",",
"slug",
"=",
"self",
".",
"kwargs",
"[",
"'category_slug'",
"]",
")",
"return",
"get_... | 66.666667 | 37 |
def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Check whether a VPC with the given name or id exists.
Returns the vpc_id or None. Raises SaltInvocationError if
both vpc_id and vpc_name are None. Optionally raise a
CommandExecutionError if... | [
"def",
"check_vpc",
"(",
"vpc_id",
"=",
"None",
",",
"vpc_name",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"if",
"not",
"_exactly_one",
"(",
"(",
"vpc_name",
... | 35.821429 | 23.25 |
def get_media_entities(tweet):
"""
Grabs all the media entities from a tweet, which are contained in the
"extended_entities" or "twitter_extended_entities" field depending on the
tweet format. Note that this is not the same as the first media entity from
the basic `entities` key; this is required to... | [
"def",
"get_media_entities",
"(",
"tweet",
")",
":",
"ext_ents_key",
"=",
"\"extended_entities\"",
"if",
"is_original_format",
"(",
"tweet",
")",
"else",
"\"twitter_extended_entities\"",
"ext_ents",
"=",
"tweet",
".",
"get",
"(",
"ext_ents_key",
")",
"media",
"=",
... | 69.050847 | 42.372881 |
def named_entity_spans(self):
"""The spans of named entities."""
if not self.is_tagged(NAMED_ENTITIES):
self.tag_named_entities()
return self.spans(NAMED_ENTITIES) | [
"def",
"named_entity_spans",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_tagged",
"(",
"NAMED_ENTITIES",
")",
":",
"self",
".",
"tag_named_entities",
"(",
")",
"return",
"self",
".",
"spans",
"(",
"NAMED_ENTITIES",
")"
] | 39 | 4.2 |
def parse(self):
"""
The function for parsing the JSON response to the vars dictionary.
"""
try:
self.vars['handle'] = self.json['handle'].strip()
except (KeyError, ValueError, TypeError):
raise InvalidEntityObject('Handle is missing for RDAP entity')
... | [
"def",
"parse",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"vars",
"[",
"'handle'",
"]",
"=",
"self",
".",
"json",
"[",
"'handle'",
"]",
".",
"strip",
"(",
")",
"except",
"(",
"KeyError",
",",
"ValueError",
",",
"TypeError",
")",
":",
"raise",... | 20.112903 | 25.758065 |
def p_reset(self, program):
"""
reset : RESET primary
"""
program[0] = node.Reset([program[2]])
self.verify_reg(program[2], 'qreg') | [
"def",
"p_reset",
"(",
"self",
",",
"program",
")",
":",
"program",
"[",
"0",
"]",
"=",
"node",
".",
"Reset",
"(",
"[",
"program",
"[",
"2",
"]",
"]",
")",
"self",
".",
"verify_reg",
"(",
"program",
"[",
"2",
"]",
",",
"'qreg'",
")"
] | 27.666667 | 5.333333 |
def imag(self, newimag):
"""Set the imaginary part of this element to ``newimag``.
This method is invoked by ``x.imag = other``.
Parameters
----------
newimag : array-like or scalar
Values to be assigned to the imaginary part of this element.
Raises
... | [
"def",
"imag",
"(",
"self",
",",
"newimag",
")",
":",
"if",
"self",
".",
"space",
".",
"is_real",
":",
"raise",
"ValueError",
"(",
"'cannot set imaginary part in real spaces'",
")",
"self",
".",
"tensor",
".",
"imag",
"=",
"newimag"
] | 30.611111 | 21.055556 |
def start(state, host, ctid, force=False):
'''
Start OpenVZ containers.
+ ctid: CTID of the container to start
+ force: whether to force container start
'''
args = ['{0}'.format(ctid)]
if force:
args.append('--force')
yield 'vzctl start {0}'.format(' '.join(args)) | [
"def",
"start",
"(",
"state",
",",
"host",
",",
"ctid",
",",
"force",
"=",
"False",
")",
":",
"args",
"=",
"[",
"'{0}'",
".",
"format",
"(",
"ctid",
")",
"]",
"if",
"force",
":",
"args",
".",
"append",
"(",
"'--force'",
")",
"yield",
"'vzctl start ... | 21.071429 | 21.642857 |
def move(self, d, add_tile=True):
"""
move and return the move score
"""
if d == Board.LEFT or d == Board.RIGHT:
chg, get = self.setLine, self.getLine
elif d == Board.UP or d == Board.DOWN:
chg, get = self.setCol, self.getCol
else:
retu... | [
"def",
"move",
"(",
"self",
",",
"d",
",",
"add_tile",
"=",
"True",
")",
":",
"if",
"d",
"==",
"Board",
".",
"LEFT",
"or",
"d",
"==",
"Board",
".",
"RIGHT",
":",
"chg",
",",
"get",
"=",
"self",
".",
"setLine",
",",
"self",
".",
"getLine",
"elif... | 30.583333 | 15.25 |
def unpitched_high(dur, idx):
"""
Non-harmonic treble/higher frequency sound as a list (due to memoization).
Parameters
----------
dur:
Duration, in samples.
idx:
Zero or one (integer), for a small difference to the sound played.
Returns
-------
A list with the synthesized note.
"""
fir... | [
"def",
"unpitched_high",
"(",
"dur",
",",
"idx",
")",
":",
"first_dur",
",",
"a",
",",
"d",
",",
"r",
",",
"gain",
"=",
"[",
"(",
"30",
"*",
"ms",
",",
"10",
"*",
"ms",
",",
"8",
"*",
"ms",
",",
"10",
"*",
"ms",
",",
".4",
")",
",",
"(",
... | 25.4 | 20.44 |
def rooms(self, sid, namespace=None):
"""Return the rooms a client is in.
The only difference with the :func:`socketio.Server.rooms` method is
that when the ``namespace`` argument is not given the namespace
associated with the class is used.
"""
return self.server.rooms(... | [
"def",
"rooms",
"(",
"self",
",",
"sid",
",",
"namespace",
"=",
"None",
")",
":",
"return",
"self",
".",
"server",
".",
"rooms",
"(",
"sid",
",",
"namespace",
"=",
"namespace",
"or",
"self",
".",
"namespace",
")"
] | 44.5 | 18.5 |
def feed_data(self, data: bytes) -> None:
"""
代理 feed_data
"""
if self._parser is not None:
self._parser.feed_data(data) | [
"def",
"feed_data",
"(",
"self",
",",
"data",
":",
"bytes",
")",
"->",
"None",
":",
"if",
"self",
".",
"_parser",
"is",
"not",
"None",
":",
"self",
".",
"_parser",
".",
"feed_data",
"(",
"data",
")"
] | 26.5 | 4.166667 |
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the data encoding the DeviceCredential struct to a stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usually a BytearrayStr... | [
"def",
"write",
"(",
"self",
",",
"output_stream",
",",
"kmip_version",
"=",
"enums",
".",
"KMIPVersion",
".",
"KMIP_1_0",
")",
":",
"local_stream",
"=",
"BytearrayStream",
"(",
")",
"if",
"self",
".",
"_device_serial_number",
"is",
"not",
"None",
":",
"self... | 35.78 | 13.94 |
def check_role_permissions(role, permissions, current_permissions):
"""
Checks the the passed in role (can be user, group or AnonymousUser) has all the passed
in permissions, granting them if necessary.
"""
role_permissions = []
# get all the current permissions, we'll remove these as we verif... | [
"def",
"check_role_permissions",
"(",
"role",
",",
"permissions",
",",
"current_permissions",
")",
":",
"role_permissions",
"=",
"[",
"]",
"# get all the current permissions, we'll remove these as we verify they should still be granted",
"for",
"permission",
"in",
"permissions",
... | 36.375 | 22.732143 |
def get_stdlib_path():
"""Returns the path to the standard lib for the current path installation.
This function can be dropped and "sysconfig.get_paths()" used directly once Python 2.6 support is dropped.
"""
if sys.version_info >= (2, 7):
import sysconfig
return sysconfig.get_paths()['... | [
"def",
"get_stdlib_path",
"(",
")",
":",
"if",
"sys",
".",
"version_info",
">=",
"(",
"2",
",",
"7",
")",
":",
"import",
"sysconfig",
"return",
"sysconfig",
".",
"get_paths",
"(",
")",
"[",
"'stdlib'",
"]",
"else",
":",
"return",
"os",
".",
"path",
"... | 37.6 | 19.3 |
def _find_cut_triangle(self, edge):
"""
Return the triangle that has edge[0] as one of its vertices and is
bisected by edge.
Return None if no triangle is found.
"""
edges = [] # opposite edge for each triangle attached to edge[0]
for tri in self.tris:
... | [
"def",
"_find_cut_triangle",
"(",
"self",
",",
"edge",
")",
":",
"edges",
"=",
"[",
"]",
"# opposite edge for each triangle attached to edge[0]",
"for",
"tri",
"in",
"self",
".",
"tris",
":",
"if",
"edge",
"[",
"0",
"]",
"in",
"tri",
":",
"edges",
".",
"ap... | 35.681818 | 14.681818 |
def delete(self, ids):
"""
Method to delete asns by their id's
:param ids: Identifiers of asns
:return: None
"""
url = build_uri_with_ids('api/v4/as/%s/', ids)
return super(ApiV4As, self).delete(url) | [
"def",
"delete",
"(",
"self",
",",
"ids",
")",
":",
"url",
"=",
"build_uri_with_ids",
"(",
"'api/v4/as/%s/'",
",",
"ids",
")",
"return",
"super",
"(",
"ApiV4As",
",",
"self",
")",
".",
"delete",
"(",
"url",
")"
] | 27.555556 | 11.333333 |
def metadata_path(self, m_path):
"""Provide pointers to the paths of the metadata file
Args:
m_path: Path to metadata file
"""
if not m_path:
self.metadata_dir = None
self.metadata_file = None
else:
if not op.exists(m_path):
... | [
"def",
"metadata_path",
"(",
"self",
",",
"m_path",
")",
":",
"if",
"not",
"m_path",
":",
"self",
".",
"metadata_dir",
"=",
"None",
"self",
".",
"metadata_file",
"=",
"None",
"else",
":",
"if",
"not",
"op",
".",
"exists",
"(",
"m_path",
")",
":",
"ra... | 33.269231 | 17.884615 |
def make_batch(self):
"""Generator function for batchifying data for learning to execute.
Yields:
tuple:
1. one-hot input tensor, representing programmatic input
2. one-hot target tensor, the vealuation result.
3. one-hot decoder target, start symbol added for sequence decoding.
... | [
"def",
"make_batch",
"(",
"self",
")",
":",
"while",
"True",
":",
"self",
".",
"reset_data_source",
"(",
")",
"obs",
"=",
"np",
".",
"reshape",
"(",
"self",
".",
"_data_source",
".",
"flat_data",
",",
"[",
"self",
".",
"batch_size",
",",
"-",
"1",
"]... | 45.576923 | 19.653846 |
def dropna(self, columns=None, how='any'):
"""
Remove missing values from an SFrame. A missing value is either ``None``
or ``NaN``. If ``how`` is 'any', a row will be removed if any of the
columns in the ``columns`` parameter contains at least one missing
value. If ``how`` is '... | [
"def",
"dropna",
"(",
"self",
",",
"columns",
"=",
"None",
",",
"how",
"=",
"'any'",
")",
":",
"# If the user gives me an empty list (the indicator to use all columns)",
"# NA values being dropped would not be the expected behavior. This",
"# is a NOOP, so let's not bother the server... | 31.776316 | 25.065789 |
def get_application_parser(commands):
"""
Builds an argument parser for the application's CLI.
:param commands:
:return: ArgumentParser
"""
parser = argparse.ArgumentParser(
description=configuration.APPLICATION_DESCRIPTION,
usage =configuration.EXECUTABLE_NAME + ' [sub-command... | [
"def",
"get_application_parser",
"(",
"commands",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"configuration",
".",
"APPLICATION_DESCRIPTION",
",",
"usage",
"=",
"configuration",
".",
"EXECUTABLE_NAME",
"+",
"' [sub-command] [o... | 26.55 | 19.35 |
def get_last_month_range():
""" Gets the date for the first and the last day of the previous complete month.
:returns: A tuple containing two date objects, for the first and the last day of the month
respectively.
"""
today = date.today()
# Get the last day for the previous month.
... | [
"def",
"get_last_month_range",
"(",
")",
":",
"today",
"=",
"date",
".",
"today",
"(",
")",
"# Get the last day for the previous month.",
"end_of_last_month",
"=",
"snap_to_beginning_of_month",
"(",
"today",
")",
"-",
"timedelta",
"(",
"days",
"=",
"1",
")",
"star... | 46.181818 | 20.090909 |
def _conf_packages(args):
"""Runs custom configuration steps for the packages that ship with support
in acorn.
"""
from acorn.config import config_dir
from os import path
from acorn.base import testmode
target = config_dir(True)
alternate = path.join(path.abspath(path.expanduser("~")), "... | [
"def",
"_conf_packages",
"(",
"args",
")",
":",
"from",
"acorn",
".",
"config",
"import",
"config_dir",
"from",
"os",
"import",
"path",
"from",
"acorn",
".",
"base",
"import",
"testmode",
"target",
"=",
"config_dir",
"(",
"True",
")",
"alternate",
"=",
"pa... | 32.388889 | 17.138889 |
def accelerated_proximal_gradient(x, f, g, gamma, niter, callback=None,
**kwargs):
r"""Accelerated proximal gradient algorithm for convex optimization.
The method is known as "Fast Iterative Soft-Thresholding Algorithm"
(FISTA). See `[Beck2009]`_ for more information.
... | [
"def",
"accelerated_proximal_gradient",
"(",
"x",
",",
"f",
",",
"g",
",",
"gamma",
",",
"niter",
",",
"callback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Get and validate input",
"if",
"x",
"not",
"in",
"f",
".",
"domain",
":",
"raise",
"Ty... | 28.457447 | 22.553191 |
def find_oxygen_reactions(model):
"""Return list of oxygen-producing/-consuming reactions."""
o2_in_model = helpers.find_met_in_model(model, "MNXM4")
return set([rxn for met in model.metabolites for
rxn in met.reactions if met.formula == "O2" or
met in o2_in_model]) | [
"def",
"find_oxygen_reactions",
"(",
"model",
")",
":",
"o2_in_model",
"=",
"helpers",
".",
"find_met_in_model",
"(",
"model",
",",
"\"MNXM4\"",
")",
"return",
"set",
"(",
"[",
"rxn",
"for",
"met",
"in",
"model",
".",
"metabolites",
"for",
"rxn",
"in",
"me... | 50.833333 | 10.666667 |
async def jsk_git(self, ctx: commands.Context, *, argument: CodeblockConverter):
"""
Shortcut for 'jsk sh git'. Invokes the system shell.
"""
return await ctx.invoke(self.jsk_shell, argument=Codeblock(argument.language, "git " + argument.content)) | [
"async",
"def",
"jsk_git",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
",",
"*",
",",
"argument",
":",
"CodeblockConverter",
")",
":",
"return",
"await",
"ctx",
".",
"invoke",
"(",
"self",
".",
"jsk_shell",
",",
"argument",
"=",
"Codeblock"... | 45.833333 | 28.833333 |
def log_binary(logger, message, **kwargs):
"""Log binary data if debug is enabled."""
if logger.isEnabledFor(logging.DEBUG):
output = ('{0}={1}'.format(k, binascii.hexlify(
bytearray(v)).decode()) for k, v in sorted(kwargs.items()))
logger.debug('%s (%s)', message, ', '.join(output)) | [
"def",
"log_binary",
"(",
"logger",
",",
"message",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"logger",
".",
"isEnabledFor",
"(",
"logging",
".",
"DEBUG",
")",
":",
"output",
"=",
"(",
"'{0}={1}'",
".",
"format",
"(",
"k",
",",
"binascii",
".",
"hexli... | 52.5 | 11.5 |
def preprocess(string):
"""
Preprocesses a string, by replacing ${VARNAME} with
os.environ['VARNAME']
Parameters
----------
string: the str object to preprocess
Returns
-------
the preprocessed string
"""
split = string.split('${')
rval = [split[0]]
for candidate... | [
"def",
"preprocess",
"(",
"string",
")",
":",
"split",
"=",
"string",
".",
"split",
"(",
"'${'",
")",
"rval",
"=",
"[",
"split",
"[",
"0",
"]",
"]",
"for",
"candidate",
"in",
"split",
"[",
"1",
":",
"]",
":",
"subsplit",
"=",
"candidate",
".",
"s... | 26.923077 | 22.807692 |
def save(self, *args, **kwargs):
"""
Determines ip protocol version automatically.
Stores address in interface shortcuts for convenience.
"""
self.protocol = 'ipv%d' % self.address.version
# save
super(Ip, self).save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"protocol",
"=",
"'ipv%d'",
"%",
"self",
".",
"address",
".",
"version",
"# save",
"super",
"(",
"Ip",
",",
"self",
")",
".",
"save",
"(",
"*",
"args",
... | 35.25 | 11 |
def do_print(self,args):
"""Print the current stack. print -h for detailed help"""
parser = CommandArgumentParser("print")
parser.add_argument('-r','--refresh',dest='refresh',action='store_true',help='refresh view of the current stack')
parser.add_argument('-i','--include',dest='include'... | [
"def",
"do_print",
"(",
"self",
",",
"args",
")",
":",
"parser",
"=",
"CommandArgumentParser",
"(",
"\"print\"",
")",
"parser",
".",
"add_argument",
"(",
"'-r'",
",",
"'--refresh'",
",",
"dest",
"=",
"'refresh'",
",",
"action",
"=",
"'store_true'",
",",
"h... | 53.166667 | 30.75 |
def _fetch(self, url, params):
"""Fetch a resource.
Method to fetch and to iterate over the contents of a
type of resource. The method returns a generator of
pages for that resource and parameters.
:param url: the endpoint of the API
:param params: parameters to filter
... | [
"def",
"_fetch",
"(",
"self",
",",
"url",
",",
"params",
")",
":",
"if",
"not",
"self",
".",
"from_archive",
":",
"self",
".",
"sleep_for_rate_limit",
"(",
")",
"headers",
"=",
"{",
"'Authorization'",
":",
"'Bearer '",
"+",
"self",
".",
"api_key",
"}",
... | 29.454545 | 17.409091 |
def flatten_args(shapes):
r"""
Decorator to flatten structured arguments to a function.
Examples
--------
>>> @flatten_args([(5,), ()])
... def f(w, lambda_):
... return .5 * lambda_ * w.T.dot(w)
>>> np.isclose(f(np.array([2., .5, .6, -.2, .9, .2])), .546)
True
>>> w = np.ar... | [
"def",
"flatten_args",
"(",
"shapes",
")",
":",
"def",
"flatten_args_dec",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"new_func",
"(",
"array1d",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"tuple",
"(",
"un... | 29.270833 | 18.333333 |
def database_root_path(cls, project, database):
"""Return a fully-qualified database_root string."""
return google.api_core.path_template.expand(
"projects/{project}/databases/{database}",
project=project,
database=database,
) | [
"def",
"database_root_path",
"(",
"cls",
",",
"project",
",",
"database",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/databases/{database}\"",
",",
"project",
"=",
"project",
",",
"database",
"=",
... | 40 | 12.285714 |
def _create_subplots(self, fig, layout):
"""
Create suplots and return axs
"""
num_panels = len(layout)
axsarr = np.empty((self.nrow, self.ncol), dtype=object)
# Create axes
i = 1
for row in range(self.nrow):
for col in range(self.ncol):
... | [
"def",
"_create_subplots",
"(",
"self",
",",
"fig",
",",
"layout",
")",
":",
"num_panels",
"=",
"len",
"(",
"layout",
")",
"axsarr",
"=",
"np",
".",
"empty",
"(",
"(",
"self",
".",
"nrow",
",",
"self",
".",
"ncol",
")",
",",
"dtype",
"=",
"object",... | 29.1875 | 15.9375 |
def solve_buffer(self, addr, nbytes, constrain=False):
"""
Reads `nbytes` of symbolic data from a buffer in memory at `addr` and attempts to
concretize it
:param int address: Address of buffer to concretize
:param int nbytes: Size of buffer to concretize
:param bool cons... | [
"def",
"solve_buffer",
"(",
"self",
",",
"addr",
",",
"nbytes",
",",
"constrain",
"=",
"False",
")",
":",
"buffer",
"=",
"self",
".",
"cpu",
".",
"read_bytes",
"(",
"addr",
",",
"nbytes",
")",
"result",
"=",
"[",
"]",
"with",
"self",
".",
"_constrain... | 41.736842 | 18.052632 |
def _encode(self, data: mx.sym.Symbol, data_length: mx.sym.Symbol, seq_len: int) -> mx.sym.Symbol:
"""
Bidirectionally encodes time-major data.
"""
# (seq_len, batch_size, num_embed)
data_reverse = mx.sym.SequenceReverse(data=data, sequence_length=data_length,
... | [
"def",
"_encode",
"(",
"self",
",",
"data",
":",
"mx",
".",
"sym",
".",
"Symbol",
",",
"data_length",
":",
"mx",
".",
"sym",
".",
"Symbol",
",",
"seq_len",
":",
"int",
")",
"->",
"mx",
".",
"sym",
".",
"Symbol",
":",
"# (seq_len, batch_size, num_embed)... | 57.166667 | 26.166667 |
def get_urls(self):
"""
Get urls method.
Returns:
list: the list of url objects.
"""
urls = super(DashboardSite, self).get_urls()
custom_urls = [
url(r'^$',
self.admin_view(HomeView.as_view()),
name='index'),
... | [
"def",
"get_urls",
"(",
"self",
")",
":",
"urls",
"=",
"super",
"(",
"DashboardSite",
",",
"self",
")",
".",
"get_urls",
"(",
")",
"custom_urls",
"=",
"[",
"url",
"(",
"r'^$'",
",",
"self",
".",
"admin_view",
"(",
"HomeView",
".",
"as_view",
"(",
")"... | 25.842105 | 18.894737 |
def _extract_placeholder_weld_objects_at_index(dependency_name, length, readable_text, index):
"""Helper method that creates a WeldObject for each component of dependency.
Parameters
----------
dependency_name : str
The name of the dependency evaluating to a tuple.
length : int
Numb... | [
"def",
"_extract_placeholder_weld_objects_at_index",
"(",
"dependency_name",
",",
"length",
",",
"readable_text",
",",
"index",
")",
":",
"weld_objects",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"length",
")",
":",
"fake_weld_input",
"=",
"Cache",
".",
"... | 32.166667 | 25.333333 |
def scale_fft(in1):
"""
This function performs in-place scaling after the IFFT without recompilation.
INPUTS:
in1 (no default): Array containing data which is to be scaled.
"""
ker = SourceModule("""
__global__ void scale_fft_ker(float *in1)
... | [
"def",
"scale_fft",
"(",
"in1",
")",
":",
"ker",
"=",
"SourceModule",
"(",
"\"\"\"\n __global__ void scale_fft_ker(float *in1)\n {\n const int len = gridDim.x*blockDim.x;\n const int col = (blockD... | 40.125 | 26.875 |
def to_date(date, dayfirst=False, format=None):
"""
Transforme un champ date vers un objet python datetime
Paramètres:
date:
- si None, renvoie la date du jour
- si de type str, renvoie un objet python datetime
- si de type datetime, le retourne sans modification
dayfirst: Si... | [
"def",
"to_date",
"(",
"date",
",",
"dayfirst",
"=",
"False",
",",
"format",
"=",
"None",
")",
":",
"## TODO: voir si pd.tseries.api ne peut pas remplacer tout ca",
"if",
"not",
"date",
":",
"return",
"dt",
".",
"datetime",
".",
"fromordinal",
"(",
"dt",
".",
... | 47.185185 | 23.555556 |
def rename_file(source, dest):
""" Rename (mv) file(s) from source to dest
>>> from tempfile import mkdtemp
>>> tmpdir = mkdtemp(suffix='doctest_rename_file', prefix='tmp')
>>> fout = ensure_open(os.path.join(tmpdir, 'fake_data.bin.gz'), 'w')
>>> fout.write(b'fake nlpia.loaders.rename_file')
30... | [
"def",
"rename_file",
"(",
"source",
",",
"dest",
")",
":",
"logger",
".",
"debug",
"(",
"'nlpia.loaders.rename_file(source={}, dest={})'",
".",
"format",
"(",
"source",
",",
"dest",
")",
")",
"if",
"not",
"isinstance",
"(",
"source",
",",
"str",
")",
":",
... | 45.272727 | 26.636364 |
def spkgeo(targ, et, ref, obs):
"""
Compute the geometric state (position and velocity) of a target
body relative to an observing body.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkgeo_c.html
:param targ: Target body.
:type targ: int
:param et: Target epoch.
:type et: flo... | [
"def",
"spkgeo",
"(",
"targ",
",",
"et",
",",
"ref",
",",
"obs",
")",
":",
"targ",
"=",
"ctypes",
".",
"c_int",
"(",
"targ",
")",
"et",
"=",
"ctypes",
".",
"c_double",
"(",
"et",
")",
"ref",
"=",
"stypes",
".",
"stringToCharP",
"(",
"ref",
")",
... | 30.115385 | 14.807692 |
def modify_event_view(request, id=None):
"""Modify event page. You may only modify an event if you were the creator or you are an
administrator.
id: event id
"""
event = get_object_or_404(Event, id=id)
is_events_admin = request.user.has_admin_permission('events')
if not is_events_admin:
... | [
"def",
"modify_event_view",
"(",
"request",
",",
"id",
"=",
"None",
")",
":",
"event",
"=",
"get_object_or_404",
"(",
"Event",
",",
"id",
"=",
"id",
")",
"is_events_admin",
"=",
"request",
".",
"user",
".",
"has_admin_permission",
"(",
"'events'",
")",
"if... | 41.828571 | 26.371429 |
def upload_file(client, bucket, local_path, remote_path, overwrite=False):
"""Uploads a file to a bucket.
TODO: docstring"""
bucket = client.get_bucket(bucket)
blob = storage.Blob(remote_path, bucket)
if (not overwrite) and blob.exists():
raise Conflict('File/object already exists on th... | [
"def",
"upload_file",
"(",
"client",
",",
"bucket",
",",
"local_path",
",",
"remote_path",
",",
"overwrite",
"=",
"False",
")",
":",
"bucket",
"=",
"client",
".",
"get_bucket",
"(",
"bucket",
")",
"blob",
"=",
"storage",
".",
"Blob",
"(",
"remote_path",
... | 40.555556 | 11.666667 |
def _process_tools_arg(plot, tools, tooltips=None):
""" Adds tools to the plot object
Args:
plot (Plot): instance of a plot object
tools (seq[Tool or str]|str): list of tool types or string listing the
tool names. Those are converted using the _tool_from_string
function.... | [
"def",
"_process_tools_arg",
"(",
"plot",
",",
"tools",
",",
"tooltips",
"=",
"None",
")",
":",
"tool_objs",
"=",
"[",
"]",
"tool_map",
"=",
"{",
"}",
"temp_tool_str",
"=",
"\"\"",
"repeated_tools",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"tools",
",",
... | 33.2 | 19.381818 |
def _construct_body_s3_dict(self):
"""Constructs the RestApi's `BodyS3Location property`_, from the SAM Api's DefinitionUri property.
:returns: a BodyS3Location dict, containing the S3 Bucket, Key, and Version of the Swagger definition
:rtype: dict
"""
if isinstance(self.definit... | [
"def",
"_construct_body_s3_dict",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"definition_uri",
",",
"dict",
")",
":",
"if",
"not",
"self",
".",
"definition_uri",
".",
"get",
"(",
"\"Bucket\"",
",",
"None",
")",
"or",
"not",
"self",
".",... | 47.586207 | 26.931034 |
def reinit(self, draw=None, clear=False):
"""
Reinitializes the plot with the same data and on the same axes.
Parameters
----------
%(InteractiveBase.start_update.parameters.draw)s
clear: bool
Whether to clear the axes or not
Warnings
-------... | [
"def",
"reinit",
"(",
"self",
",",
"draw",
"=",
"None",
",",
"clear",
"=",
"False",
")",
":",
"# call the initialize_plot method. Note that clear can be set to",
"# False if any fmto has requires_clearing attribute set to True,",
"# because this then has been cleared before",
"self... | 37.428571 | 20.47619 |
def stdrepr(self, obj, *, cls=None, tag='span'):
"""
Standard representation for objects, used when there is no
handler for its type in type_handlers on the HRepr object,
and no __hrepr__ method on obj. For an object of class 'klass',
the result is:
``<span class="hrepr-... | [
"def",
"stdrepr",
"(",
"self",
",",
"obj",
",",
"*",
",",
"cls",
"=",
"None",
",",
"tag",
"=",
"'span'",
")",
":",
"if",
"cls",
"is",
"None",
":",
"cls",
"=",
"f'hrepr-{obj.__class__.__name__}'",
"return",
"getattr",
"(",
"self",
".",
"H",
",",
"tag"... | 39.818182 | 22.181818 |
def send_no_servlet_response(self):
"""
Default response sent when no servlet is found for the requested path
"""
# Use the helper to send the error page
response = _HTTPServletResponse(self)
response.send_content(404, self._service.make_not_found_page(self.path)) | [
"def",
"send_no_servlet_response",
"(",
"self",
")",
":",
"# Use the helper to send the error page",
"response",
"=",
"_HTTPServletResponse",
"(",
"self",
")",
"response",
".",
"send_content",
"(",
"404",
",",
"self",
".",
"_service",
".",
"make_not_found_page",
"(",
... | 43.714286 | 13.428571 |
def _mems_updated_cb(self):
"""Called when the memories have been identified"""
logger.info('Memories finished updating')
self.param.refresh_toc(self._param_toc_updated_cb, self._toc_cache) | [
"def",
"_mems_updated_cb",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'Memories finished updating'",
")",
"self",
".",
"param",
".",
"refresh_toc",
"(",
"self",
".",
"_param_toc_updated_cb",
",",
"self",
".",
"_toc_cache",
")"
] | 52.5 | 14.25 |
def multihead_attention(queries,
keys,
scope="multihead_attention",
num_units=None,
num_heads=4,
dropout_rate=0,
is_training=True,
causality=False):
... | [
"def",
"multihead_attention",
"(",
"queries",
",",
"keys",
",",
"scope",
"=",
"\"multihead_attention\"",
",",
"num_units",
"=",
"None",
",",
"num_heads",
"=",
"4",
",",
"dropout_rate",
"=",
"0",
",",
"is_training",
"=",
"True",
",",
"causality",
"=",
"False"... | 38.148148 | 22.296296 |
def _launch_all(self, launchers):
"""
Launches all available launchers.
"""
for launcher in launchers:
print("== Launching %s ==" % launcher.batch_name)
launcher()
return True | [
"def",
"_launch_all",
"(",
"self",
",",
"launchers",
")",
":",
"for",
"launcher",
"in",
"launchers",
":",
"print",
"(",
"\"== Launching %s ==\"",
"%",
"launcher",
".",
"batch_name",
")",
"launcher",
"(",
")",
"return",
"True"
] | 29.125 | 9.375 |
def _add_ubridge_ethernet_connection(self, bridge_name, ethernet_interface, block_host_traffic=False):
"""
Creates a connection with an Ethernet interface in uBridge.
:param bridge_name: bridge name in uBridge
:param ethernet_interface: Ethernet interface name
:param block_host_... | [
"def",
"_add_ubridge_ethernet_connection",
"(",
"self",
",",
"bridge_name",
",",
"ethernet_interface",
",",
"block_host_traffic",
"=",
"False",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"linux\"",
")",
"and",
"block_host_traffic",
"is",
"Fa... | 63.191489 | 36.085106 |
def add_to_manifest(self, manifest):
"""
Add useful details to the manifest about this service
so that it can be used in an application.
:param manifest: An predix.admin.app.Manifest object
instance that manages reading/writing manifest config
for a cloud foundry... | [
"def",
"add_to_manifest",
"(",
"self",
",",
"manifest",
")",
":",
"# Add this service to list of services",
"manifest",
".",
"add_service",
"(",
"self",
".",
"service",
".",
"name",
")",
"# Add environment variable to manifest",
"varname",
"=",
"predix",
".",
"config"... | 36.388889 | 15.5 |
def import_locations(self, marker_file):
"""Parse Xearth data files.
``import_locations()`` returns a dictionary with keys containing the
xearth_ name, and values consisting of a :class:`Xearth` object and
a string containing any comment found in the marker file.
It expects Xea... | [
"def",
"import_locations",
"(",
"self",
",",
"marker_file",
")",
":",
"self",
".",
"_marker_file",
"=",
"marker_file",
"data",
"=",
"utils",
".",
"prepare_read",
"(",
"marker_file",
")",
"for",
"line",
"in",
"data",
":",
"line",
"=",
"line",
".",
"strip",
... | 39.921569 | 23.019608 |
def getuser(self, user_id):
"""
Get info for a user identified by id
:param user_id: id of the user
:return: False if not found, a dictionary if found
"""
request = requests.get(
'{0}/{1}'.format(self.users_url, user_id),
headers=self.headers, ver... | [
"def",
"getuser",
"(",
"self",
",",
"user_id",
")",
":",
"request",
"=",
"requests",
".",
"get",
"(",
"'{0}/{1}'",
".",
"format",
"(",
"self",
".",
"users_url",
",",
"user_id",
")",
",",
"headers",
"=",
"self",
".",
"headers",
",",
"verify",
"=",
"se... | 31.8 | 16.466667 |
def filter_string(self, word):
"""Return a string like the input but containing only legal IPA segments
Args:
word (unicode): input string to be filtered
Returns:
unicode: string identical to `word` but with invalid IPA segments
absent
"""
... | [
"def",
"filter_string",
"(",
"self",
",",
"word",
")",
":",
"segs",
"=",
"[",
"m",
".",
"group",
"(",
"0",
")",
"for",
"m",
"in",
"self",
".",
"seg_regex",
".",
"finditer",
"(",
"word",
")",
"]",
"return",
"''",
".",
"join",
"(",
"segs",
")"
] | 31 | 21.846154 |
def calc(self, *args, **kwargs):
"""
:type args: list[DataFrame]
"""
cases = kwargs.pop('_cases', [])
if not isinstance(cases, Iterable):
cases = [cases, ]
result_callback = kwargs.pop('_result_callback', None)
execute_now = kwargs.pop('execute_now', T... | [
"def",
"calc",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cases",
"=",
"kwargs",
".",
"pop",
"(",
"'_cases'",
",",
"[",
"]",
")",
"if",
"not",
"isinstance",
"(",
"cases",
",",
"Iterable",
")",
":",
"cases",
"=",
"[",
"ca... | 34.827586 | 19.862069 |
def oauth_client_create(self, name, redirect_uri, **kwargs):
"""
Make a new OAuth Client and return it
"""
params = {
"label": name,
"redirect_uri": redirect_uri,
}
params.update(kwargs)
result = self.client.post('/account/oauth-clients', ... | [
"def",
"oauth_client_create",
"(",
"self",
",",
"name",
",",
"redirect_uri",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"\"label\"",
":",
"name",
",",
"\"redirect_uri\"",
":",
"redirect_uri",
",",
"}",
"params",
".",
"update",
"(",
"kwargs",
... | 30.555556 | 20.444444 |
def format_x_tick(axis,
major_locator=None,
major_formatter=None,
minor_locator=None,
minor_formatter=None):
"""Set x axis's format.
This method is designed for time axis.
**中文文档**
设置X轴格式。
"""
if major_locator:
ax... | [
"def",
"format_x_tick",
"(",
"axis",
",",
"major_locator",
"=",
"None",
",",
"major_formatter",
"=",
"None",
",",
"minor_locator",
"=",
"None",
",",
"minor_formatter",
"=",
"None",
")",
":",
"if",
"major_locator",
":",
"axis",
".",
"xaxis",
".",
"set_major_l... | 28.192308 | 17.115385 |
def _transform_selected(X, transform, selected, copy=True):
"""Apply a transform function to portion of selected features.
Parameters
----------
X : array-like or sparse matrix, shape=(n_samples, n_features)
Dense array or sparse matrix.
transform : callable
A callable transform(X)... | [
"def",
"_transform_selected",
"(",
"X",
",",
"transform",
",",
"selected",
",",
"copy",
"=",
"True",
")",
":",
"if",
"selected",
"==",
"\"all\"",
":",
"return",
"transform",
"(",
"X",
")",
"if",
"len",
"(",
"selected",
")",
"==",
"0",
":",
"return",
... | 28.651163 | 21.837209 |
def stop(self):
"""Stop the timer."""
if self._t0 is None:
raise RuntimeError('Timer not started.')
self._time += self._get_time()
self._t0 = None | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"_t0",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'Timer not started.'",
")",
"self",
".",
"_time",
"+=",
"self",
".",
"_get_time",
"(",
")",
"self",
".",
"_t0",
"=",
"None"
] | 23.125 | 18.5 |
def notify(self, state, notifications):
'''
Call this to schedule sending partner notification.
'''
def do_append(desc, notifications):
for notification in notifications:
if not isinstance(notification, PendingNotification):
raise ValueErr... | [
"def",
"notify",
"(",
"self",
",",
"state",
",",
"notifications",
")",
":",
"def",
"do_append",
"(",
"desc",
",",
"notifications",
")",
":",
"for",
"notification",
"in",
"notifications",
":",
"if",
"not",
"isinstance",
"(",
"notification",
",",
"PendingNotif... | 46.705882 | 23.058824 |
def to_local(self, dt):
"""Convert any timestamp to local time (with tzinfo)."""
if dt.tzinfo is None:
dt = dt.replace(tzinfo=self.utc)
return dt.astimezone(self.local) | [
"def",
"to_local",
"(",
"self",
",",
"dt",
")",
":",
"if",
"dt",
".",
"tzinfo",
"is",
"None",
":",
"dt",
"=",
"dt",
".",
"replace",
"(",
"tzinfo",
"=",
"self",
".",
"utc",
")",
"return",
"dt",
".",
"astimezone",
"(",
"self",
".",
"local",
")"
] | 40 | 6.4 |
def directory(cls, prefix=None):
"""
Path that should be used for caching. Different for all subclasses.
"""
prefix = prefix or utility.read_config().directory
name = cls.__name__.lower()
directory = os.path.expanduser(os.path.join(prefix, name))
utility.ensure_di... | [
"def",
"directory",
"(",
"cls",
",",
"prefix",
"=",
"None",
")",
":",
"prefix",
"=",
"prefix",
"or",
"utility",
".",
"read_config",
"(",
")",
".",
"directory",
"name",
"=",
"cls",
".",
"__name__",
".",
"lower",
"(",
")",
"directory",
"=",
"os",
".",
... | 39.444444 | 12.333333 |
def read_classification_results(storage_client, file_path):
"""Reads classification results from the file in Cloud Storage.
This method reads file with classification results produced by running
defense on singe batch of adversarial images.
Args:
storage_client: instance of CompetitionStorageClient or Non... | [
"def",
"read_classification_results",
"(",
"storage_client",
",",
"file_path",
")",
":",
"if",
"storage_client",
":",
"# file on Cloud",
"success",
"=",
"False",
"retry_count",
"=",
"0",
"while",
"retry_count",
"<",
"4",
":",
"try",
":",
"blob",
"=",
"storage_cl... | 29.157895 | 21.438596 |
def to_json_file(file, data, pretty):
"""
Writes object instance in JSON formatted String to file
:param file: File to write JSON string ot
:param data: Object to convert to JSON
:param pretty: Use pretty formatting or not
"""
json_string = to_json(data, pretty)
file_utils.write_to... | [
"def",
"to_json_file",
"(",
"file",
",",
"data",
",",
"pretty",
")",
":",
"json_string",
"=",
"to_json",
"(",
"data",
",",
"pretty",
")",
"file_utils",
".",
"write_to_file",
"(",
"file",
",",
"json_string",
")"
] | 33.5 | 8.1 |
def export(self, node):
"""Export tree starting at `node`."""
attriter = self.attriter or (lambda attr_values: attr_values)
return self.__export(node, self.dictcls, attriter, self.childiter) | [
"def",
"export",
"(",
"self",
",",
"node",
")",
":",
"attriter",
"=",
"self",
".",
"attriter",
"or",
"(",
"lambda",
"attr_values",
":",
"attr_values",
")",
"return",
"self",
".",
"__export",
"(",
"node",
",",
"self",
".",
"dictcls",
",",
"attriter",
",... | 52.75 | 20 |
def _close_received(self, error):
"""Callback called when a connection CLOSE frame is received.
This callback will process the received CLOSE error to determine if
the connection is recoverable or whether it should be shutdown.
:param error: The error information from the close
... | [
"def",
"_close_received",
"(",
"self",
",",
"error",
")",
":",
"if",
"error",
":",
"condition",
"=",
"error",
".",
"condition",
"description",
"=",
"error",
".",
"description",
"info",
"=",
"error",
".",
"info",
"else",
":",
"condition",
"=",
"b\"amqp:unkn... | 47.157895 | 19.894737 |
def GetView(self, viewname):
"""Get Info on View Name
"""
# Build Request
soap_request = soap('GetView')
soap_request.add_parameter('listName', self.listName)
if viewname == None:
views = self.GetViewCollection()
for view in views:
... | [
"def",
"GetView",
"(",
"self",
",",
"viewname",
")",
":",
"# Build Request",
"soap_request",
"=",
"soap",
"(",
"'GetView'",
")",
"soap_request",
".",
"add_parameter",
"(",
"'listName'",
",",
"self",
".",
"listName",
")",
"if",
"viewname",
"==",
"None",
":",
... | 39.820513 | 21.025641 |
def process_module(self, node):
'''
process a module
'''
if not HAS_PYQVER:
return
minimum_version = tuple([int(x) for x in self.config.minimum_python_version.split('.')])
with open(node.path, 'r') as rfh:
for version, reasons in pyqver2.get_versi... | [
"def",
"process_module",
"(",
"self",
",",
"node",
")",
":",
"if",
"not",
"HAS_PYQVER",
":",
"return",
"minimum_version",
"=",
"tuple",
"(",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"config",
".",
"minimum_python_version",
".",
"split",
... | 38.75 | 20.5 |
def _set_desc(self):
"""Sets the global description if any"""
# TODO: manage different in/out styles
if self.docs['in']['desc']:
self.docs['out']['desc'] = self.docs['in']['desc']
else:
self.docs['out']['desc'] = '' | [
"def",
"_set_desc",
"(",
"self",
")",
":",
"# TODO: manage different in/out styles",
"if",
"self",
".",
"docs",
"[",
"'in'",
"]",
"[",
"'desc'",
"]",
":",
"self",
".",
"docs",
"[",
"'out'",
"]",
"[",
"'desc'",
"]",
"=",
"self",
".",
"docs",
"[",
"'in'"... | 37.857143 | 11.571429 |
def build_markdown_body(self, text):
"""Generate the body for the Markdown file.
- processes each json block one by one
- for each block, process:
- the creator of the notebook (user)
- the date the notebook was created
- the date the notebook was last update... | [
"def",
"build_markdown_body",
"(",
"self",
",",
"text",
")",
":",
"key_options",
"=",
"{",
"'dateCreated'",
":",
"self",
".",
"process_date_created",
",",
"'dateUpdated'",
":",
"self",
".",
"process_date_updated",
",",
"'title'",
":",
"self",
".",
"process_title... | 35.678571 | 12.678571 |
def parse(parse_obj, agent=None, etag=None, modified=None, inject=False):
"""Parse a subscription list and return a dict containing the results.
:param parse_obj: A file-like object or a string containing a URL, an
absolute or relative filename, or an XML document.
:type parse_obj: str or file
... | [
"def",
"parse",
"(",
"parse_obj",
",",
"agent",
"=",
"None",
",",
"etag",
"=",
"None",
",",
"modified",
"=",
"None",
",",
"inject",
"=",
"False",
")",
":",
"guarantees",
"=",
"common",
".",
"SuperDict",
"(",
"{",
"'bozo'",
":",
"0",
",",
"'feeds'",
... | 37.824324 | 19.972973 |
def cmd_gyrocal(self, args):
'''do a full gyro calibration'''
mav = self.master
mav.mav.command_long_send(mav.target_system, mav.target_component,
mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, 0,
1, 0, 0, 0, 0, 0, 0) | [
"def",
"cmd_gyrocal",
"(",
"self",
",",
"args",
")",
":",
"mav",
"=",
"self",
".",
"master",
"mav",
".",
"mav",
".",
"command_long_send",
"(",
"mav",
".",
"target_system",
",",
"mav",
".",
"target_component",
",",
"mavutil",
".",
"mavlink",
".",
"MAV_CMD... | 50.666667 | 19.666667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.