text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def manifest(request, form): ''' Produces the registration manifest for people with the given product type. ''' products = form.cleaned_data["product"] categories = form.cleaned_data["category"] line_items = ( Q(lineitem__product__in=products) | Q(lineitem__product__categor...
[ "def", "manifest", "(", "request", ",", "form", ")", ":", "products", "=", "form", ".", "cleaned_data", "[", "\"product\"", "]", "categories", "=", "form", ".", "cleaned_data", "[", "\"category\"", "]", "line_items", "=", "(", "Q", "(", "lineitem__product__i...
27.580247
20.024691
def dumps(self): """Override the default to avoid duplicate dump.""" return [self.__class__.__name__.lower(), [x.dumps() for x in self.ts]]
[ "def", "dumps", "(", "self", ")", ":", "return", "[", "self", ".", "__class__", ".", "__name__", ".", "lower", "(", ")", ",", "[", "x", ".", "dumps", "(", ")", "for", "x", "in", "self", ".", "ts", "]", "]" ]
51
20.666667
def install_package(self, name, index=None, force=False, update=False): """Install a given package. Args: name (str): The package name to install. This can be any valid pip package specification. index (str): The URL for a pypi index to use. force (bo...
[ "def", "install_package", "(", "self", ",", "name", ",", "index", "=", "None", ",", "force", "=", "False", ",", "update", "=", "False", ")", ":", "cmd", "=", "'install'", "if", "force", ":", "cmd", "=", "'{0} {1}'", ".", "format", "(", "cmd", ",", ...
31
25.083333
def adjust_prior(self,index,prior): """ Adjusts priors for the latent variables Parameters ---------- index : int or list[int] Which latent variable index/indices to be altered prior : Prior object Which prior distribution? E.g. Normal(0,1) Retu...
[ "def", "adjust_prior", "(", "self", ",", "index", ",", "prior", ")", ":", "if", "isinstance", "(", "index", ",", "list", ")", ":", "for", "item", "in", "index", ":", "if", "item", "<", "0", "or", "item", ">", "(", "len", "(", "self", ".", "z_list...
45.171429
26.257143
def add_virtual_columns_equatorial_to_galactic_cartesian(self, alpha, delta, distance, xname, yname, zname, radians=True, alpha_gp=np.radians(192.85948), delta_gp=np.radians(27.12825), l_omega=np.radians(32.93192)): """From http://arxiv.org/pdf/1306.2945v2.pdf""" if not radians: alpha = "pi/180.*%s" % a...
[ "def", "add_virtual_columns_equatorial_to_galactic_cartesian", "(", "self", ",", "alpha", ",", "delta", ",", "distance", ",", "xname", ",", "yname", ",", "zname", ",", "radians", "=", "True", ",", "alpha_gp", "=", "np", ".", "radians", "(", "192.85948", ")", ...
98.625
64.5
def archive(self): """Store model output to laboratory archive.""" # Traverse the model directory deleting symlinks, zero length files # and empty directories for path, dirs, files in os.walk(self.work_path, topdown=False): for f_name in files: f_path = os.pa...
[ "def", "archive", "(", "self", ")", ":", "# Traverse the model directory deleting symlinks, zero length files", "# and empty directories", "for", "path", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "self", ".", "work_path", ",", "topdown", "=", "False",...
43.083333
17.166667
def load_imgs(filenames, masker, nan_to_num=True): """ Load multiple images from file into an ndarray. Args: filenames: A single filename or list of filenames pointing to valid images. masker: A Masker instance. nan_to_num: Optional boolean indicating whether to convert NaNs to zero. ...
[ "def", "load_imgs", "(", "filenames", ",", "masker", ",", "nan_to_num", "=", "True", ")", ":", "if", "isinstance", "(", "filenames", ",", "string_types", ")", ":", "filenames", "=", "[", "filenames", "]", "data", "=", "np", ".", "zeros", "(", "(", "mas...
35.052632
18.631579
def init_check_window(self): """ initiates the object that will control steps 1-6 of checking headers, filling in cell values, etc. """ self.check_dia = pmag_er_magic_dialogs.ErMagicCheckFrame3(self, 'Check Data', ...
[ "def", "init_check_window", "(", "self", ")", ":", "self", ".", "check_dia", "=", "pmag_er_magic_dialogs", ".", "ErMagicCheckFrame3", "(", "self", ",", "'Check Data'", ",", "self", ".", "WD", ",", "self", ".", "contribution", ")" ]
48.714286
20.428571
def refresh(self): """ Updates the current line decoration """ if self.enabled: self._clear_deco() if self._color: color = self._color else: color = drift_color(self.editor.background, 110) brush = QtGui.QBru...
[ "def", "refresh", "(", "self", ")", ":", "if", "self", ".", "enabled", ":", "self", ".", "_clear_deco", "(", ")", "if", "self", ".", "_color", ":", "color", "=", "self", ".", "_color", "else", ":", "color", "=", "drift_color", "(", "self", ".", "ed...
36.333333
12.2
def native_projection_explanation(ax): """Example showing how the "native" longitude and latitude relate to the stereonet projection.""" ax.set_title('Longitude and Latitude', size=18, y=1.1) # Hide the azimuth labels ax.set_azimuth_ticklabels([]) # Make the axis tick labels visible: ax.se...
[ "def", "native_projection_explanation", "(", "ax", ")", ":", "ax", ".", "set_title", "(", "'Longitude and Latitude'", ",", "size", "=", "18", ",", "y", "=", "1.1", ")", "# Hide the azimuth labels", "ax", ".", "set_azimuth_ticklabels", "(", "[", "]", ")", "# Ma...
28.125
17.25
def resolve(self, definitions): """ Resolve named references to other WSDL objects. This includes cross-linking information (from) the portType (to) the I{soap} protocol information on the binding for each operation. @param definitions: A definitions object. @type defini...
[ "def", "resolve", "(", "self", ",", "definitions", ")", ":", "self", ".", "resolveport", "(", "definitions", ")", "for", "op", "in", "self", ".", "operations", ".", "values", "(", ")", ":", "self", ".", "resolvesoapbody", "(", "definitions", ",", "op", ...
43.846154
10.153846
def idle_task(self): '''run periodic tasks''' now = time.time() if now - self.last_chan_check >= 1: self.last_chan_check = now self.update_channels()
[ "def", "idle_task", "(", "self", ")", ":", "now", "=", "time", ".", "time", "(", ")", "if", "now", "-", "self", ".", "last_chan_check", ">=", "1", ":", "self", ".", "last_chan_check", "=", "now", "self", ".", "update_channels", "(", ")" ]
32
9
def _ParseDateTimeValue(self, byte_stream, file_offset): """Parses a CUPS IPP RFC2579 date-time value from a byte stream. Args: byte_stream (bytes): byte stream. file_offset (int): offset of the attribute data relative to the start of the file-like object. Returns: dfdatetime.R...
[ "def", "_ParseDateTimeValue", "(", "self", ",", "byte_stream", ",", "file_offset", ")", ":", "datetime_value_map", "=", "self", ".", "_GetDataTypeMap", "(", "'cups_ipp_datetime_value'", ")", "try", ":", "value", "=", "self", ".", "_ReadStructureFromByteStream", "(",...
39.666667
23.1
def null_technical_500_response(request, exc_type, exc_value, tb, status_code=500): """ Alternative function for django.views.debug.technical_500_response. Django's convert_exception_to_response() wrapper is called on each 'Middleware' object to avoid leaking exceptions. If an uncaught exception is rai...
[ "def", "null_technical_500_response", "(", "request", ",", "exc_type", ",", "exc_value", ",", "tb", ",", "status_code", "=", "500", ")", ":", "try", ":", "# Store the most recent tb for WSGI requests. The class can be found in the second frame of the tb", "if", "isinstance", ...
51.37037
34.037037
def is_on(self): """ Get sensor state. Assume offline or open (worst case). """ if self._type == 'Occupancy': return self.status not in CONST.STATUS_ONLINE return self.status not in (CONST.STATUS_OFF, CONST.STATUS_OFFLINE, C...
[ "def", "is_on", "(", "self", ")", ":", "if", "self", ".", "_type", "==", "'Occupancy'", ":", "return", "self", ".", "status", "not", "in", "CONST", ".", "STATUS_ONLINE", "return", "self", ".", "status", "not", "in", "(", "CONST", ".", "STATUS_OFF", ","...
33
15.2
def pad_array(v, idx): """Expand lists in multidimensional arrays to pad unset values.""" i_v, i_s = idx[0] if len(idx) > 1: # Append missing subarrays v.extend([[] for _ in range(len(v), i_v - i_s + 1)]) # Pad elements for e in v: pad_array(e, idx[1:]) else...
[ "def", "pad_array", "(", "v", ",", "idx", ")", ":", "i_v", ",", "i_s", "=", "idx", "[", "0", "]", "if", "len", "(", "idx", ")", ">", "1", ":", "# Append missing subarrays", "v", ".", "extend", "(", "[", "[", "]", "for", "_", "in", "range", "(",...
28.615385
20.153846
def clear(self): """ Clears out the widgets from this stack. """ for i in range(self.count() - 1, -1, -1): w = self.widget(i) if w: self.removeWidget(w) w.close() w.deleteLater()
[ "def", "clear", "(", "self", ")", ":", "for", "i", "in", "range", "(", "self", ".", "count", "(", ")", "-", "1", ",", "-", "1", ",", "-", "1", ")", ":", "w", "=", "self", ".", "widget", "(", "i", ")", "if", "w", ":", "self", ".", "removeW...
28.2
9.8
def prepend_status(func): """Prepends the output of `func` with the status.""" @ft.wraps(func) def wrapper(self, *args, **kwargs): """Wrapper stub.""" res = func(self, *args, **kwargs) if self.status is not StepResult.UNSET: res = "[{status}]".format(status=self.status.n...
[ "def", "prepend_status", "(", "func", ")", ":", "@", "ft", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Wrapper stub.\"\"\"", "res", "=", "func", "(", "self", ",", "*", "...
29.833333
16.416667
def remove_outcome(self, outcome_id, force=False, destroy=True): """Overwrites the remove_outcome method of the State class. Prevents user from removing a outcome from the library state. For further documentation, look at the State class. :raises exceptions.NotImplementedError: in any ...
[ "def", "remove_outcome", "(", "self", ",", "outcome_id", ",", "force", "=", "False", ",", "destroy", "=", "True", ")", ":", "if", "force", ":", "return", "State", ".", "remove_outcome", "(", "self", ",", "outcome_id", ",", "force", ",", "destroy", ")", ...
45
24.5
def start_import(self, version_id=None): """ Starts importing this draft layerversion (cancelling any running import), even if the data object hasn’t changed from the previous version. :raises Conflict: if this version is already published. """ if not version_id: ...
[ "def", "start_import", "(", "self", ",", "version_id", "=", "None", ")", ":", "if", "not", "version_id", ":", "version_id", "=", "self", ".", "version", ".", "id", "target_url", "=", "self", ".", "_client", ".", "get_url", "(", "'VERSION'", ",", "'POST'"...
44.769231
23.692308
def get(msg_or_dict, key, default=_SENTINEL): """Retrieve a key's value from a protobuf Message or dictionary. Args: mdg_or_dict (Union[~google.protobuf.message.Message, Mapping]): the object. key (str): The key to retrieve from the object. default (Any): If the key is not p...
[ "def", "get", "(", "msg_or_dict", ",", "key", ",", "default", "=", "_SENTINEL", ")", ":", "# We may need to get a nested key. Resolve this.", "key", ",", "subkey", "=", "_resolve_subkeys", "(", "key", ")", "# Attempt to get the value from the two types of objects we know ab...
40.755102
23.959184
def getLastPoses(self, unRenderPoseArrayCount, unGamePoseArrayCount): """Get the last set of poses returned by WaitGetPoses.""" fn = self.function_table.getLastPoses pRenderPoseArray = TrackedDevicePose_t() pGamePoseArray = TrackedDevicePose_t() result = fn(byref(pRenderPoseArra...
[ "def", "getLastPoses", "(", "self", ",", "unRenderPoseArrayCount", ",", "unGamePoseArrayCount", ")", ":", "fn", "=", "self", ".", "function_table", ".", "getLastPoses", "pRenderPoseArray", "=", "TrackedDevicePose_t", "(", ")", "pGamePoseArray", "=", "TrackedDevicePose...
55.125
22
def write_yum_repo(content, filename='ceph.repo'): """add yum repo file in /etc/yum.repos.d/""" repo_path = os.path.join('/etc/yum.repos.d', filename) if not isinstance(content, str): content = content.decode('utf-8') write_file(repo_path, content.encode('utf-8'))
[ "def", "write_yum_repo", "(", "content", ",", "filename", "=", "'ceph.repo'", ")", ":", "repo_path", "=", "os", ".", "path", ".", "join", "(", "'/etc/yum.repos.d'", ",", "filename", ")", "if", "not", "isinstance", "(", "content", ",", "str", ")", ":", "c...
47.166667
7.166667
def param_projection(self, x_param, y_param, metric): """ Projects the grid search results onto 2 dimensions. The wrapped GridSearch object is assumed to be fit already. The display value is taken as the max over the non-displayed dimensions. Parameters ---------- ...
[ "def", "param_projection", "(", "self", ",", "x_param", ",", "y_param", ",", "metric", ")", ":", "return", "param_projection", "(", "self", ".", "estimator", ".", "cv_results_", ",", "x_param", ",", "y_param", ",", "metric", ")" ]
36.2
26.866667
def _read_cwl_record(rec): """Read CWL records, handling multiple nesting and batching cases. """ keys = set([]) out = [] if isinstance(rec, dict): is_batched = all([isinstance(v, (list, tuple)) for v in rec.values()]) cur = [{} for _ in range(len(rec.values()[0]) if is_batched else ...
[ "def", "_read_cwl_record", "(", "rec", ")", ":", "keys", "=", "set", "(", "[", "]", ")", "out", "=", "[", "]", "if", "isinstance", "(", "rec", ",", "dict", ")", ":", "is_batched", "=", "all", "(", "[", "isinstance", "(", "v", ",", "(", "list", ...
34.037037
15.259259
def p_pipeline(p): '''pipeline : pipeline BAR newline_list pipeline | pipeline BAR_AND newline_list pipeline | command''' if len(p) == 2: p[0] = [p[1]] else: p[0] = p[1] p[0].append(ast.node(kind='pipe', pipe=p[2], pos=p.lexspan(2))) p[0].exten...
[ "def", "p_pipeline", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "2", ":", "p", "[", "0", "]", "=", "[", "p", "[", "1", "]", "]", "else", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "p", "[", "0", "]", ".", "append", ...
32.7
19.1
def start(st_reg_number): """Checks the number valiaty for the Sergipe state""" divisor = 11 if len(st_reg_number) > 9: return False if len(st_reg_number) < 9: return False sum_total = 0 peso = 9 for i in range(len(st_reg_number)-1): sum_total = sum_total + int(st...
[ "def", "start", "(", "st_reg_number", ")", ":", "divisor", "=", "11", "if", "len", "(", "st_reg_number", ")", ">", "9", ":", "return", "False", "if", "len", "(", "st_reg_number", ")", "<", "9", ":", "return", "False", "sum_total", "=", "0", "peso", "...
22.333333
21.791667
def initialize_dictionaries(self, p_set): """ Initialize dictionaries with the textual inputs in the PredictorSet object p_set - PredictorSet object that has had data fed in """ success = False if not (hasattr(p_set, '_type')): error_message = "needs to be an ...
[ "def", "initialize_dictionaries", "(", "self", ",", "p_set", ")", ":", "success", "=", "False", "if", "not", "(", "hasattr", "(", "p_set", ",", "'_type'", ")", ")", ":", "error_message", "=", "\"needs to be an essay set of the train type.\"", "log", ".", "except...
42.857143
19.5
def _set_standby(self, v, load=False): """ Setter method for standby, mapped from YANG variable /ssh_sa/ssh/server/standby (container) If this variable is read-only (config: false) in the source YANG file, then _set_standby is considered as a private method. Backends looking to populate this variabl...
[ "def", "_set_standby", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base",...
71.5
33.045455
def load_scenario(self, scenario_name, **kwargs): """Load a scenario into the emulated object. Scenarios are specific states of an an object that can be customized with keyword parameters. Typical examples are: - data logger with full storage - device with low battery indi...
[ "def", "load_scenario", "(", "self", ",", "scenario_name", ",", "*", "*", "kwargs", ")", ":", "scenario", "=", "self", ".", "_known_scenarios", ".", "get", "(", "scenario_name", ")", "if", "scenario", "is", "None", ":", "raise", "ArgumentError", "(", "\"Un...
38.545455
24.045455
def download_rec(session, rec_url, target_path): """Download and extract a recorded game.""" try: resp = session.get(session.auth.base_url + rec_url) except RequestException: raise VooblyError('failed to connect for download') try: downloaded = zipfile.ZipFile(io.BytesIO(resp.con...
[ "def", "download_rec", "(", "session", ",", "rec_url", ",", "target_path", ")", ":", "try", ":", "resp", "=", "session", ".", "get", "(", "session", ".", "auth", ".", "base_url", "+", "rec_url", ")", "except", "RequestException", ":", "raise", "VooblyError...
39.25
13.833333
def itemsize(self): """ Individual item sizes """ return self._items[:self._count, 1] - self._items[:self._count, 0]
[ "def", "itemsize", "(", "self", ")", ":", "return", "self", ".", "_items", "[", ":", "self", ".", "_count", ",", "1", "]", "-", "self", ".", "_items", "[", ":", "self", ".", "_count", ",", "0", "]" ]
43.333333
18.333333
def render_registration(self): ''' Render pinned points on video frame as red rectangle. ''' surface = self.get_surface() if self.canvas is None or self.df_canvas_corners.shape[0] == 0: return surface corners = self.df_canvas_corners.copy() corners['w...
[ "def", "render_registration", "(", "self", ")", ":", "surface", "=", "self", ".", "get_surface", "(", ")", "if", "self", ".", "canvas", "is", "None", "or", "self", ".", "df_canvas_corners", ".", "shape", "[", "0", "]", "==", "0", ":", "return", "surfac...
34.24
18.16
def update(self, points, pointvol=0., rstate=None, bootstrap=0, pool=None, kdtree=None, mc_integrate=False): """ Update the radii of our balls. Parameters ---------- points : `~numpy.ndarray` with shape (npoints, ndim) The set of points to bound. ...
[ "def", "update", "(", "self", ",", "points", ",", "pointvol", "=", "0.", ",", "rstate", "=", "None", ",", "bootstrap", "=", "0", ",", "pool", "=", "None", ",", "kdtree", "=", "None", ",", "mc_integrate", "=", "False", ")", ":", "# If possible, compute ...
36.852941
21.970588
def es2et( es_fo, et_fo, ): """Convert ES to ET. Args: es_fo (file): File object for the ES file. et_fo (file): File object for the ET file. """ et_fo.write("# Mapping information for read tuples" + os.linesep) et_fo.write("#" + os.linesep) et_fo.write("# ...
[ "def", "es2et", "(", "es_fo", ",", "et_fo", ",", ")", ":", "et_fo", ".", "write", "(", "\"# Mapping information for read tuples\"", "+", "os", ".", "linesep", ")", "et_fo", ".", "write", "(", "\"#\"", "+", "os", ".", "linesep", ")", "et_fo", ".", "write"...
38.330275
21.770642
def get_asset_admin_session(self, proxy=None): """Gets an asset administration session for creating, updating and deleting assets. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.repository.AssetAdminSession) - an ``AssetAdminSession`` raise: NullArgument - ``pr...
[ "def", "get_asset_admin_session", "(", "self", ",", "proxy", "=", "None", ")", ":", "asset_lookup_session", "=", "self", ".", "_provider_manager", ".", "get_asset_lookup_session", "(", "proxy", ")", "return", "AssetAdminSession", "(", "self", ".", "_provider_manager...
46.333333
17.111111
def missing_whitespace_after_import_keyword(logical_line): r"""Multiple imports in form from x import (a, b, c) should have space between import statement and parenthesised name list. Okay: from foo import (bar, baz) E275: from foo import(bar, baz) E275: from importable.module import(bar, baz) ...
[ "def", "missing_whitespace_after_import_keyword", "(", "logical_line", ")", ":", "line", "=", "logical_line", "indicator", "=", "' import('", "if", "line", ".", "startswith", "(", "'from '", ")", ":", "found", "=", "line", ".", "find", "(", "indicator", ")", "...
37.4
12
def _dataframe_to_edge_list(df): """ Convert dataframe into list of edges, assuming that source and target ids are stored in _SRC_VID_COLUMN, and _DST_VID_COLUMN respectively. """ cols = df.columns if len(cols): assert _SRC_VID_COLUMN in cols, "Vertex DataFrame must contain column %s" % _SRC...
[ "def", "_dataframe_to_edge_list", "(", "df", ")", ":", "cols", "=", "df", ".", "columns", "if", "len", "(", "cols", ")", ":", "assert", "_SRC_VID_COLUMN", "in", "cols", ",", "\"Vertex DataFrame must contain column %s\"", "%", "_SRC_VID_COLUMN", "assert", "_DST_VID...
42.615385
29.692308
def process_der(self, data, name): """ DER processing :param data: :param name: :return: """ from cryptography.x509.base import load_der_x509_certificate try: x509 = load_der_x509_certificate(data, self.get_backend()) self.num_der_c...
[ "def", "process_der", "(", "self", ",", "data", ",", "name", ")", ":", "from", "cryptography", ".", "x509", ".", "base", "import", "load_der_x509_certificate", "try", ":", "x509", "=", "load_der_x509_certificate", "(", "data", ",", "self", ".", "get_backend", ...
33.625
19.125
async def handle_control_event(self, message): """Handle an event from the Channels layer. Channels layer callback, do not call directly. """ cmd = message[WorkerProtocol.COMMAND] logger.debug(__("Manager worker got channel command '{}'.", cmd)) # Prepare settings for u...
[ "async", "def", "handle_control_event", "(", "self", ",", "message", ")", ":", "cmd", "=", "message", "[", "WorkerProtocol", ".", "COMMAND", "]", "logger", ".", "debug", "(", "__", "(", "\"Manager worker got channel command '{}'.\"", ",", "cmd", ")", ")", "# P...
46.818182
23.984848
def fstab(jail): ''' Display contents of a fstab(5) file defined in specified jail's configuration. If no file is defined, return False. CLI Example: .. code-block:: bash salt '*' jail.fstab <jail name> ''' ret = [] config = show_config(jail) if 'fstab' in config: ...
[ "def", "fstab", "(", "jail", ")", ":", "ret", "=", "[", "]", "config", "=", "show_config", "(", "jail", ")", "if", "'fstab'", "in", "config", ":", "c_fstab", "=", "config", "[", "'fstab'", "]", "elif", "'mount.fstab'", "in", "config", ":", "c_fstab", ...
32.860465
15.186047
def wait_for_keys(self, *keys, timeout=0): """Waits until one of the specified keys was pressed, and returns which key was pressed. :param keys: iterable of integers of pygame-keycodes, or simply multiple keys passed via multiple arguments :type keys: iterable :par...
[ "def", "wait_for_keys", "(", "self", ",", "*", "keys", ",", "timeout", "=", "0", ")", ":", "if", "len", "(", "keys", ")", "==", "1", "and", "_is_iterable", "(", "keys", "[", "0", "]", ")", ":", "keys", "=", "keys", "[", "0", "]", "return", "sel...
39.352941
21.294118
def spawn(cls, executable, args, path, env, spawnProcess=None): """ Run an executable with some arguments in the given working directory with the given environment variables. Returns a Deferred which fires with a two-tuple of (exit status, output list) if the process terminates ...
[ "def", "spawn", "(", "cls", ",", "executable", ",", "args", ",", "path", ",", "env", ",", "spawnProcess", "=", "None", ")", ":", "d", "=", "defer", ".", "Deferred", "(", ")", "proto", "=", "cls", "(", "d", ",", "filepath", ".", "FilePath", "(", "...
40
20
def shiftx_image2d_flux(image2d_orig, xoffset): """Resample 2D image using a shift in the x direction (flux is preserved). Parameters ---------- image2d_orig : numpy array 2D image to be resampled. xoffset : float Offset to be applied. Returns ------- image2d_resampled ...
[ "def", "shiftx_image2d_flux", "(", "image2d_orig", ",", "xoffset", ")", ":", "if", "image2d_orig", ".", "ndim", "==", "1", ":", "naxis1", "=", "image2d_orig", ".", "size", "elif", "image2d_orig", ".", "ndim", "==", "2", ":", "naxis2", ",", "naxis1", "=", ...
28.806452
16.516129
def serialize_elements(document, elements, options=None): """Serialize list of elements into HTML string. :Args: - document (:class:`ooxml.doc.Document`): Document object - elements (list): List of elements - options (dict): Optional dictionary with :class:`Context` options :Returns: ...
[ "def", "serialize_elements", "(", "document", ",", "elements", ",", "options", "=", "None", ")", ":", "ctx", "=", "Context", "(", "document", ",", "options", ")", "tree_root", "=", "root", "=", "etree", ".", "Element", "(", "'div'", ")", "for", "elem", ...
29.84
24.32
def _get_col_epsg(mapped_class, geom_attr): """Get the EPSG code associated with a geometry attribute. Arguments: geom_attr the key of the geometry property as defined in the SQLAlchemy mapper. If you use ``declarative_base`` this is the name of the geometry attribute as defined i...
[ "def", "_get_col_epsg", "(", "mapped_class", ",", "geom_attr", ")", ":", "col", "=", "class_mapper", "(", "mapped_class", ")", ".", "get_property", "(", "geom_attr", ")", ".", "columns", "[", "0", "]", "return", "col", ".", "type", ".", "srid" ]
33.230769
23.153846
def doubleClick(x=None, y=None, interval=0.0, button='left', duration=0.0, tween=linear, pause=None, _pause=True): """Performs a double click. This is a wrapper function for click('left', x, y, 2, interval). The x and y parameters detail where the mouse event happens. If None, the current mouse positi...
[ "def", "doubleClick", "(", "x", "=", "None", ",", "y", "=", "None", ",", "interval", "=", "0.0", ",", "button", "=", "'left'", ",", "duration", "=", "0.0", ",", "tween", "=", "linear", ",", "pause", "=", "None", ",", "_pause", "=", "True", ")", "...
40.232558
27.348837
def DeserializeUnsigned(self, reader): """ Deserialize unsigned data only. Args: reader (neo.IO.BinaryReader): """ self.Version = reader.ReadUInt32() self.PrevHash = reader.ReadUInt256() self.MerkleRoot = reader.ReadUInt256() self.Timestamp = ...
[ "def", "DeserializeUnsigned", "(", "self", ",", "reader", ")", ":", "self", ".", "Version", "=", "reader", ".", "ReadUInt32", "(", ")", "self", ".", "PrevHash", "=", "reader", ".", "ReadUInt256", "(", ")", "self", ".", "MerkleRoot", "=", "reader", ".", ...
33.285714
7.428571
def run(self, writer, reader): """ Pager entry point. In interactive mode (terminal is a tty), run until ``process_keystroke()`` detects quit keystroke ('q'). In non-interactive mode, exit after displaying all unicode points. :param writer: callable writes to output st...
[ "def", "run", "(", "self", ",", "writer", ",", "reader", ")", ":", "self", ".", "_page_data", "=", "self", ".", "initialize_page_data", "(", ")", "self", ".", "_set_lastpage", "(", ")", "if", "not", "self", ".", "term", ".", "is_a_tty", ":", "self", ...
37.4
17.7
def drain_D(self): """ Returns depth of drain pipe. :returns: Depth :return: float """ tank_A = 2 * self.channel_L * self.channel_W drain_D = (np.sqrt(8 * tank_A / (np.pi * self.drain_t) * np.sqrt( self.downstream_H * self.drain_K / (2 * u.standard_gravity))))....
[ "def", "drain_D", "(", "self", ")", ":", "tank_A", "=", "2", "*", "self", ".", "channel_L", "*", "self", ".", "channel_W", "drain_D", "=", "(", "np", ".", "sqrt", "(", "8", "*", "tank_A", "/", "(", "np", ".", "pi", "*", "self", ".", "drain_t", ...
38.888889
18.777778
def _restore_auto_increment(self, table): """restore the auto increment value for the table to what it was previously""" query, seq_table, seq_column, seq_name = self._get_auto_increment_info(table) if query: queries = [query, "select nextval('{}')".format(seq_name)] retu...
[ "def", "_restore_auto_increment", "(", "self", ",", "table", ")", ":", "query", ",", "seq_table", ",", "seq_column", ",", "seq_name", "=", "self", ".", "_get_auto_increment_info", "(", "table", ")", "if", "query", ":", "queries", "=", "[", "query", ",", "\...
57.333333
17.333333
def spanstring2tokens(docgraph, span_string): """ Converts a span string (e.g. 'word_88..word_91') into a list of token IDs (e.g. ['word_88', 'word_89', 'word_90', 'word_91']. Token IDs that do not occur in the given document graph will be filtered out. Q: Why are some token IDs missing in a docume...
[ "def", "spanstring2tokens", "(", "docgraph", ",", "span_string", ")", ":", "tokens", "=", "convert_spanstring", "(", "span_string", ")", "existing_nodes", "=", "set", "(", "docgraph", ".", "nodes", "(", ")", ")", "existing_tokens", "=", "[", "]", "for", "tok...
42
21.348837
def add_auth(self, req, **kwargs): """ Add AWS3 authentication to a request. :type req: :class`boto.connection.HTTPRequest` :param req: The HTTPRequest object. """ # This could be a retry. Make sure the previous # authorization header is removed first. i...
[ "def", "add_auth", "(", "self", ",", "req", ",", "*", "*", "kwargs", ")", ":", "# This could be a retry. Make sure the previous", "# authorization header is removed first.", "if", "'X-Amzn-Authorization'", "in", "req", ".", "headers", ":", "del", "req", ".", "headers...
46.272727
13.272727
def cli(env, volume_id, new_size, new_iops, new_tier): """Modify an existing file storage volume.""" file_manager = SoftLayer.FileStorageManager(env.client) if new_tier is not None: new_tier = float(new_tier) try: order = file_manager.order_modified_volume( volume_id, ...
[ "def", "cli", "(", "env", ",", "volume_id", ",", "new_size", ",", "new_iops", ",", "new_tier", ")", ":", "file_manager", "=", "SoftLayer", ".", "FileStorageManager", "(", "env", ".", "client", ")", "if", "new_tier", "is", "not", "None", ":", "new_tier", ...
35.304348
20.043478
def _getSortKey(self, planet): """ Takes a planet and turns it into a key to be sorted by :param planet: :return: """ value = eval('planet.'+self._planetProperty) # TODO some sort of data validation, either before or using try except if self.unit is not None: ...
[ "def", "_getSortKey", "(", "self", ",", "planet", ")", ":", "value", "=", "eval", "(", "'planet.'", "+", "self", ".", "_planetProperty", ")", "# TODO some sort of data validation, either before or using try except", "if", "self", ".", "unit", "is", "not", "None", ...
31.411765
22.529412
def add_matplotlib_cmaps(fail_on_import_error=True): """Add all matplotlib colormaps.""" try: from matplotlib import cm as _cm from matplotlib.cbook import mplDeprecation except ImportError: if fail_on_import_error: raise # silently fail return for na...
[ "def", "add_matplotlib_cmaps", "(", "fail_on_import_error", "=", "True", ")", ":", "try", ":", "from", "matplotlib", "import", "cm", "as", "_cm", "from", "matplotlib", ".", "cbook", "import", "mplDeprecation", "except", "ImportError", ":", "if", "fail_on_import_er...
33.608696
14.695652
def parse_comment(comment): """ Parse a comment of the form # investigation_time=50.0, imt="PGA", ... and returns it as pairs of strings: >>> parse_comment('''path=('b1',), time=50.0, imt="PGA"''') [('path', ('b1',)), ('time', 50.0), ('imt', 'PGA')] """ names, vals = [], [] pieces =...
[ "def", "parse_comment", "(", "comment", ")", ":", "names", ",", "vals", "=", "[", "]", ",", "[", "]", "pieces", "=", "comment", ".", "split", "(", "'='", ")", "for", "i", ",", "piece", "in", "enumerate", "(", "pieces", ")", ":", "if", "i", "==", ...
33.666667
9.666667
def call_alert(*args, **kwargs): ''' Lamp alert Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. * **on**: Turns on or off an alert. Default is True. CLI Example: .. code-block:: bash salt '*' hue.alert salt '*' hue.alert id=1 ...
[ "def", "call_alert", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "res", "=", "dict", "(", ")", "devices", "=", "_get_lights", "(", ")", "for", "dev_id", "in", "'id'", "not", "in", "kwargs", "and", "sorted", "(", "devices", ".", "keys", "("...
24.708333
29.208333
def _generic_io_transform(node, name, cls): """Transform the given name, by adding the given *class* as a member of the node.""" io_module = astroid.MANAGER.ast_from_module_name("_io") attribute_object = io_module[cls] instance = attribute_object.instantiate_class() node.locals[name] = [instance]
[ "def", "_generic_io_transform", "(", "node", ",", "name", ",", "cls", ")", ":", "io_module", "=", "astroid", ".", "MANAGER", ".", "ast_from_module_name", "(", "\"_io\"", ")", "attribute_object", "=", "io_module", "[", "cls", "]", "instance", "=", "attribute_ob...
44.571429
11.714286
def groupby_size(columns, column_tys, grouping_columns, grouping_column_tys): """ Groups the given columns by the corresponding grouping column value, and aggregate by summing values. Args: columns (List<WeldObject>): List of columns as WeldObjects column_tys (List<str>): List of each c...
[ "def", "groupby_size", "(", "columns", ",", "column_tys", ",", "grouping_columns", ",", "grouping_column_tys", ")", ":", "weld_obj", "=", "WeldObject", "(", "encoder_", ",", "decoder_", ")", "if", "len", "(", "grouping_columns", ")", "==", "1", "and", "len", ...
33.196721
22.04918
def run(version, quiet, no_fetch, push, **kwargs): # pragma: no cover """ A nicer `git pull`. """ if version: if NO_DISTRIBUTE: print(colored('Please install \'git-up\' via pip in order to ' 'get version information.', 'yellow')) else: ...
[ "def", "run", "(", "version", ",", "quiet", ",", "no_fetch", ",", "push", ",", "*", "*", "kwargs", ")", ":", "# pragma: no cover\r", "if", "version", ":", "if", "NO_DISTRIBUTE", ":", "print", "(", "colored", "(", "'Please install \\'git-up\\' via pip in order to...
25.62069
21.068966
def once(self, event: str, *handlers: T.Callable) -> T.Callable: """Registers one or more handlers to a specified event, but removes them when the event is first triggered. This method may as well be used as a decorator for the handler.""" def _once_wrapper(*handlers: T.Callable) -> T.C...
[ "def", "once", "(", "self", ",", "event", ":", "str", ",", "*", "handlers", ":", "T", ".", "Callable", ")", "->", "T", ".", "Callable", ":", "def", "_once_wrapper", "(", "*", "handlers", ":", "T", ".", "Callable", ")", "->", "T", ".", "Callable", ...
38.619048
16.761905
def formatException(self, record): """ Format and return the specified exception information as a string. :type record logging.LogRecord :rtype: dict """ if record.exc_info is None: return {} (exc_type, exc_message, trace) = record.exc_info r...
[ "def", "formatException", "(", "self", ",", "record", ")", ":", "if", "record", ".", "exc_info", "is", "None", ":", "return", "{", "}", "(", "exc_type", ",", "exc_message", ",", "trace", ")", "=", "record", ".", "exc_info", "return", "{", "'e'", ":", ...
31.722222
21.166667
def toolchain_spec_compile_entries( toolchain, spec, entries, process_name, overwrite_log=None): """ The standardized Toolchain Spec Entries compile function This function accepts a toolchain instance, the spec to be operated with and the entries provided for the process name. The standard ...
[ "def", "toolchain_spec_compile_entries", "(", "toolchain", ",", "spec", ",", "entries", ",", "process_name", ",", "overwrite_log", "=", "None", ")", ":", "processor", "=", "getattr", "(", "toolchain", ",", "'compile_%s_entry'", "%", "process_name", ")", "modpath_l...
39.243902
22.512195
def set_timeout(self, timeout): """ set the timeout limit. :Parameters: #. timeout (number): The maximum delay or time allowed to successfully set the lock. When timeout is exhausted before successfully setting the lock, the lock ends up not acquired. ...
[ "def", "set_timeout", "(", "self", ",", "timeout", ")", ":", "try", ":", "timeout", "=", "float", "(", "timeout", ")", "assert", "timeout", ">=", "0", "assert", "timeout", ">=", "self", ".", "__wait", "except", ":", "raise", "Exception", "(", "'timeout m...
35.4375
18.4375
def finite_difference(self, *args, **kwargs): """ Calculates a numerical approximation of the Jacobian of the model using the sixth order central finite difference method. Accepts a `dx` keyword to tune the relative stepsize used. Makes 6*n_params calls to the model. :re...
[ "def", "finite_difference", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# See also: scipy.misc.derivative. It might be convinced to work, but", "# it will make way too many function evaluations", "dx", "=", "kwargs", ".", "pop", "(", "'dx'", ")", ...
51.333333
20.126984
def get_locations(): """ Pull the accounts locations. """ arequest = requests.get(LOCATIONS_URL, headers=HEADERS) status_code = str(arequest.status_code) if status_code == '401': _LOGGER.error("Token expired.") return False return arequest....
[ "def", "get_locations", "(", ")", ":", "arequest", "=", "requests", ".", "get", "(", "LOCATIONS_URL", ",", "headers", "=", "HEADERS", ")", "status_code", "=", "str", "(", "arequest", ".", "status_code", ")", "if", "status_code", "==", "'401'", ":", "_LOGGE...
31.7
9.1
def get_json(request, token): """Return matching results as JSON""" result = [] searchtext = request.GET['q'] if len(searchtext) >= 3: pickled = _simple_autocomplete_queryset_cache.get(token, None) if pickled is not None: app_label, model_name, query = pickle.loads(pickled) ...
[ "def", "get_json", "(", "request", ",", "token", ")", ":", "result", "=", "[", "]", "searchtext", "=", "request", ".", "GET", "[", "'q'", "]", "if", "len", "(", "searchtext", ")", ">=", "3", ":", "pickled", "=", "_simple_autocomplete_queryset_cache", "."...
40.061224
15.632653
def absent(name, protocol=None, service_address=None): ''' Ensure the LVS service is absent. name The name of the LVS service protocol The service protocol service_address The LVS service address ''' ret = {'name': name, 'changes': {}, 'result...
[ "def", "absent", "(", "name", ",", "protocol", "=", "None", ",", "service_address", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", "}", "#ch...
33.825
24.725
def izscan(self, key, *, match=None, count=None): """Incrementally iterate sorted set items using async for. Usage example: >>> async for val, score in redis.izscan(key, match='something*'): ... print('Matched:', val, ':', score) """ return _ScanIter(lambda cur: se...
[ "def", "izscan", "(", "self", ",", "key", ",", "*", ",", "match", "=", "None", ",", "count", "=", "None", ")", ":", "return", "_ScanIter", "(", "lambda", "cur", ":", "self", ".", "zscan", "(", "key", ",", "cur", ",", "match", "=", "match", ",", ...
37.5
20.75
def tally(self, chain): """Store the object's current value to a chain. :Parameters: chain : integer Chain index. """ value = self._getfunc() try: self._trace[chain][self._index[chain]] = value.copy() except AttributeError: sel...
[ "def", "tally", "(", "self", ",", "chain", ")", ":", "value", "=", "self", ".", "_getfunc", "(", ")", "try", ":", "self", ".", "_trace", "[", "chain", "]", "[", "self", ".", "_index", "[", "chain", "]", "]", "=", "value", ".", "copy", "(", ")",...
25.4
19.4
def _init_relationships(self, relationships_arg): """Return a set of relationships found in all subset GO Terms.""" if relationships_arg: relationships_all = self._get_all_relationships() if relationships_arg is True: return relationships_all else: ...
[ "def", "_init_relationships", "(", "self", ",", "relationships_arg", ")", ":", "if", "relationships_arg", ":", "relationships_all", "=", "self", ".", "_get_all_relationships", "(", ")", "if", "relationships_arg", "is", "True", ":", "return", "relationships_all", "el...
44.666667
13
def parse_log(file_path): """ Parse a CISM output log and extract some information. Args: file_path: absolute path to the log file Return: A dictionary created by the elements object corresponding to the results of the bit for bit testing """ if not os.path.isfile(file_...
[ "def", "parse_log", "(", "file_path", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "file_path", ")", ":", "return", "elements", ".", "error", "(", "\"Output Log\"", ",", "\"Could not open file: \"", "+", "file_path", ".", "split", "(", "os...
38.116667
14.95
def disassociate(self, eip_or_aid): """Disassociates an EIP. If the EIP was allocated for a VPC instance, an AllocationId(aid) must be provided instead of a PublicIp. """ if "." in eip_or_aid: # If an IP is given (Classic) return "true" == self.call("Disassociat...
[ "def", "disassociate", "(", "self", ",", "eip_or_aid", ")", ":", "if", "\".\"", "in", "eip_or_aid", ":", "# If an IP is given (Classic)", "return", "\"true\"", "==", "self", ".", "call", "(", "\"DisassociateAddress\"", ",", "response_data_key", "=", "\"return\"", ...
59.166667
19.333333
def get_sequence_lengths(fastafilenames): """Returns dictionary of sequence lengths, keyed by organism. Biopython's SeqIO module is used to parse all sequences in the FASTA file corresponding to each organism, and the total base count in each is obtained. NOTE: ambiguity symbols are not discounted...
[ "def", "get_sequence_lengths", "(", "fastafilenames", ")", ":", "tot_lengths", "=", "{", "}", "for", "fn", "in", "fastafilenames", ":", "tot_lengths", "[", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "split", "(", "fn", ")", "[", "...
37
19.428571
def open_resource(source): """ Opens a resource in binary reading mode. Wraps the resource with a context manager when it doesn't have one. :param source: a filepath or an URL. """ try: return open(source, mode='rb') except (IOError, OSError) as err: try: resourc...
[ "def", "open_resource", "(", "source", ")", ":", "try", ":", "return", "open", "(", "source", ",", "mode", "=", "'rb'", ")", "except", "(", "IOError", ",", "OSError", ")", "as", "err", ":", "try", ":", "resource", "=", "urlopen", "(", "source", ")", ...
29.64
15.24
def invite(self, channel, nick): """ Invite someone to a channel. Required arguments: * channel - Channel to invite them to. * nick - Nick to invite. """ with self.lock: self.is_in_channel(channel) self.send('INVITE %s %s' % (nick, channel...
[ "def", "invite", "(", "self", ",", "channel", ",", "nick", ")", ":", "with", "self", ".", "lock", ":", "self", ".", "is_in_channel", "(", "channel", ")", "self", ".", "send", "(", "'INVITE %s %s'", "%", "(", "nick", ",", "channel", ")", ")", "while",...
32.1
14
def verify_user(self): """Verify if the changeset was made by a inexperienced mapper (anyone with less than 5 edits) or by a user that was blocked more than once. """ user_reasons = get_user_details(self.uid) [self.label_suspicious(reason) for reason in user_reasons]
[ "def", "verify_user", "(", "self", ")", ":", "user_reasons", "=", "get_user_details", "(", "self", ".", "uid", ")", "[", "self", ".", "label_suspicious", "(", "reason", ")", "for", "reason", "in", "user_reasons", "]" ]
50.333333
15
def run_gendoc(source, dest, args): """Starts gendoc which reads source and creates rst files in dest with the given args. :param source: The python source directory for gendoc. Can be a relative path. :type source: str :param dest: The destination for the rst files. Can be a relative path. :type d...
[ "def", "run_gendoc", "(", "source", ",", "dest", ",", "args", ")", ":", "args", ".", "insert", "(", "0", ",", "'gendoc.py'", ")", "args", ".", "append", "(", "dest", ")", "args", ".", "append", "(", "source", ")", "print", "'Running gendoc.main with: %s'...
34.444444
19.277778
def flatten(struct): """Cleates a flat list of all items in structured output (dicts, lists, items) Examples: > _flatten({'a': foo, b: bar}) [foo, bar] > _flatten([foo, [bar, troll]]) [foo, bar, troll] > _flatten(foo) [foo] """ if struct is None: return [] flat = [] ...
[ "def", "flatten", "(", "struct", ")", ":", "if", "struct", "is", "None", ":", "return", "[", "]", "flat", "=", "[", "]", "if", "isinstance", "(", "struct", ",", "dict", ")", ":", "for", "key", ",", "result", "in", "struct", ".", "items", "(", ")"...
21.966667
18.466667
def stop(self): """Stop a task immediately. Raises: RuntimeError: If the task hasn't been started or has already been stopped. """ if self._status is TaskStatus.STOPPED: return if self._status is not TaskStatus.STARTED: raise ...
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "_status", "is", "TaskStatus", ".", "STOPPED", ":", "return", "if", "self", ".", "_status", "is", "not", "TaskStatus", ".", "STARTED", ":", "raise", "RuntimeError", "(", "\"Cannot stop %s in state %s\"...
29.352941
18.882353
def replace_parameters(context, nb, parameters): # Uma: This is a copy-paste from papermill papermill/execute.py:104 (execute_parameters). # Typically, papermill injects the injected-parameters cell *below* the parameters cell # but we want to *replace* the parameters cell, which is what this function does....
[ "def", "replace_parameters", "(", "context", ",", "nb", ",", "parameters", ")", ":", "# Uma: This is a copy-paste from papermill papermill/execute.py:104 (execute_parameters).", "# Typically, papermill injects the injected-parameters cell *below* the parameters cell", "# but we want to *repl...
44.938776
25.959184
def division_content(self, election_day, division, special=False): """ Return serialized content for a division page. """ from electionnight.models import PageType division_type = ContentType.objects.get_for_model(division) page_type = PageType.objects.get( m...
[ "def", "division_content", "(", "self", ",", "election_day", ",", "division", ",", "special", "=", "False", ")", ":", "from", "electionnight", ".", "models", "import", "PageType", "division_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", ...
36.892857
14.821429
def get_fragility_model_04(fmodel, fname): """ :param fmodel: a fragilityModel node :param fname: path of the fragility file :returns: an :class:`openquake.risklib.scientific.FragilityModel` instance """ logging.warning('Please upgrade %s to NRML 0.5', fname) node05 =...
[ "def", "get_fragility_model_04", "(", "fmodel", ",", "fname", ")", ":", "logging", ".", "warning", "(", "'Please upgrade %s to NRML 0.5'", ",", "fname", ")", "node05", "=", "convert_fragility_model_04", "(", "fmodel", ",", "fname", ")", "node05", ".", "limitStates...
35.230769
14
def get_name(principal): ''' Gets the name from the specified principal. Args: principal (str): Find the Normalized name based on this. Can be a PySID object, a SID string, or a user name in any capitalization. .. note:: Searching based on the u...
[ "def", "get_name", "(", "principal", ")", ":", "# If this is a PySID object, use it", "if", "isinstance", "(", "principal", ",", "pywintypes", ".", "SIDType", ")", ":", "sid_obj", "=", "principal", "else", ":", "# If None is passed, use the Universal Well-known SID for \"...
36.836364
23.127273
def build_wxsfile_file_section(root, files, NAME, VERSION, VENDOR, filename_set, id_set): """ Builds the Component sections of the wxs file with their included files. Files need to be specified in 8.3 format and in the long name format, long filenames will be converted automatically. Features are spec...
[ "def", "build_wxsfile_file_section", "(", "root", ",", "files", ",", "NAME", ",", "VERSION", ",", "VENDOR", ",", "filename_set", ",", "id_set", ")", ":", "root", "=", "create_default_directory_layout", "(", "root", ",", "NAME", ",", "VERSION", ",", "VENDOR", ...
41.340909
22.988636
def getAnalyses(self, **kwargs): """Returns a list of the latest root cause analysis results for a specified check. Optional Parameters: * limit -- Limits the number of returned results to the specified quantity. Type: Integer ...
[ "def", "getAnalyses", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# 'from' is a reserved word, use time_from instead", "if", "kwargs", ".", "get", "(", "'time_from'", ")", ":", "kwargs", "[", "'from'", "]", "=", "kwargs", ".", "get", "(", "'time_from'", ...
36.736842
20.701754
def make_multipart(self, content_disposition=None, content_type=None, content_location=None): """ Makes this request field into a multipart request field. This method overrides "Content-Disposition", "Content-Type" and "Content-Location" headers to the request par...
[ "def", "make_multipart", "(", "self", ",", "content_disposition", "=", "None", ",", "content_type", "=", "None", ",", "content_location", "=", "None", ")", ":", "self", ".", "headers", "[", "'Content-Disposition'", "]", "=", "content_disposition", "or", "'form-d...
39.636364
20.636364
def softmax_to_unary(sm, GT_PROB=1): """Deprecated, use `unary_from_softmax` instead.""" warning("pydensecrf.softmax_to_unary is deprecated, use unary_from_softmax instead.") scale = None if GT_PROB == 1 else GT_PROB return unary_from_softmax(sm, scale, clip=None)
[ "def", "softmax_to_unary", "(", "sm", ",", "GT_PROB", "=", "1", ")", ":", "warning", "(", "\"pydensecrf.softmax_to_unary is deprecated, use unary_from_softmax instead.\"", ")", "scale", "=", "None", "if", "GT_PROB", "==", "1", "else", "GT_PROB", "return", "unary_from_...
55.2
13.8
def calc_area_extent(self, key): """Calculate area extent for a dataset.""" # Calculate the area extent of the swath based on start line and column # information, total number of segments and channel resolution xyres = {500: 22272, 1000: 11136, 2000: 5568} chkres = xyres[key.reso...
[ "def", "calc_area_extent", "(", "self", ",", "key", ")", ":", "# Calculate the area extent of the swath based on start line and column", "# information, total number of segments and channel resolution", "xyres", "=", "{", "500", ":", "22272", ",", "1000", ":", "11136", ",", ...
48.594595
20.054054
def comb_indices(n, k): """``n``-dimensional version of itertools.combinations. Args: a (np.ndarray): The array from which to get combinations. k (int): The desired length of the combinations. Returns: np.ndarray: Indices that give the ``k``-combinations of ``n`` elements. Exa...
[ "def", "comb_indices", "(", "n", ",", "k", ")", ":", "# Count the number of combinations for preallocation", "count", "=", "comb", "(", "n", ",", "k", ",", "exact", "=", "True", ")", "# Get numpy iterable from ``itertools.combinations``", "indices", "=", "np", ".", ...
30.516129
18.774194
def convert_complex_output(out_in): """ Convert complex values in the output dictionary `out_in` to pairs of real and imaginary parts. """ out = {} for key, val in out_in.iteritems(): if val.data.dtype in complex_types: rval = copy(val) rval.data = val.data.real...
[ "def", "convert_complex_output", "(", "out_in", ")", ":", "out", "=", "{", "}", "for", "key", ",", "val", "in", "out_in", ".", "iteritems", "(", ")", ":", "if", "val", ".", "data", ".", "dtype", "in", "complex_types", ":", "rval", "=", "copy", "(", ...
24.190476
16.095238
def nac(x, depth, name=None, reuse=None): """NAC as in https://arxiv.org/abs/1808.00508.""" with tf.variable_scope(name, default_name="nac", values=[x], reuse=reuse): x_shape = shape_list(x) w = tf.get_variable("w", [x_shape[-1], depth]) m = tf.get_variable("m", [x_shape[-1], depth]) w = tf.tanh(w) ...
[ "def", "nac", "(", "x", ",", "depth", ",", "name", "=", "None", ",", "reuse", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"nac\"", ",", "values", "=", "[", "x", "]", ",", "reuse", "=", "reu...
46.7
9.8
def raise_os_error(_errno, path=None): """ Helper for raising the correct exception under Python 3 while still being able to raise the same common exception class in Python 2.7. """ msg = "%s: '%s'" % (strerror(_errno), path) if path else strerror(_errno) raise OSError(_errno, msg)
[ "def", "raise_os_error", "(", "_errno", ",", "path", "=", "None", ")", ":", "msg", "=", "\"%s: '%s'\"", "%", "(", "strerror", "(", "_errno", ")", ",", "path", ")", "if", "path", "else", "strerror", "(", "_errno", ")", "raise", "OSError", "(", "_errno",...
37.5
18.75
def find_multiplex_by_name(self, multiplex_name: str) -> Multiplex: """ Find and return a multiplex in the influence graph with the given name. Raise an AttributeError if there is no multiplex in the graph with the given name. """ for multiplex in self.multiplexes: i...
[ "def", "find_multiplex_by_name", "(", "self", ",", "multiplex_name", ":", "str", ")", "->", "Multiplex", ":", "for", "multiplex", "in", "self", ".", "multiplexes", ":", "if", "multiplex", ".", "name", "==", "multiplex_name", ":", "return", "multiplex", "raise"...
50.777778
18.888889
def abspath(rel): """ Take paths relative to the current file and convert them to absolute paths. Parameters ------------ rel : str Relative path, IE '../stuff' Returns ------------- abspath : str Absolute path, IE '/home/user/stuff' """ retu...
[ "def", "abspath", "(", "rel", ")", ":", "return", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "cwd", ",", "rel", ")", ")" ]
21.6875
17.8125
def send_email_smtp(to, subject, html_content, config, files=None, data=None, images=None, dryrun=False, cc=None, bcc=None, mime_subtype='mixed'): """ Send an email with html content, eg: send_email_smtp( 'test@example.com', 'foo', '<b>Foo</b> bar',['/dev/null...
[ "def", "send_email_smtp", "(", "to", ",", "subject", ",", "html_content", ",", "config", ",", "files", "=", "None", ",", "data", "=", "None", ",", "images", "=", "None", ",", "dryrun", "=", "False", ",", "cc", "=", "None", ",", "bcc", "=", "None", ...
32.966667
16.833333
def properties(obj): """ Returns a dictionary with one entry per attribute of the given object. The key being the attribute name and the value being the attribute value. Attributes starting in two underscores will be ignored. This function is an alternative to vars() which only returns instance vari...
[ "def", "properties", "(", "obj", ")", ":", "return", "dict", "(", "(", "attr", ",", "getattr", "(", "obj", ",", "attr", ")", ")", "for", "attr", "in", "dir", "(", "obj", ")", "if", "not", "attr", ".", "startswith", "(", "'__'", ")", ")" ]
41.333333
26.833333
def main(args=sys.argv): """Parse the arguments, and pass the config object on to run.""" # Don't make changes to sys.argv args = list(args) # Remove arg[0] args.pop(0) # Pop off the options clear_opt = False if '-c' in args: args.remove('-c') clear_opt = True elif ...
[ "def", "main", "(", "args", "=", "sys", ".", "argv", ")", ":", "# Don't make changes to sys.argv", "args", "=", "list", "(", "args", ")", "# Remove arg[0]", "args", ".", "pop", "(", "0", ")", "# Pop off the options", "clear_opt", "=", "False", "if", "'-c'", ...
23.37037
19.962963
def _CreateSingleValueCondition(self, value, operator): """Creates a single-value condition with the provided value and operator.""" if isinstance(value, str) or isinstance(value, unicode): value = '"%s"' % value return '%s %s %s' % (self._field, operator, value)
[ "def", "_CreateSingleValueCondition", "(", "self", ",", "value", ",", "operator", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", "or", "isinstance", "(", "value", ",", "unicode", ")", ":", "value", "=", "'\"%s\"'", "%", "value", "return", "...
55.4
12.2